【Android开发基础】SQLite开发复刻通讯录、记事本、计算机
由于篇幅所限,这里只展示如何使用SQLite数据库创建一个简单的通讯录应用程序的核心函数。请注意,这不是一个完整的应用程序,而是展示了如何使用SQLite来存储和检索数据的核心方法。
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class ContactsDatabaseHelper extends SQLiteOpenHelper {
private static final String TABLE_NAME = "contacts";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
private static final String COL_PHONE = "phone";
public ContactsDatabaseHelper(Context context) {
super(context, "contacts.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + TABLE_NAME + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NAME + " TEXT, " + COL_PHONE + " TEXT)";
db.execSQL(createTableStatement);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Implement schema migration logic if needed
}
public boolean insertContact(String name, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_NAME, name);
cv.put(COL_PHONE, phone);
long result = db.insert(TABLE_NAME, null, cv);
return result != -1;
}
public Cursor getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
return db.query(TABLE_NAME, new String[]{COL_ID, COL_NAME, COL_PHONE}, null, null, null, null, null);
}
public Cursor getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
return db.query(TABLE_NAME, new String[]{COL_ID, COL_NAME, COL_PHONE}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
}
public boolean updateContact(int id, String name, String phone) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_NAME, name);
cv.put(COL_PHONE, phone);
int result = db.update(TABLE_NAME, cv, COL_ID + "=?", new String[]{String.valueOf(id)});
return result > 0;
}
public boolean deleteContact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.de
评论已关闭