Android——Sqlite数据库——实现联系人信息的添加、查询、修改以及删除功能
以下是一个简化的示例代码,展示了如何在Android中使用SQLite数据库来实现基本的联系人信息添加、查询、修改和删除功能。
public class ContactsDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "contacts.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "contacts_table";
public ContactsDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "NAME TEXT,"
+ "PHONE TEXT,"
+ "EMAIL TEXT" + ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
// 添加联系人信息
public boolean addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("NAME", contact.getName());
values.put("PHONE", contact.getPhoneNumber());
values.put("EMAIL", contact.getEmail());
long result = db.insert(TABLE_NAME, null, values);
return result != -1;
}
// 查询所有联系人信息
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{"ID", "NAME", "PHONE", "EMAIL"}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setEmail(cursor.getString(3));
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
return contactList;
}
// 根据ID查询联系人信息
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{"ID", "NAME", "PHONE", "EMAIL"}, "ID =
评论已关闭