0

Help jsonObject NPE. I can parse and display the results i want to get from my db. I tried the php code in jsonlint.com it works. My problem is in android studio, when i parse and display the result it works. But when i run the activity on where it is supposed to display the app crashes.

Parser

public class Send extends Activity {
EditText et1, et2, et3, et4, et5;
String team1, score1, team2, score2, Type;
Button logout;
String json_string, JSON_STRING;



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

    et1 = (EditText) findViewById(R.id.et1);
    et2 = (EditText) findViewById(R.id.et2);
    et3 = (EditText) findViewById(R.id.et3);
    et4 = (EditText) findViewById(R.id.et4);
    et5 = (EditText) findViewById(R.id.et5);
    logout = (Button) findViewById(R.id.logout);


    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(v.getContext(), login.class));
            finish();
        }
    });
}

public void send(View view) {
    Type = et1.getText().toString();
    team1 = et2.getText().toString();
    score1 = et3.getText().toString();
    team2 = et4.getText().toString();
    score2 = et5.getText().toString();
    String method = "send";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method, Type, team1, score1, team2, score2);

}


public void get(View view) {
    new BgTask().execute();
}

class BgTask extends AsyncTask<Void, Void, String> {
    String json_url;

    @Override
    protected void onPreExecute() {
        json_url = "http://10.0.2.2/result/hehe.php";
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputstream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
            StringBuilder stringBuilder = new StringBuilder();
            while ((JSON_STRING = bufferedReader.readLine()) != null) {
                stringBuilder.append(JSON_STRING + "\n");
            }

            bufferedReader.close();
            inputstream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        json_string = result;
    }
}

public void publishGame(View view)
{
    if(json_string == null)
    {
        Toast.makeText(getApplicationContext(), "Get Data First",Toast.LENGTH_SHORT).show();
    }
    else
    {
        Intent intent = new Intent(this, Games.class);
        intent.putExtra("json_data", json_string);
        startActivity(intent);
    }
}

}

Here is where the app display the json result

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.games);
    final Spinner sports;
    final String[] str = {"Sports", "Basketball", "Football", "Futsal", "Softball", "Badminton", "Track and Field", "Chess", "Table Tennis", "Swimming", "Volleyball", "Sepak Takraw", "Taekwondo", "Judo", "Frisbee"};

    sports = (Spinner) findViewById(R.id.sp1);
    nonsports = (Spinner) findViewById(R.id.sp2);
    games = (Button) findViewById(R.id.games);
    news = (Button) findViewById(R.id.news);
    sched = (Button) findViewById(R.id.sched);
    stand = (Button) findViewById(R.id.stand);

    listview = (ListView) findViewById(R.id.listView);
    gamesAdapter = new GamesAdapter(this,R.layout.gamesadapterlayout);
    listview.setAdapter(gamesAdapter);
    Bundle intent=getIntent().getExtras();
    if(intent !=null) {

        json_string = getIntent().getExtras().getString("json_data");
    }


    ArrayAdapter<String> sp1 = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, str);
    sports.setAdapter(sp1);


    games.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             Intent intent = new Intent(v.getContext(), Games.class);   startActivity(getIntent());
        }
    });

    news.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), MainActivity.class);
            startActivity(intent);
        }
    });

    stand.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), Standings.class);
            startActivity(intent);
        }
    });

    sched.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), Schedule.class);
            startActivity(intent);
        }
    });

    sports.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long row_id) {
            Intent intent = null;




        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    try {
            jsonObject = new JSONObject(json_string);
            jsonArray = jsonObject.getJSONArray("server_response");
            int count = 0;
            String team1, score1, team2, score2, Type;

            while (count < jsonArray.length()) {
                JSONObject JO = jsonArray.getJSONObject(count);
                team1 = JO.getString("team1");
                score1 = JO.getString("score1");
                team2 = JO.getString("team2");
                score2 = JO.getString("score2");
                Type = JO.getString("Type");
                Downloader downloader = new Downloader(team1, score1, team2, score2, Type);
                gamesAdapter.add(downloader);

                count++;
            }


    } catch (JSONException e) {
        e.printStackTrace();
    }

}

The error is pointing at

try {
    jsonObject = new JSONObject(json_string); 

and it is telling me that it is NPE

Here is an image where i will dispaly the result in Games.class

The result of the display in the Games.class

Now the problem is after displaying it. When i click other menu and click the Games menu again it crashes. Because of the jsonObject NPE. Thanks

Logcat

E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.example.abe.ateneofiesta, PID: 6392
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abe.ateneofiesta/com.example.abe.ateneofiesta.Games}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                            at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                            at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                            at org.json.JSONObject.<init>(JSONObject.java:156)
                                                                            at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                            at com.example.abe.ateneofiesta.Games.onCreate(Games.java:111)
                                                                            at android.app.Activity.performCreate(Activity.java:6237)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:148) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                            at java.lang.reflect.Method.invoke(Native Method) 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
orange
  • 717
  • 2
  • 6
  • 14
  • I would recommend you follow this post. http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a – OneCricketeer Oct 27 '16 at 20:31
  • Also, this does not appear to be a [mcve]. How/where did you call `publishGame` or `get` to set the `json_string` to anything but null? – OneCricketeer Oct 27 '16 at 20:35
  • The get and publishgame both have android:onclick. Both classes are located in the parser. Thanks – orange Oct 27 '16 at 20:38
  • Your "parser" appears to be an Activity. Please show the rest of that class. – OneCricketeer Oct 27 '16 at 20:47
  • And because both classes are in the same file doesn't mean you still can't follow the advice from that post. You are dealing with asynchronous code. You will not immeadiately receive the `json_string` value until the request finishes. The error is a result of you starting the Activity too soon and not waiting for the AsyncTask to finish – OneCricketeer Oct 27 '16 at 20:49
  • updated sir. entire class of the parser is there – orange Oct 28 '16 at 06:06
  • Please add the full logcat as well – OneCricketeer Oct 28 '16 at 06:08
  • added the logcat sir – orange Oct 28 '16 at 06:40
  • Sorry, I'm not seeing why the value is null. You clearly put `if(json_string == null)` and there should be an Intent to the Game activity, and so the value should be retrieved there. You'll likely want to try more debugging on your code to see the order in which your code is being evaluated – OneCricketeer Oct 28 '16 at 06:47

0 Answers0