Reputation: 433
I want to have an example String[] images
like the below dynamically, but i cannot achieve it
String[] images = new String[] { "http://image/image1", "http://image/image1", "http://image/image1"};
I have a json where it contains the image urls, below code is how i am tryig to put the json image urls to the string[] images
String[] images = new String[]{};
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String imagepath = c.getString("imagepath");
images[i] = imagepath; // trying to put the values to String[] images
}
Upvotes: 0
Views: 2731
Reputation: 10569
int lenth=contacts.length();
String[] images = new String[lenth];
for (int i = 0; i < lenth; i++) {
JSONObject c = contacts.getJSONObject(i);
String imagepath = c.getString("imagepath");
images[i] = imagepath ; // trying to put the values to String[] images
}
For better looping follow Performance Tips .
Upvotes: 3
Reputation: 431
try using Arraylist instead of array
ArrayList<String> arraylist=new ArrayList<>();
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String imagepath = c.getString("imagepath");
arraylist.add(imagepath);
}
to retrive item use arraylist.get(i);
Upvotes: 3
Reputation: 11999
You must define a size for your String[]
before using it.
String[] images = new String[contacts.length()];
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String imagepath = c.getString("imagepath");
images[i] = newURL; // trying to put the values to String[] images
}
Upvotes: 2