只允许使用 Android SQLite 进行唯一数据输入?
在我开始按问题描述之前,我想指出我知道其他线程在问这个问题,但是对我来说,没有一个能够解决我的问题。
我一直在使用BumpAPI开发共享应用程序,该应用程序在收到块后,将其保存到SQLite数据库中,以便在列表视图活动中检索,这一切都正常工作并且数据已保存,但是如果相同的文本发送两次,它将一次又一次地保存,列表视图将显示这一点, 根据我所读到的内容,我需要“唯一”标识符吗?然而,作为SQL的新手,我对实现这一目标感到茫然,这是我的DataHelper类,我用它来创建和添加条目,有人会好心地修改它或通知我一个可能的解决方案吗?
非常感谢
public class DataHelper {
private static final String DATABASE_NAME = "tags.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "TagTable";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)" + "text unique, " + "ON CONFLICT REPLACE");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}