循环访问JSON时listadpter中的空引用

时间:2018-06-18 14:09:16

标签: android arrays json nullpointerexception

我从简单的api中获取一些json,以列表视图显示。

public class ScenariosActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();
private ListView ScenarioListView   ;

ArrayList<HashMap<String, String>> scenarioList;

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

    ScenarioListView = findViewById(R.id.scenariosListView);

    new getScenarios().execute();
}

@SuppressLint("StaticFieldLeak")
class getScenarios extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(ScenariosActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        HttpHandler httpHandler = new HttpHandler();
        String url = "https://40kapi.evinwijninga.com/scenarios";
        String jsonStr = httpHandler.makeServiceCall(url);
        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);

                JSONArray scenarios = jsonObject.getJSONArray("scenarios");
                Log.e(TAG, "JSONARRAY :"+scenarios);

                for (int i = 0; i < scenarios.length(); i++){
                    Log.e(TAG, "Scenario's length: "+String.valueOf(scenarios.length()));
                    JSONObject s = scenarios.getJSONObject(i);

                    String id = null;
                    String title = null;

                    if (s.getString("id") != null) {
                        id = s.getString("id");
                        Log.e(TAG, id);
                    } else {
                        Log.e(TAG, "id = null");
                    }

                    if (s.getString("title") != null) {
                        title = s.getString("title");
                        Log.e(TAG, title);
                    } else {
                        Log.e(TAG, "title = null");
                    }

                    if (id != null && title != null){

                        // make new scenario
                        HashMap<String, String> scenario = new HashMap<>();
                        // add properties to scenario
                        scenario.put("id", id);
                        scenario.put("title", title);
                        // add scenario to scenariolist
                        scenarioList.add(scenario);
                    } else {
                        Log.e(TAG, "id or title is null");
                    }
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG).show();
                }
            });
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        ListAdapter adapter = new SimpleAdapter(ScenariosActivity.this, scenarioList,
                R.layout.scenario_list_item, new String[]{"title"},
                new int[]{R.id.title});
        ScenarioListView.setAdapter(adapter);
    }
}
}

执行时我得到一个空引用:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference

我记录了数组的长度,它是3,这很好。我得到了第一个记录的jsonobject的id和字符串,那就是它。

当通过json数组循环其对象时,我做错了。

1 个答案:

答案 0 :(得分:1)

将您的ArrayList scenarioList初始化为:

ArrayList<HashMap<String, String>> scenarioList = new ArrayList<>();

在这里,您尝试访问scenarioList而不进行初始化,因为它是空的,并且您将获得空指针异常。