android读取sqlite数据库的数据并用listview显示的代码
时间: 2023-12-03 11:44:22 浏览: 273
以下是一个简单的示例代码,用于从SQLite数据库中读取数据并在ListView中显示:
1. 创建一个数据库帮助类 DBHelper.java:
```java
public class DBHelper 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";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT);";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void insertData(String name) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
db.insert(TABLE_NAME, null, values);
db.close();
}
public ArrayList<String> getData() {
ArrayList<String> dataList = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
dataList.add(name);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return dataList;
}
}
```
2. 在Activity中使用DBHelper类来读取数据并在ListView中显示:
```java
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayList<String> dataList;
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.list_view);
dataList = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
dbHelper = new DBHelper(this);
dbHelper.insertData("John");
dbHelper.insertData("Mary");
dbHelper.insertData("Tom");
ArrayList<String> list = dbHelper.getData();
dataList.clear();
dataList.addAll(list);
adapter.notifyDataSetChanged();
}
}
```
注意:需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
阅读全文