数据库,我们首先要创建一个类,里面用来创建表
public class BlackNumberDBOpenHelper extends SQLiteOpenHelper {
创建好了以后我们就开始写他的增删改查了
public class BlackNumberDao {
private BlackNumberDBOpenHelper blackNumberDBOpenHelper;
//在构造方法里初始化helper对象
public BlackNumberDao(Context context) {
blackNumberDBOpenHelper = new BlackNumberDBOpenHelper(context);
}
//方法 添加
public boolean add(String peoplename, String phonenumber, String mode) {
SQLiteDatabase writableDatabase = blackNumberDBOpenHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("peoplename", peoplename);
contentValues.put("phonenumber", phonenumber);
contentValues.put("mode", mode);
long result = writableDatabase.insert("blacknumber", null, contentValues);
writableDatabase.close();//关闭数据库
if (result != -1) {
return true;
} else {
return false;
}
}
//方法 删除
public boolean delete(String phonenumber) {
SQLiteDatabase writableDatabase = blackNumberDBOpenHelper.getWritableDatabase();
int result = writableDatabase.delete("blacknumber", "phonenumber=?", new String[]{phonenumber});
writableDatabase.close();//关闭数据库
if (result > 0) {
return true;
} else {
return false;
}
}
//方法 修改拦截模式
public boolean updateMode(String phonenumber, String newMode) {
SQLiteDatabase writableDatabase = blackNumberDBOpenHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("mode", newMode);
int result = writableDatabase.update("blacknumber", contentValues, "phonenumber=?", new String[]{phonenumber});
writableDatabase.close();//关闭数据库
if (result > 0) {
return true;
} else {
return false;
}
}
//方法 查询某个号码的拦截模式 如果返回null代表当前号码不是黑名单号码
public String find(String phonenumber) {
String mode = null;
SQLiteDatabase readableDatabase = blackNumberDBOpenHelper.getReadableDatabase();
Cursor cursor = readableDatabase.query("blacknumber", new String[]{"mode"}, "phonenumber=?", new String[]{phonenumber}, null, null, null);
if (cursor.moveToNext()) {
mode = cursor.getString(0);
}
cursor.close();
readableDatabase.close();
return mode;
}
//方法 查询黑名单里的所有信息
public List
SQLiteDatabase readableDatabase = blackNumberDBOpenHelper.getReadableDatabase();
List
Cursor cursor = readableDatabase.query("blacknumber", new String[]{"_id", "peoplename", "phonenumber", "mode"}, null, null, null, null, null);
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String peoplename = cursor.getString(1);
String phonenumber = cursor.getString(2);
String mode = cursor.getString(3);
BlackNumberInfo info = new BlackNumberInfo();
info.setId(_id);
info.setPeoplename(peoplename);
info.setPhonenumber(phonenumber);
info.setMode(mode);
infos.add(info);
}
cursor.close();
readableDatabase.close();
return infos;
}
}
这其实可以当成一个工具类,我们用的时候就直接改表名就好了