使用 AsyncTask 将数据从 URL 提取到数组列表中



下面列出的原始代码有效,它将在两个单独的行中显示7,加利福尼亚州,昨天和我从网站上获取的标题,当我尝试将标题添加到任何ArrayLists时出现问题,如下所示:

try {
JSONObject json = new JSONObject(s);
String title = json.getJSONObject("metadata").getString("title");
text.setText(title);
magnitude.add(title);
} catch (JSONException e) {
e.printStackTrace();
}

这会给我一个错误:java.lang.IndexOutOfBoundsException: Index: 2, Size: 2我不知道为什么。 有什么解决方案吗?

原始代码:

public class MainActivity extends AppCompatActivity {

ArrayList<String> magnitude;
ArrayList<String> place;
ArrayList<String> time;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.textView);
magnitude = new ArrayList<>();
place = new ArrayList<>();
time = new ArrayList<>();
getJson json = new getJson();
String result = "";
try {
result = json.execute("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10").get();
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}


public void initRecycleView() {
RecyclerView recycler = findViewById(R.id.list);
recyclerAdapter adapter = new recyclerAdapter(MainActivity.this, magnitude, place, time);
recycler.setAdapter(adapter);
recycler.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}

public class getJson extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
magnitude.add("7");
place.add("California");
time.add("yesterday");
try {
JSONObject json = new JSONObject(s);
String title = json.getJSONObject("metadata").getString("title");
text.setText(title);

} catch (JSONException e) {
e.printStackTrace();
}
magnitude.add("7");
place.add("California");
time.add("yesterday");

initRecycleView();
}
@Override
protected String doInBackground(String... strings) {

String result = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1) {
char character = (char) data;
result += character;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
}

你的代码工作正常。 可能是来自其他地方的错误。也许来自你没有提到的回收器适配器。 检查 @Override public int getItemCount(( { 返回 0;数组列表的大小 }

也许您使用的值比数组列表包含的值更多。

相关内容

  • 没有找到相关文章

最新更新