Zubair Younas
Zubair Younas

Reputation: 71

Put data in String[] dynamically

I want to populate a ListView which reads items from NAMES[].

The ListView is populated in a Dialog.

I tried using predefined data and it works fine. But not when I put the data in a loop.

public String[] NAMES;

public void forDialog() {
    Dialog dialog = new Dialog(Gorups.this);
    NAMES = new String[]{};
    int j = 1;
    int i = Integer.parseInt(readFile(last));

    // Start reading from 1 to "how many files are saved"
    while (j <= i) {
        try {
            FileInputStream fis = openFileInput("filepg" + j + ".txt");
            String a = readFile("filepg" + j + ".txt");
            NAMES[j-1] = a;
            // Here, I want to keep adding data in NAMES by reading all saved files

            int size = fis.available();
            byte[] buffer = new byte[size];
            fis.read(buffer);
            fis.close();
        } catch (Exception e) {
            // If limit is reached, break the loop
            break;
        }
        j++;
    }
    dialog.setTitle("Saved Contacts in PG:");
    dialog.setContentView(R.layout.custome_dialog);
    pglist = (ListView)dialog.findViewById(R.id.lvpg);

    // Here, I am populating the ListView
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            Gorups.this,
            android.R.layout.simple_list_item_1, NAMES );
    pglist.setAdapter(arrayAdapter);
    dialog.show();
}

When I run it, ListView is Empty. How do I put values in ListView in a loop?

Upvotes: 0

Views: 26

Answers (1)

Pavel Kuznetsov
Pavel Kuznetsov

Reputation: 344

You can use List<String> in ArrayAdapter constructor (as comment above says). Then you need to edit the list and call adapter.notifyDatasetChanged() to update data.

Upvotes: 1

Related Questions