所以我有两个我目前正在尝试访问的变量。 waterAmt和bucketExp。我不确定为什么waterAmt变量工作正常但另一个不是。似乎bucketExp没有以它应该的方式存储,即使它存储与waterAmt相同。提前感谢您的帮助。
访问数据库的代码:
//pull data
data = new Database(SetupTimerPC1.this);
data.open();
bucketExpTotal = data.getBucketExp();
totalWater = data.getWaterAmt();
data.close();
//add new data to old
bucketExpTotal += bucketExp;
totalWater += waterAmt;
//push data
data.open();
data.bucketExpEntry(bucketExpTotal);
data.waterAmountEntry(totalWater);
data.close();
将waterAmt输入数据库的代码:
public long waterAmountEntry(int waterAmt)
{
ContentValues cv = new ContentValues();
cv.put(KEY_WATER, waterAmt);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}//end waterAmountEntry function
将bucketExp输入数据库的代码:
public long bucketExpEntry(int bucketExp)
{
ContentValues cv = new ContentValues();
cv.put(KEY_BUCKETEXP, bucketExp);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}//end bucketExpEntry function
从数据库中提取waterAmt的代码:
public int getWaterAmt()
{
int waterAmount = 0, iWaterAmount = 0;
String[] columns = new String[] {KEY_ROWID, KEY_ROCK, KEY_METEORROCK, KEY_WATER,
KEY_POPULATION, KEY_SHOVEL, KEY_BUCKET, KEY_PICKAXE, KEY_SHOVELEXP,
KEY_BUCKETEXP, KEY_PICKAXEEXP};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (c != null && c.getCount() > 0)
{
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
iWaterAmount = c.getColumnIndex(KEY_WATER);
waterAmount = c.getInt(iWaterAmount);
}//end for
c.close();
return waterAmount;
}//end if
return 0;
}//end getWaterAmt function
从数据库中提取bucketExp的代码:
public int getBucketExp()
{
int bucketExp = 0, iBucketExp = 0;
String[] columns = new String[] {KEY_ROWID, KEY_ROCK, KEY_METEORROCK, KEY_WATER,
KEY_POPULATION, KEY_SHOVEL, KEY_BUCKET, KEY_PICKAXE, KEY_SHOVELEXP,
KEY_BUCKETEXP, KEY_PICKAXEEXP};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
if (c != null && c.getCount() > 0)
{
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
iBucketExp = c.getColumnIndex(KEY_BUCKETEXP);
bucketExp = c.getInt(iBucketExp);
}//end for
c.close();
return bucketExp;
}//end if
return 0;
}//end getBucketExp function
答案 0 :(得分:0)
现在您的查询相当于:
"SELECT [columns] FROM [table];"
这将返回表中的所有行。接下来,您将迭代整个结果集,并在每次迭代中将值设置为返回等于结果行中的某个列。
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
bucketExp = cursor.getInt(...);
}
基本上这意味着bucketExp
将等于结果最后一行中此列的值。
我想要的 认为 是特定行/记录的值。您需要更改查询以返回您正在查找的行,并摆脱for
循环。这是一个通过ID查找特定行并返回bucketExp:
public int getBucketExp(long id) {
String[] columns = new String[] { KEY_BUCKETEXP };
String where = KEY_ROWID + " = ?";
String[] whereArgs = new String[] { Long.toString(id) };
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, where, whereArgs,
null, null, null);
int bucketExp = 0;
if (cursor.moveToFirst()) {
bucketExp = cursor.getInt(cursor.getColumnIndex(KEY_BUCKETEXP));
}
return bucketExp;
}