简体   繁体   English

无法将项目添加到 Arraylist<String>

[英]Cant add item to Arraylist<String>

I want to add an item to my Arraylist "eventPicture".我想向我的 Arraylist“eventPicture”添加一个项目。

public class Main extends AppCompatActivity{
...
ArrayList<String> eventPicture = new ArrayList<String>(); 
protected void onCreate(Bundle savedInstanceState) {
...
String url = "https://developer.android.com/static/images/android_logo.png";
eventPicture.add(0, url);

The above one works correctly, but I want do add the url in an other method with a for loop...上面的工作正常,但我想用for循环在另一种方法中添加url...

 private void showEvents(String response){
    try{
        JSONObject jsonObject = new JSONObject(response);
        events = jsonObject.getJSONArray(Constants.JSON_ARRAY);
        for(int i = 0; i <= events.length(); i++){
        ...
        String url = (Constants.URL_GET_SPECIAL_EVENTS_PICTURE + image);
        eventPicture.add(i, url);
       }

I have a json object with the data from a mysql database.我有一个 json 对象,其中包含来自 mysql 数据库的数据。 Everthing works fine, but I can't add items to my arraylist (eventPicture)一切正常,但我无法将项目添加到我的数组列表 (eventPicture)

Many thanks to your reply.非常感谢您的回复。

change改变

 for(int i = 0; i <= events.length(); i++)

to

 for(int i = 0; i < events.length(); i++)

Your second code is adding the same URL over and over.您的第二个代码是一遍又一遍地添加相同的 URL。
You have to assign your String url to events.getString("whatever JSON key here") .您必须将 String url 分配给events.getString("whatever JSON key here") You're also looping through events without retrieving the data.您还可以在不检索数据的情况下遍历事件。

Here is a reworked version of your function.这是您的功能的重新设计版本。 I do not have enough details to fill the entire script, but you should be able to work things out from here.我没有足够的细节来填写整个脚本,但您应该能够从这里解决问题。

private void showEvents(String response) {
    try{
        JSONArray urls = response.getJSONArray("URLs");
        for(int i = 0; i < urls.length(); i++) {
            JSONObject jsonObject = urls.getJSONObject(i);
            String url = events.getString("whatever JSON key");
            eventPicture.add(url);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM