listview显示sqlite数据库
时间: 2023-04-27 11:06:50 浏览: 119
sqlite查询结果在listview中展示的实现
要在ListView中显示SQLite数据库,您需要执行以下步骤:
1. 创建一个SQLite数据库并插入数据。
2. 创建一个ListView并设置适配器。
3. 从SQLite数据库中检索数据并将其添加到适配器中。
以下是一个示例代码,可以帮助您实现这个过程:
1. 创建SQLite数据库并插入数据
```
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_AGE + " INTEGER)";
db.execSQL(createTable);
String insertData1 = "INSERT INTO " + TABLE_NAME + " (" +
COLUMN_NAME + ", " + COLUMN_AGE + ") VALUES ('John', 25)";
db.execSQL(insertData1);
String insertData2 = "INSERT INTO " + TABLE_NAME + " (" +
COLUMN_NAME + ", " + COLUMN_AGE + ") VALUES ('Mary', 30)";
db.execSQL(insertData2);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
2. 创建ListView并设置适配器
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
private DatabaseHelper databaseHelper;
private SQLiteDatabase database;
private Cursor cursor;
private SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
databaseHelper = new DatabaseHelper(this);
database = databaseHelper.getReadableDatabase();
String[] fromColumns = {DatabaseHelper.COLUMN_NAME, DatabaseHelper.COLUMN_AGE};
int[] toViews = {R.id.text_name, R.id.text_age};
adapter = new SimpleCursorAdapter(this, R.layout.list_item, null, fromColumns, toViews, );
listView.setAdapter(adapter);
}
@Override
protected void onResume() {
super.onResume();
cursor = database.query(DatabaseHelper.TABLE_NAME, null, null, null, null, null, null);
adapter.changeCursor(cursor);
}
@Override
protected void onPause() {
super.onPause();
cursor.close();
}
@Override
protected void onDestroy() {
super.onDestroy();
database.close();
databaseHelper.close();
}
}
```
3. 从SQLite数据库中检索数据并将其添加到适配器中
在MainActivity中的onResume方法中,我们从SQLite数据库中检索数据并将其添加到适配器中。在onPause方法中,我们关闭游标以释放资源。在onDestroy方法中,我们关闭数据库和数据库助手以释放资源。
希望这可以帮助您在ListView中显示SQLite数据库。
阅读全文