【发布时间】:2015-02-23 10:39:57
【问题描述】:
我有以下代码在数据库中插入 contentValues。我使用 SQLitedatabase 方法 insert() 在数据库中插入值,如下所示:
public static final String ID = "id";
public boolean replaceOrUpdate(DBListener dbListener,final String sTable, ContentValues[] contentValues,String tag) {
this.mDbListener=dbListener;
if(mDatabase == null) {
openDB();
}
mDatabase.beginTransaction();
try {
int count = contentValues.length;
for (int i=0; i<count;i++) {
ContentValues value = contentValues[i];
long id = mDatabase.replaceOrThrow(sTable,null,value);
}
mDatabase.setTransactionSuccessful();
mDbListener.onCompleteInsertion(tag);
}catch (Exception e) {
Log.v("Exception = " , " " + e.toString());
e.printStackTrace();
}finally {
mDatabase.endTransaction();
}
return true;
}
public ArrayList<String> getAllPlacesIDs()
{
ArrayList<String> ids = new ArrayList<String>();
try
{
if(mDatabase==null || !mDatabase.isOpen())
{
openDB();
}
String query="SELECT "+DBUtil.ID+" FROM "+TABLE_MERCHANT_STORES;
Cursor cursor = mDatabase.rawQuery(query,null);
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext())
{
ids.add(cursor.getString(cursor.getColumnIndex(DBUtil.ID)));
}
cursor.close();
}catch(SQLException sqx)
{
sqx.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
}
return ids;
}
创建表如下:
db.execSQL("CREATE TABLE IF NOT EXISTS "+
TABLE_MERCHANT_STORES +" ("+
AUTO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
DBUtil.ID +" INTEGER NOT NULL UNIQUE, "+...)
此代码在棒棒糖之前的设备上运行良好,但插入在棒棒糖上无法正常工作。它似乎卡在某些值上并继续在表中插入缺失值。插入后,当我打印所有值时,它们以升序显示,缺少一些中间值。表中存储的id值为
1 2 3 4 5 7 11 13 14 15 16 17 19
而在棒棒糖前插入(预期)的值是:
514 533 531 312 434 162 253 252 151 344 153 160 658
在棒棒糖设备上看到的错误模式是,当在表中插入一个 id 时,只要它接收到的下一个 id 不大于查询,似乎查询会继续插入最后一个最大 ID 和当前最大 id 之间的间隙比插入的当前 id。这是棒棒糖sqlite中的错误吗?还是我的设备特有的东西?应用程序中没有实现这样的逻辑。我该如何纠正?是因为使用的字符串是 id 吗?它在棒棒糖之前的设备上运行良好,但在棒棒糖上运行错误。
编辑:
我添加值的方式如下:
private void insertIntoDB() {
int count = jsonArray.length();
ContentValues[] values = new ContentValues[count];
for(int i=0;i<count;i++){
JSONObject storeObject=jsonArray.getJSONObject(i);
if(storeObject!=null){
ContentValues value=new ContentValues();
value.put(DBUtil.ID, storeObject.getInt("id"));
mArrId.add(storeObject.getInt("id")+"");
value.put("place_parent", storeObject.getInt("place_parent"));
}
}
Cursor c1=new MylocalCursorLoader(mContext, "Delete from " + DBUtil.TABLE_MERCHANT_STORES).loadInBackground();
if(c1!=null){
DBUtil dbUtil = DBUtil.getInstance(mContext.getApplicationContext());
dbUtil.replaceOrUpdate(this, DBUtil.TABLE_MERCHANT_STORES, values,"merchant-stores");
mProgess.setVisibility(View.VISIBLE);
}
}
MyLocalCursorLoader 是一个扩展 CursorLoader 的类。 storeObject.getInt("id") 的值按
的顺序排列514 533 531 312 434 162 253 252 151 344 153 160 658
【问题讨论】: