I am trying to populate a list with data from SQLite.How can I use For loops to reduce the number of lines in the following code? I will have to pass String Arrays fa, fe, fi, fo to the 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]);
}
As your source data is always the same you do not need to re-read it many times, and can just loop once
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
}
Note
not sure what fa = arrayList.toArray(new String[0]);
is doing but I think you can do it after the loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.