0

I want to populate a String array in a do while statement like below, I can populate a TextView with the code but I need to be able to click on through, if you know what I mean.

It's not all here but I hope you get my drift.

String[] theLocations = { };

do {        
    //...Here I would like to fill theLocations with the same values as output below
    output.append("\n\n" + BeachName + " - " + distence + "Kms");           
} while (theCursor.moveToNext());   

I guess I will need the _id field also!

Cheers,

Mike.

2 Answers 2

2

The problem with array is that it has a fixed size, and while loop usually don't run a fixed number of times.

There are two better options:

  1. Use StringBuilder:

    StringBuilder sb = new StringBuilder();
    do {        
        sb.append("\n\n" + BeachName + " - " + distence + "Kms");           
    } while (theCursor.moveToNext());   
    
  2. Use ArrayList<String>:

    List<String> ar = new ArrayList<String>();
    do {        
        ar.add("\n\n" + BeachName + " - " + distence + "Kms");           
    } while (theCursor.moveToNext());   
    
Sign up to request clarification or add additional context in comments.

2 Comments

You can do a String[]theLocation = ar.toArray(new String[ar.size()]) at the end to get an array.
Thanks Binyamin and @Njzk2 but as I was using ArrayAdapter, not in the above code to populate my list List<String> ar = new ArrayList<String>(); worked perfectly and first time. thanks!
1

Use

cursor.getCount()

to initialize your String[]:

String[] theLocations = new String[cursor.getCount()]
int index = 0;
while (cursor.moveToNext()) {
    theLocations[index++] = cursor.getString(column);
}

Comments

Your Answer

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