我很难将通过按钮点击存储的数据显示在ListView中保存在SqlLite数据库中。当我点击它以将数据添加到数据库时,它不会在按钮下方显示我想要的数据。
我的代码:
boolean hasMoreData = cursor.moveToFirst();
while (hasMoreData) {
// get the value out of each column
long key = cursor.getLong(cursor.getColumnIndexOrThrow(MyDataEntry._ID));
String studentID = cursor.getString(cursor.getColumnIndexOrThrow(MyDataEntry.STUDENT_ID_COLUMN));
String studentGrade = cursor.getString(cursor.getColumnIndexOrThrow(MyDataEntry.STUDENT_GRADE_COLUMN));
//For now, just print out the record to the log.
ArrayList<String> myList = new ArrayList<>();
myList.add( " student id: "+ studentID);
myList.add(" student grade : " +studentGrade);
ArrayAdapter<String> myAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,myList);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(myAdapter);
System.out.println("RECORD KEY: " + key + " student id: " + studentID + " student grade : " + studentGrade);
//move on to the next row!
hasMoreData = cursor.moveToNext();
}
在模拟器中看起来像这样:
我想要的是什么:
答案 0 :(得分:1)
在循环外放置 ArrayAdapter 和 ListView 。
ArrayList<String> myList = new ArrayList<>();
boolean hasMoreData = cursor.moveToFirst();
while (hasMoreData) {
long key = cursor.getLong(cursor.getColumnIndexOrThrow(MyDataEntry._ID));
String studentID = cursor.getString(cursor.getColumnIndexOrThrow(MyDataEntry.STUDENT_ID_COLUMN));
String studentGrade = cursor.getString(cursor.getColumnIndexOrThrow(MyDataEntry.STUDENT_GRADE_COLUMN));
myList.add( " student id: "+ studentID);
myList.add(" student grade : " +studentGrade);
hasMoreData = cursor.moveToNext();
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, myList);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(myAdapter);
答案 1 :(得分:0)
每次拨打ArrayList<String> myList = new ArrayList<>();
和ArrayAdapter<String> myAdapter = new ArrayAdapter<String>();
时,您都会重置列表。
删除ArrayList<String> myList = new ArrayList<>();
然后移动
ArrayAdapter<String> myAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(myAdapter);
在您的循环上方,您将解决此问题
循环调用&#39; myAdapter.add(&#34;无论你想要什么&#34;);&#39;然后myAdapter.notifyDataSetChanged()
更新ui