android studio如何用数据库将数据写入listview并显示
时间: 2023-09-10 20:06:43 浏览: 197
首先,你需要创建一个数据库并将数据存储在其中。你可以使用SQLite数据库,它是Android中默认的关系型数据库。以下是一个简单的创建和插入数据的代码示例:
```
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myDatabase";
private static final String TABLE_NAME = "myTable";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_AGE + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addData(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name);
values.put(KEY_AGE, age);
db.insert(TABLE_NAME, null, values);
db.close();
}
}
```
在上面的示例中,我们创建了一个名为myDatabase的数据库和名为myTable的表。表中有三个列: id, name和age。addData()方法用于向表中插入数据。
现在你需要在你的Activity中使用DBHelper类来从数据库中获取数据并将其显示在ListView中。以下是示例代码:
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
private List<String> dataList = new ArrayList<>();
private ArrayAdapter<String> adapter;
private DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
dbHelper = new DBHelper(this);
getData();
}
private void getData() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {DBHelper.KEY_NAME, DBHelper.KEY_AGE};
Cursor cursor = db.query(DBHelper.TABLE_NAME, projection, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_NAME));
int age = cursor.getInt(cursor.getColumnIndex(DBHelper.KEY_AGE));
dataList.add(name + " (" + age + ")");
} while (cursor.moveToNext());
}
cursor.close();
db.close();
adapter.notifyDataSetChanged();
}
}
```
在上面的示例中,我们创建了一个ListView和一个ArrayAdapter来显示数据。我们还使用DBHelper类从数据库中获取数据,并将其添加到dataList中。最后,我们调用adapter.notifyDataSetChanged()来通知ListView更新数据。
这样,你就可以使用数据库将数据写入ListView并显示了。
阅读全文