问题的原因可能是数据库查询代码没有正确地与显示数据的代码结合在一起。以下是一个示例代码,演示如何通过点击按钮显示所有数据库记录:
SQLiteOpenHelper dbHelper = new SQLiteOpenHelper(context, "mydatabase.db", null, 1);
public Cursor getAllRecords() { SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM mytable", null); return cursor; }
Button showAllButton = findViewById(R.id.showAllButton); ListView listView = findViewById(R.id.listView);
showAllButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Cursor cursor = getAllRecords(); MyCursorAdapter adapter = new MyCursorAdapter(context, cursor, 0); listView.setAdapter(adapter); } });
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor cursor, int flags) { super(context, cursor, flags); }
@Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.list_item, parent, false); return view; }
@Override public void bindView(View view, Context context, Cursor cursor) { TextView text1 = view.findViewById(R.id.text1); TextView text2 = view.findViewById(R.id.text2); String name = cursor.getString(cursor.getColumnIndex("name")); String age = cursor.getString(cursor.getColumnIndex("age")); text1.setText(name); text2.setText(age);
上一篇:AndroidStudio中的数据库检查器是否需要在查询数据库之前才能显示数据库的模式?
下一篇:AndroidStudio中的SQLLite数据库错误(android.database.sqlite.SQLiteException)