[英]JSON: Null pointer exception
从本教程中 ,我得到了这个错误
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
它来自MainActivity.java
class AttemptLogin extends AsyncTask<String, String, String> { // <--- cause of error
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); }
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString()); // <--- cause of error
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(MainActivity.this,OtherActivity.class);
startActivity(ii);
// this finish() method is used to tell android os that we are done with current
// activity now! Moving to other activity
finish();
return json.getString(TAG_MESSAGE);
}
else{
return json.getString(TAG_MESSAGE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
**/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
已经有很多人问同样的问题,但是对于这个特定问题仍然没有答案。
这是我第一次使用JSON,因此代码中可能存在错误,但我还没有找到它。
希望有人能帮助我弄清楚我在哪里做错了。 谢谢。
我建议切换到排球库。 最适合通过android进行的所有NetworkRelated通话。 它非常易于使用。
http://developer.android.com/training/volley/index.html
以下是有关如何使用排球的基本教程http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.