将数据动态放入String []

时间:2017-11-22 16:34:00

标签: android listview for-loop

我想填充从ListView读取项目的NAMES[]

ListView填充了Dialog

我尝试使用预定义数据,但效果很好。但是当我把数据放在一个循环中时不是。

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

运行时,ListViewEmpty。如何将ListView中的值放入循环中?

1 个答案:

答案 0 :(得分:1)

您可以在ArrayAdapter构造函数中使用List<String>(如上面的注释所示)。 然后你需要编辑列表并调用adapter.notifyDatasetChanged()来更新数据。