json对象的NullPointerException

2 java android json nullpointerexception runtimeexception

为什么在运行应用程序时总是会出现NullPointerException?每次我启动我的genymotion模拟器,然后第一次运行应用程序,它崩溃,但第二次我运行我的应用程序工作顺利.我不知道为什么它会在第一次运行时发生.

这是我的Splash屏幕,它从RetrieveGamesBGTask中检索JSON对象:

public class Splash extends Activity {
     RetrieveGamesBGTask retrieveGamesBGTask;
    String json_string;

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

        Thread thread = new Thread(){
            @Override
            public void run() {
                try {
                    retrieveGamesBGTask = new RetrieveGamesBGTask();
                    retrieveGamesBGTask.execute();
                    sleep(3000);
                    Intent intent = new Intent(getApplication(), Games.class);
                    intent.putExtra("json_data", json_string);
                    intent.putExtra("json_data", retrieveGamesBGTask.getResult());
                    startActivity(intent);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();
Run Code Online (Sandbox Code Playgroud)

这是下一个应用程序,它在第一次运行时每次崩溃:

 retrieveGamesBGTask = new RetrieveGamesBGTask();
        retrieveGamesBGTask.execute();

  Intent intent = this.getIntent();

        if (intent != null) {
            json_string = intent.getStringExtra("json_data");
        }


        try {
            if (jsonObject == null) {
                jsonObject = new JSONObject(json_string);
                jsonArray = jsonObject.getJSONArray("server_response");
                int count = 0;
                String teamone, teamonepts, teamtwo, teamtwopts, s_name, s_gender;

                while (count < jsonArray.length()) {
                    JSONObject JO = jsonArray.getJSONObject(count);
                    teamone = JO.getString("teamone");
                    teamonepts = JO.getString("teamonepts");
                    teamtwo = JO.getString("teamtwo");
                    teamtwopts = JO.getString("teamtwopts");
                    s_name = JO.getString("s_name");
                    s_gender = JO.getString("s_gender");
                    Downloader downloader = new Downloader(teamone, teamonepts, teamtwo, teamtwopts, s_name, s_gender);
                    gamesAdapter.add(downloader);

                    count++;
                }
            } else {
                Toast.makeText(this, "JSON is null", Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

这是我的RetrieveGamesBGTask

class RetrieveGamesBGTask extends AsyncTask<Void, Void, String> {
    String json_result, json_string;

    @Override
    protected void onPreExecute() {


    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            URL url = new URL(Config.URL_GAMES);
            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) {
        Log.d("haha", "hehe");
        json_result = result;
    }

    public String getResult() {
        return json_result;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的logcat:

FATAL EXCEPTION: main 
Process: com.example.aaa.bbb, PID: 5680
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aaa.bbb/com.example.aaa.bbb.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)
Run Code Online (Sandbox Code Playgroud)

Ray*_*oix 7

这里有一些你可以做得更好的事情.但是你的主要问题是你正在做异步任务(backgroundtask)而没有处理正确的回调.

以下内容会发生什么:

  1. 启动异步任务.
  2. 你睡了3秒钟(这可能是为了在代码继续之前尝试进行异步完成.)
  3. Async任务可能没有在3秒内完成.
  4. 您尝试解析尚未收到的JSON.
  5. 这会抛出一个nullpointer.

现在,虽然崩溃异步任务仍然运行并完成.我不确定你是否保存这个JSON然后它在完成时变得可读并且第二次变得可用,或者第二次任务可以在3秒内完成.

你应该做什么

  1. 启动异步任务.
  2. 难道不是让线程睡眠.
  3. 在异步任务中onPostExecute有一个回调你的主线程.
  4. 让回调返回从任务中获得的JSON.
  5. 如果调用本身成功,现在解析您将拥有的JSON.

要实现这一目标,请访问https://developer.android.com/training/best-background.html

它应该提供足够的信息来使这段代码稳定.