英文:
looping in primitive array android java
问题
以下是您要求的翻译部分:
代码1:
try{
JSONArray data = new JSONArray(str);
for(int i=0; i<data.length(); i++)
{
JSONObject videos = data.getJSONObject(i);
videoListData = new VideoData[]{new VideoData("aaa", getBitmap(videos.getString("url")))};
}
VideoAdapter adapter = new VideoAdapter(videoListData);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
代码2:
VideoData[] videoListData = new VideoData[]{
new VideoData("Email", getBitmap("xaf234")),
new VideoData("Info", getBitmap("xaf290")),
new VideoData("Info", getBitmap("1f7ucv5"))
}
问:如何将代码2实现为循环?
请帮忙,谢谢。
英文:
I've tried to looping JSONArray to put it's value into primitive array, but the result always null, here's my code (code 1):
try{
JSONArray data = new JSONArray(str);
/for(int i=0;i<=data.length();i++)
{
JSONObject videos = data.getJSONObject(i);
videoListData = new VideoData[]{new VideoData("aaa",getBitmap(videos.getString("url")))};
}
VideoAdapter adapter = new VideoAdapter(videoListData);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
I've tried to put it without looping and successful, here's my code (code 2):
VideoData[] videoListData = new VideoData[]{
new VideoData("Email", getBitmap("xaf234")),
new VideoData("Info", getBitmap("xaf290")),
new VideoData("Info", getBitmap("1f7ucv5"))
Q : How to implements code 2 in looping?
please help
Thanks.
答案1
得分: 2
你在每次循环时都在创建一个新的数组。这不是你想要做的;你想在每次循环时向数组中添加元素。
Java 数组具有固定的大小,您需要事先知道大小。因此,不要使用它们;改用 ArrayList。
因此:
List<VideoData> videoListData = new ArrayList<VideoData>();
// 你的其余代码,除了...
videoListData.add(new VideoData("aaa", getBitmap(...)));
英文:
You're making a new array every time you loop. That's not what you want to be doing; you want to add to the array every loop.
Java arrays are fixed size and you need to know the size beforehand. Hence, don't use them; use ArrayList instead.
Thus:
List<VideoData> videoListData = new ArrayList<VideoData>();
// the rest of your code, except...
videoListData.add(new VideoData("aaa", getBitmap(...));
答案2
得分: 0
在你的for循环中,你每次都在赋予新的值,但你需要将数据添加到你的videoListData中,就像这样:
videoListData.add(new VideoData("aaa", getBitmap(videos.getString("url"))));
英文:
In your for loop you are assigning new value every time, but you need to add data in your videoListData, like
videoListData.add(new VideoData("aaa",getBitmap(videos.getString("url"))));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论