在Android中,使用SQLite數據庫進行數據存儲是一種常見的方法
在AndroidManifest.xml文件中,添加以下權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
創建一個名為MyDBHelper的類,該類繼承自SQLiteOpenHelper。這個類將用于創建和管理SQLite數據庫。
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "myTable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public 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 NOT NULL, "
+ COLUMN_AGE + " INTEGER);";
public MyDBHelper(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) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
在你的Activity中,使用MyDBHelper類來創建、打開和操作數據庫。
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
MyDBHelper myDBHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDBHelper = new MyDBHelper(this);
// 插入數據
insertData("張三", 25);
insertData("李四", 30);
// 查詢數據
String name = queryData(1);
if (name != null) {
Toast.makeText(this, "查詢到的名字: " + name, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "沒有查詢到數據", Toast.LENGTH_SHORT).show();
}
}
private void insertData(String name, int age) {
SQLiteDatabase db = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MyDBHelper.COLUMN_NAME, name);
values.put(MyDBHelper.COLUMN_AGE, age);
db.insert(MyDBHelper.TABLE_NAME, null, values);
db.close();
}
private String queryData(int id) {
String result = null;
SQLiteDatabase db = myDBHelper.getReadableDatabase();
Cursor cursor = db.query(MyDBHelper.TABLE_NAME, new String[]{MyDBHelper.COLUMN_NAME}, MyDBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(id)}, null, null, null);
if (cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(MyDBHelper.COLUMN_NAME));
}
cursor.close();
db.close();
return result;
}
}
這個示例展示了如何在Android中使用SQLite數據庫進行數據存儲。你可以根據需要修改表結構、列名和操作方法。