尝试在空对象引用上调用虚方法'int org.json.JSONObject.getInt(java.lang.String)'

时间:2015-03-06 15:52:10

标签: java android json

我正在尝试检查phpmyadmin数据库上的用户名/ psw 但我无法弄清楚问题所在。 logcat给了我这个错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference

Java代码:

 public class MainActivity extends ActionBarActivity {

// Progress Dialog
private ProgressDialog pDialog;
private String password="";
private String userName="";



JSONParser jsonParser = new JSONParser();


// url to create new product
private static String url_login = "http://localhost/android_connect/get_login.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

Button btnSignIn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnSignIn=(Button)findViewById(R.id.buttonSignIN);

}

public void signIn(View V)
{
    final Dialog dialog = new Dialog(MainActivity.this);
    dialog.setContentView(R.layout.login);
    dialog.setTitle("Login");

    // get the Refferences of views
    final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
    final  EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);

    Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);

    // Set On ClickListener
    btnSignIn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // get The User name and Password
            userName=editTextUserName.getText().toString();
            password=editTextPassword.getText().toString();

            new LoginUser().execute();

        }
    });

    dialog.show();

}

class LoginUser extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Verificoo NomeUtente & Password ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Checking login
     * */
    protected String doInBackground(String... args) {


        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("use_username", userName));
        params.add(new BasicNameValuePair("use_psw", password));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_login,
                "POST", params);


        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS)

            if (success == 1) {
                     //blablabla
            } else {

                Intent intent = getIntent();
                finish();

                Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();

                startActivity(intent);

            }
        } 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();
    }

}
}

3 个答案:

答案 0 :(得分:0)

@miselking

这里是JsonParser类

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");
        }
        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;

}
}

答案 1 :(得分:0)

检查json是否为空

if(json!=null){do something}

答案 2 :(得分:0)

此行错误

httpPost.setEntity(new UrlEncodedFormEntity(params));

使用此行

if (params!=null) 
   httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

并且在GET方法中使用HTTP.UTF_8代替"utf-8"