如何使用For循环减少以下代码中的行数?

时间:2019-05-14 07:48:05

标签: java android loops

我正在尝试使用SQLite中的数据填充列表。如何使用For循环减少以下代码中的行数?我将必须将字符串数组fa,fe,fi,fo传递给ListAdapter。

    arrayList = new ArrayList<>();
    Cursor res = myhelp.getAllData();

    if (res.getCount() == 0) {
        Toast.makeText(this, "No data", Toast.LENGTH_SHORT).show();
    }else {
        while (res.moveToNext()) {

            arrayList.add(res.getString(0));
            fa = arrayList.toArray(new String[0]);

            }
        }
    arrayList1 = new ArrayList<>();
    Cursor res1 = myhelp.getAllData();

        while (res1.moveToNext()) {

            arrayList1.add(res1.getString(1));
            fe = arrayList1.toArray(new String[0]);


    }
    arrayList2 = new ArrayList<>();
    Cursor res2 = myhelp.getAllData();

        while (res2.moveToNext()) {

            arrayList2.add(res2.getString(2));
            fi = arrayList2.toArray(new String[0]);


    }
    arrayList3 = new ArrayList<>();
    Cursor res3 = myhelp.getAllData();

        while (res3.moveToNext()) {

            arrayList3.add(res3.getString(3));
            fo = arrayList3.toArray(new String[0]);

        }

1 个答案:

答案 0 :(得分:0)

由于您的源数据始终是相同的,因此您无需多次重新读取它,而只需循环一次即可

arrayList = new ArrayList<>();
arrayList1 = new ArrayList<>();
arrayList2 = new ArrayList<>();
// etc
Cursor res = myhelp.getAllData();
while (res.moveToNext()) {

        arrayList.add(res.getString(0));
        fa = arrayList.toArray(new String[0]);
        arrayList1.add(res.getString(1));
        fe = arrayList1.toArray(new String[0]);
        arrayList2.add(res.getString(2));
        fi = arrayList2.toArray(new String[0]);
        // etc

}

注意

不确定fa = arrayList.toArray(new String[0]);在做什么,但我认为您可以在循环后完成