3

Im getting error in the following code. I am getting error in between the --->1 & --->2 ..ie while loop. Got response code as 200.But still my app is crashed.

Note: The same question was already asked.Even I analyzed that but i m not getting the right thing.Please help me to fix it.

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 Error:

 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();
            }
9
  • Did you declare StringBuffer? Commented Mar 12, 2016 at 8:18
  • Yes declared.Even nothing is printed the value of StringBuffer in Log.e Commented Mar 12, 2016 at 8:21
  • Provide full logat of errors..i think you didn't initialize buffer in ur code. Commented Mar 12, 2016 at 8:23
  • Error is at SignUpFragment_1.java:187 ..what is it? Commented Mar 12, 2016 at 8:26
  • Ya.. in this line I m getting Commented Mar 12, 2016 at 8:27

2 Answers 2

1

The Exception is JSONObject.getString(java.lang.String), so it means you are getting JSONObject which is null, so jObj is null and LogCat is not showing any Exception because of your goodness, you didn't catch exceptions.

So to work your code, replace code from else part.

You were not assigning JSONObject to json string variable in else part.

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 + " \"}";
}

And never ever forget to Catch and Log Exception

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

I'm sure, it'll solve your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Now I m checking my DB & PHP.
0

The error say's that you haven't initialize your string line... so either initialize like line = "" or pass null (which will again throw NullPointerException when it accessed without assigning any value) to it..you can also try StringBuilder class like..

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 ....

2 Comments

line is initialized in while condition as line = br.readLine(). so that is not the error.
try executing these lines without initializing String line, i'm using same method since 2 years...try it once

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.