android studio sqlite 存储数据 代码展示
时间: 2023-09-11 16:08:59 浏览: 88
Android数据存储实现(基于sqlite)
5星 · 资源好评率100%
Sure! 这里是一个简单的 Android Studio SQLite 存储数据的代码示例:
首先,创建一个类来代表对应数据表中的行:
```java
public class MyData {
private int id;
private String name;
private int age;
public MyData(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
接下来,在要使用 SQLite 的 Activity 中,创建一个 SQLiteOpenHelper 子类:
```java
public class MyDatabaseHelper 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 ID_COLUMN = "id";
private static final String NAME_COLUMN = "name";
private static final String AGE_COLUMN = "age";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME + " (" +
ID_COLUMN + " INTEGER PRIMARY KEY," +
NAME_COLUMN + " TEXT," +
AGE_COLUMN + " INTEGER)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Implement if needed
}
public void addData(MyData data) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID_COLUMN, data.getId());
values.put(NAME_COLUMN, data.getName());
values.put(AGE_COLUMN, data.getAge());
db.insert(TABLE_NAME, null, values);
db.close();
}
public List<MyData> getAllData() {
List<MyData> dataList = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
String selectAllQuery = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(selectAllQuery, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(ID_COLUMN));
String name = cursor.getString(cursor.getColumnIndex(NAME_COLUMN));
int age = cursor.getInt(cursor.getColumnIndex(AGE_COLUMN));
dataList.add(new MyData(id, name, age));
}
cursor.close();
db.close();
return dataList;
}
}
```
最后,在 Activity 中使用这个 SQLiteOpenHelper,通过它来添加数据和获取数据:
```java
public class MainActivity extends AppCompatActivity {
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new MyDatabaseHelper(this);
MyData dataToInsert = new MyData(1, "John", 25);
dbHelper.addData(dataToInsert);
List<MyData> dataList = dbHelper.getAllData();
for (MyData data : dataList) {
Log.d("MyData", data.getId() + ", " + data.getName() + ", " + data.getAge());
}
}
}
```
希望这个示例对你有帮助!
阅读全文