0

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
     }
4
  • You need to specify the length of your array when you create it. Commented Nov 4, 2015 at 10:10
  • What is that newURL you may need to assign imagepath right ? Commented Nov 4, 2015 at 10:24
  • sorry im assigning imagepath not the newURL Commented Nov 4, 2015 at 10:30
  • Consider to accept any answer. Commented Nov 30, 2015 at 4:43

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

Comments

3
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 .

Comments

2

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
}

3 Comments

What is the length / content of contacts ?
contacts is JSONArray which i get from httpclient
Did you check that contacts is not empty ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.