try { SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null); db.execSQL("CREATE TABLE IF NOT EXISTS user(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)"); } catch (Exception e) { Log.e("TAG", "创建数据库或表失败: " + e.toString()); }
Cursor cursor = db.rawQuery("SELECT * FROM user", null); CursorAdapter adapter = new CursorAdapter(context, cursor, true) { @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.item_user, parent, false); }
@Override public void bindView(View view, Context context, Cursor cursor) { TextView tvName = view.findViewById(R.id.tv_name); TextView tvAge = view.findViewById(R.id.tv_age); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); tvName.setText(name); tvAge.setText(String.valueOf(age)); } }; recyclerView.setAdapter(adapter);