【发布时间】:2012-01-07 08:26:58
【问题描述】:
在我开始描述问题之前,我想指出我知道其他线程在问这个问题,但是对我来说没有一个能够解决我的问题。
我一直在使用 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);
}
}
}
【问题讨论】: