简体   繁体   中英

Cant add item to Arraylist<String>

I want to add an item to my 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...

 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. Everthing works fine, but I can't add items to my arraylist (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.
You have to assign your String url to 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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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