я новичок в Android. Я строю приложение для Android, которое соединяется с локальным сервером.
используемый сервер xampp 3.2.1.
Я использовал парсер JSON, чтобы сделать грубую операцию над базой данных.
я определил класс парсера json.
Когда я начинаю свою основную деятельность, я получаю следующие ошибки (вот мой logcat для mainacctivity):
11-02 17:47:46.236: E/IMGSRV(16540): :0: PVRDRMOpen: TP3, ret = 43
11-02 17:47:46.236: E/IMGSRV(16540): :0: PVRDRMOpen: TP3, ret = 49
11-02 17:48:07.356: E/IMGSRV(16540): :0: PVRDRMOpen: TP3, ret = 43
11-02 17:48:07.356: E/IMGSRV(16540): :0: PVRDRMOpen: TP3, ret = 49
11-02 17:48:07.396: I/dalvikvm(16540): Total arena pages for JIT: 11
11-02 17:48:07.396: I/dalvikvm(16540): Total arena pages for JIT: 12
11-02 17:48:07.406: I/dalvikvm(16540): Total arena pages for JIT: 13
11-02 17:48:07.406: I/dalvikvm(16540): Total arena pages for JIT: 14
11-02 17:48:07.406: I/dalvikvm(16540): Total arena pages for JIT: 15
11-02 17:48:07.406: I/dalvikvm(16540): Total arena pages for JIT: 16
11-02 17:48:07.406: I/dalvikvm(16540): Total arena pages for JIT: 17
11-02 17:48:07.406: I/dalvikvm(16540): Total arena pages for JIT: 18
11-02 17:48:07.416: I/dalvikvm(16540): Total arena pages for JIT: 19
11-02 17:48:07.416: I/dalvikvm(16540): Total arena pages for JIT: 20
11-02 17:48:07.416: I/dalvikvm(16540): Total arena pages for JIT: 21
при регистрации активности после регистрации пользовательских полей, к сожалению, ваше приложение остановилось. вот ошибка logcat для активности регистрации.
11-02 17:51:34.176: E/JSON Parser(16540): Error parsing data org.json.JSONException: End of input at character 0 of
11-02 17:51:34.176: E/AndroidRuntime(16540): FATAL EXCEPTION: AsyncTask #4
11-02 17:51:34.176: E/AndroidRuntime(16540): java.lang.RuntimeException: An error occured while executing doInBackground()
11-02 17:51:34.176: E/AndroidRuntime(16540): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-02 17:51:34.176: E/AndroidRuntime(16540): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.lang.Thread.run(Thread.java:841)
11-02 17:51:34.176: E/AndroidRuntime(16540): Caused by: java.lang.NullPointerException
11-02 17:51:34.176: E/AndroidRuntime(16540): at com.example.ddubusmarg.SignUpActivity$CreateNewProduct.doInBackground(SignUpActivity.java:126)
11-02 17:51:34.176: E/AndroidRuntime(16540): at com.example.ddubusmarg.SignUpActivity$CreateNewProduct.doInBackground(SignUpActivity.java:1)
11-02 17:51:34.176: E/AndroidRuntime(16540): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-02 17:51:34.176: E/AndroidRuntime(16540): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-02 17:51:34.176: E/AndroidRuntime(16540): ... 4 more
11-02 17:51:34.676: E/WindowManager(16540): Activity com.example.ddubusmarg.SignUpActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{21c67e98 V.E..... R......D 0,0-684,192} that was originally added here
11-02 17:51:34.676: E/WindowManager(16540): android.view.WindowLeaked: Activity com.example.ddubusmarg.SignUpActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{21c67e98 V.E..... R......D 0,0-684,192} that was originally added here
11-02 17:51:34.676: E/WindowManager(16540): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:371)
11-02 17:51:34.676: E/WindowManager(16540): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
11-02 17:51:34.676: E/WindowManager(16540): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
11-02 17:51:34.676: E/WindowManager(16540): at android.app.Dialog.show(Dialog.java:281)
11-02 17:51:34.676: E/WindowManager(16540): at com.example.ddubusmarg.SignUpActivity$CreateNewProduct.onPreExecute(SignUpActivity.java:93)
11-02 17:51:34.676: E/WindowManager(16540): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
11-02 17:51:34.676: E/WindowManager(16540): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-02 17:51:34.676: E/WindowManager(16540): at com.example.ddubusmarg.SignUpActivity$1.onClick(SignUpActivity.java:73)
11-02 17:51:34.676: E/WindowManager(16540): at android.view.View.performClick(View.java:4401)
11-02 17:51:34.676: E/WindowManager(16540): at android.view.View$PerformClick.run(View.java:18184)
11-02 17:51:34.676: E/WindowManager(16540): at android.os.Handler.handleCallback(Handler.java:730)
11-02 17:51:34.676: E/WindowManager(16540): at android.os.Handler.dispatchMessage(Handler.java:92)
11-02 17:51:34.676: E/WindowManager(16540): at android.os.Looper.loop(Looper.java:150)
11-02 17:51:34.676: E/WindowManager(16540): at android.app.ActivityThread.main(ActivityThread.java:5390)
11-02 17:51:34.676: E/WindowManager(16540): at java.lang.reflect.Method.invokeNative(Native Method)
11-02 17:51:34.676: E/WindowManager(16540): at java.lang.reflect.Method.invoke(Method.java:525)
11-02 17:51:34.676: E/WindowManager(16540): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-02 17:51:34.676: E/WindowManager(16540): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-02 17:51:34.676: E/WindowManager(16540): at dalvik.system.NativeStart.main(Native Method)
мой ноутбук и мобильный телефон находятся в одной сети. Я подключаюсь к своему локальному серверу с IP-адресом ноутбука.
вот мой класс jsonparser:
пакет com.example.ddubusmarg;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//while ((line = reader.readLine()) != null) {
// sb.append(line + "\n");
//}
while ((line = reader.readLine()) != null)
{
if(line.startsWith("{"))
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
вот signupActivity.java:
пакет com.example.ddubusmarg;
public class SignUpActivity extends Activity implements OnItemSelectedListener {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputId;
EditText inputPassword;
EditText inputCity;
EditText inputPhoneNumber;
// url to create new product
private static String url_create_product = "http://192.168.1.6/registrationjson/insertnew.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
//spinner creation
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.boarding_city, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
// Edit Text
inputName = (EditText) findViewById(R.id.editText1); // name
inputId = (EditText) findViewById(R.id.editText2); //id
inputPassword = (EditText) findViewById(R.id.editText3); //password
//inputCity = (EditText) findViewById(R.id.spinner); boarding city
inputPhoneNumber = (EditText) findViewById(R.id.editText4); // phone number
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.button1);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUpActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
//again spinnerprotected String doInBackground(String... args) {
String name = inputName.getText().toString();
String id = inputId.getText().toString();
String password = inputPassword.getText().toString();
Spinner spinner = (Spinner) findViewById(R.id.spinner);
String city = spinner.getSelectedItem().toString();
String phoneNumber = inputPhoneNumber.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("id", id));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("city", city));
params.add(new BasicNameValuePair("phoneNumber", phoneNumber));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"GET", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}}
вот это insertnewrecord.php:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_GET['NAME']) && isset($_GET['ID']) && isset($_GET['PASSWORD']) && isset($_GET['CITY']) && isset($_GET['PHONE NUMBER']) ) {
$name = $_GET['NAME'];
$id = $_GET['ID'];
$password = $_GET['PASSWORD'];
$city = $_GET['CITY'];
$phone_number = $_GET['PHONE_NUMBER'];
// include db connect class
require_once __DIR__ . '/connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO registration(name, id, password, city, phone_number) VALUES('$name', '$id', '$password', '$city', '$phone_number')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "record successfuly inserted";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
любезно помогите.
Можно только строить догадки, не видя ваш код. Непосредственная проблема у вас есть NullPointerException
Я хотел бы начать с просмотра строки 126 SignUpActivity.java, как показано в вашей трассировке стека:
Caused by: java.lang.NullPointerException
at com.example.ddubusmarg.SignUpActivity$CreateNewProduct.doInBackground(SignUpActivity.java:126)
Других решений пока нет …