JSON:空指针异常

时间:2015-10-27 16:15:43

标签: java android mysql json

this tutorial,我收到了此错误

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,所以可能代码中出现了问题,我还没有找到它。

希望有人能帮助我弄明白我哪里做错了。谢谢。

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

我建议切换到凌空库。它最适合通过android进行所有NetworkRelated调用。它非常易于使用。

http://developer.android.com/training/volley/index.html

以下是关于如何使用排球的基本教程 http://www.androidhive.info/2014/05/android-working-with-volley-library-1/