我写了一个Cursor,它将在databasehelper类中读取表中的所有信息,并为其分配一个自定义列表视图,我希望每个元素都对应相应的字段。但是,Cursor仅打印最后一个元素,并且仅限于3次迭代。
这是数据库助手类:
nditer
} 这是片段函数调用它:
public Cursor getPrograss(){
SQLiteDatabase db = this.getReadableDatabase ();
StatsitcsHelper object = new StatsitcsHelper ();
Cursor cursor = db.rawQuery ("select * from " + TABLE_PROGGRES, null);
cursor.moveToFirst();
if (cursor!= null && cursor.getCount() > 0 && !cursor.isAfterLast()){
cursor.moveToNext();
}
return cursor;
这是适配器:
public void ShowStatstics() {
DatabaseHelper db = new DatabaseHelper (getActivity ());
Cursor cursor = db.getPrograss ();
String DataA = cursor.getString(cursor.getColumnIndex(COL_P_Date));
String WeightA = cursor.getString(cursor.getColumnIndex(COL_P_Weight));
String PercentA = cursor.getString(cursor.getColumnIndex(COL_P_Percentage));
String[] Prograss = {DataA,WeightA,PercentA};
ListAdapter listAdapter = new StatisticsAdapter (getActivity (),Prograss);
lest.setAdapter (listAdapter);
}
答案 0 :(得分:0)
你可以像这样创建一个POJO类,
public class Data {
String date;
String weight;
String percentage;
}
然后在你的方法中你可以返回ArrayList并显示在下面的列表中,
public ArrayList<Data> getPrograss() {
SQLiteDatabase db = this.getReadableDatabase();
StatsitcsHelper object = new StatsitcsHelper();
Cursor cursor = db.rawQuery ("select * from " + TABLE_PROGGRES, null);
ArrayList<Data> datas = new ArrayList<>();
if(cursor != null) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
Data data = new Data();
data.date = cursor.getString(cursor.getColumnIndex(COL_P_Date));
data.weight = cursor.getString(cursor.getColumnIndex(COL_P_Weight));
data.percentage = cursor.getString(cursor.getColumnIndex(COL_P_Percentage));
datas.add(data);
}
cursor.close();
}
return datas;
}
你的适配器类看起来像这样,
class StatisticsAdapter extends ArrayAdapter<Data> {
public StatisticsAdapter(@NonNull Context context, ArrayList<Data> resource) {
super (context, R.layout.listview_layout ,resource);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater ListInflate = LayoutInflater.from(getContext ());
Data data = getItem(position);
View customView = ListInflate.inflate (R.layout.listview_layout,parent,false);
String first = data.date;
TextView date = (TextView) customView.findViewById (R.id.List_Date);
String Second = data.weight;
TextView Weight = (TextView) customView.findViewById (R.id.List_Weight);
String Thierd = data.percentage;
TextView Percent = (TextView) customView.findViewById (R.id.List_Percentage);
date.setText (first);
Weight.setText (Second);
Percent.setText (Thierd);
return customView;
}
}
你可以从你的方法创建适配器,
public void showStatstics() {
DatabaseHelper db = new DatabaseHelper (getActivity ());
ArrayList<Data> datas = db.getPrograss ();
ListAdapter listAdapter = new StatisticsAdapter (getActivity (),datas);
lest.setAdapter (listAdapter);
}