空对象引用上的java.lang.String org.json.JSONObject.getString(java.lang.String)'

时间:2016-03-12 08:13:08

标签: android json

我在以下代码中遇到错误。我在---> 1&之间得到错误---> 2 ..ie while 循环。 响应代码为200 。但我的应用程序仍然崩溃。

注意:    同样的问题已经被问到了。即使我分析了这一点,但我没有得到正确的答案。请帮我解决。

if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {

    is = con.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    Log.e("LOGIN CHECK", "json"); // -----------> 1 (Prints in Log.e)
    while ((line = br.readLine()) != null){
           buffer.append(line).append("\r\n");
    }
    json = buffer.toString();    // -----------> 2 (Didnt print in Log.e)
    Log.e("LOGIN CHECK", "json" + buffer.toString());
    is.close();
 }

LogCat错误:

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
                                                       at com.xxxxx.restaurant.Fragment.SignUpFragment_1$ProcessLogin.onPostExecute(SignUpFragment_1.java:187)
                                                       at com.xxxx.restaurant.Fragment.SignUpFragment_1$ProcessLogin.onPostExecute(SignUpFragment_1.java:163)
                                                       at android.os.AsyncTask.finish(AsyncTask.java:632)
                                                       at android.os.AsyncTask.access$600(AsyncTask.java:177)
                                                       at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:145)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5942)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

Json PArser:

public class JSONParser {

    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {
    }

    public JSONObject getJSONFromUrl(String url, HashMap<String, String> params) {
        HttpURLConnection con = null;
        InputStream is = null;

        try {
            con = (HttpURLConnection) (new URL(url)).openConnection();
            con.setRequestMethod("POST");
            con.connect();
            OutputStream os = con.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(params));
            writer.flush();
            writer.close();
            os.close();
            StringBuilder buffer = new StringBuilder();
            Log.e("Response Buffer", String.valueOf(buffer));
            int responseCode = con.getResponseCode();
            Log.e("Response Code", String.valueOf(responseCode));

            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {

                is = con.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                Log.e("LOGIN CHECK", "json");
                while ((line = br.readLine()) != null)
                    buffer.append(line).append("\r\n");
                json = buffer.toString();
                Log.e("LOGIN CHECK", "json" + buffer.toString());
                is.close();
            }else{
                  json = "abc";
            }
            con.disconnect();
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable ignored) {
            }
            try {
                if (con != null) {
                    con.disconnect();
                }
            } catch (Throwable ignored) {
            }
        }
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
        }
        return jObj;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

SignUpFragment_1:

try {
                if (json.getString(KEY_SUCCESS) != null) {  // Error in this LINE

                    String res = json.getString(KEY_SUCCESS);

                    if (Integer.parseInt(res) == 1) {
                        dbUtil.open();
                        JSONObject json_user = json.getJSONObject("user");

                        UserFunctions logout = new UserFunctions();
                        logout.logoutUser(context);

                        dbUtil.addLogIn(strUsername, strEmail, strPassword, LogInActivity.img);
                        Intent upanel = new Intent(context, MainActivity.class);
                        upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        pDialog.dismiss();
                        startActivity(upanel);
                    } else {
                        pDialog.dismiss();
                        Toast.makeText(context, "Incorrect username/password", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

2 个答案:

答案 0 :(得分:1)

ExceptionJSONObject.getString(java.lang.String),这意味着您的JSONObject为空,因此jObjnullLogCat为由于你的善意,没有显示任何Exception,你没有捕捉到异常。

因此,要使用代码,请替换else部分中的代码。

您没有在其他部分中将JSONObject分配给json字符串变量。

if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
    is = con.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    Log.e("LOGIN CHECK", "json");
    while ((line = br.readLine()) != null)
        buffer.append(line).append("\r\n");
    json = buffer.toString();
    Log.e("LOGIN CHECK", "json" + buffer.toString());
    is.close();
} else {
      json = "{" + KEY_SUCCESS + ":\"error response code " + responseCode + " \"}";
}

永远不要忘记CatchLog Exception

try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    e.printStackTrace();
}

我敢肯定,它会解决你的问题。

答案 1 :(得分:0)

该错误表示您尚未初始化字符串line ...因此要么初始化为line = "",要么传递null (这将是当它访问时再次抛出NullPointerException而没有赋值给它 ..你也可以试试StringBuilder类...

BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
  while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
  }
reader.close();
json = sb.toString();            // this is your String json;

Refer my example for further detail ....