【发布时间】:2020-12-24 11:13:25
【问题描述】:
这是一个从 Internet 获取 JSON 数据的简单程序。 answerWithAsyncTask() 是一个接口,确保所有下载的数据只有在下载完成后才会添加到 questionArrayList。
错误:java.lang.IndexOutOfBoundsException:索引:1,大小:0
private List<Question> questionList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Few findViewbyId's here. Ignoring them
questionList = new QuestionBank().getQuestions(new answerWithAsyncTask() {
@Override
public void asyncMe(ArrayList<Question> questionArrayList) {
questionTextview.setText(questionArrayList.get(currentQuestionIndex).getQuestionId());
}
});
updateQuestion(); //This is the newly added line
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.prev_button:
updateQuestion();
break;
}
}
private void updateQuestion() {
String question = questionList.get(1).getQuestionId();
questionTextview.setText(question);
}
UPDATE这是我的getQuestions方法。
String url ="https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
private ArrayList<Question> questionArrayList= new ArrayList<>();
public List<Question> getQuestions (final answerWithAsyncTask callback){
JsonArrayRequest jsonArrayRequest =new JsonArrayRequest(Request.Method.GET, url, (String) null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
for(int i=0;i<response.length();i++){
Question question = new Question();
try {
question.setQuestionId(response.getJSONArray(i).getString(0));
question.setTorF(response.getJSONArray(i).getBoolean(1));
questionArrayList.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(null != callback) callback.asyncMe(questionArrayList);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
这是我的界面answerWithAsyncTask
public interface answerWithAsyncTask {
void asyncMe(ArrayList<Question> arrayList);
}
【问题讨论】:
-
在您的方法 updateQuestion() 中更改 - get(1) 到 get(0)。然后告诉我它是否有效?
-
不,它没有。实际上,通过 JSON 数组解析的数据数量超过 900。因此,无论是 0 还是 1,它都应该显示一个值。
-
例如在第一种情况下,如果改为写
get(50),它仍然会相应地显示数据。但在第二种情况下,任何值都会导致错误。 -
Index: 1, Size: 0 表示 ArrayList 的大小为 0。您尝试访问其元素的行,应首先通过记录检查其大小。
-
其实我已经抽象了剩下的代码。 Volley 是异步的,这意味着它会在从 Internet 下载数据之前显示数据,这就是我使用 answerWithAsyncTAsk() 内部接口的原因,以便在此处维护一种委托(仅在完全接收时显示数据)。
标签: android android-studio methods android-asynctask synchronization