阅读量:0
在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中使用数据库:
在你的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数据库进行数据存储。你可以根据需要修改表结构、列名和操作方法。