android查sqlite并显示_android studio从Sqlite数据库检索数据并将其显示为textview
时间: 2024-03-23 09:42:08 浏览: 86
android读取sqlite数据库的数据并用listview显示
要从SQLite数据库检索数据并将其显示在Android应用程序中,您可以按照以下步骤进行操作:
1. 创建一个SQLite数据库并创建一个表。
2. 向表中插入数据。
3. 在Android应用程序中使用Cursor对象检索数据。
4. 将数据显示在TextView中。
以下是示例代码:
1. 创建SQLite数据库并创建表:
```
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "my_database.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "my_table";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_AGE + " INTEGER);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle upgrade
}
}
```
2. 向表中插入数据:
```
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_NAME, "John Doe");
values.put(DatabaseHelper.COLUMN_AGE, 30);
long newRowId = db.insert(DatabaseHelper.TABLE_NAME, null, values);
```
3. 使用Cursor对象检索数据:
```
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {
DatabaseHelper.COLUMN_NAME,
DatabaseHelper.COLUMN_AGE
};
String selection = DatabaseHelper.COLUMN_NAME + " = ?";
String[] selectionArgs = { "John Doe" };
Cursor cursor = db.query(
DatabaseHelper.TABLE_NAME, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null // The sort order
);
```
4. 将数据显示在TextView中:
```
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));
int age = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_AGE));
textView.setText(name + " is " + age + " years old.");
}
cursor.close();
```
希望这可以帮助您开始从SQLite数据库检索数据并将其显示在Android应用程序中。
阅读全文