的Android - 光标索引越界异常
问题描述:
我的计划是想检查的选项表,如果它已经被设置(插入)的选项(如音量,振动)的。基本上,如果没有设置选项,表格中的第一列为0.如果第一行为空,则切换到默认选项,否则切换到选项集。我环绕我的选择检查者使用尝试捕捉一个收到此错误:所以我不知道如果我的代码是对我的需要的Android - 光标索引越界异常
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0.
我仍然福利局这个SQL的东西。
这是在OnCreate中(我的选项检查):
options = new DBFunctions(this);
try{
String row = "0".toString();
long l = Long.parseLong(row);
options.open();
String retId = options.getId(l);
int id = Integer.parseInt(retId);
options.close();
//codes for setting the options if/if no data in option table exists will be put here
}catch(Exception e){
String error = e.toString();
tv.setText(error);
}
这是我在我的DBFunctions的getId()。 Java的:
public String getId(long l) {
String[] columns = new String[]{"id", "volume", "vibrate", "theme"};
Cursor c = db.query(table, columns, "id=" + l, null, null, null, null);
if(c !=null){
c.moveToFirst();
String id = c.getString(1);
return id;
}
return null;
}
`
答
你试图从Cursor
是空的(0行)获取的数据,这抛出异常。我看到你的其他问题,我已经看到了你在options
表id
列设置为INTEGER PRIMARY KEY AUTOINCREMENT
。 AUTOINCREMENT意味着本专栏将每行插入数据库时增加它的价值,我认为它也开始在高于0(不知道)的值。这意味着你在getId
方法使查询总是会返回一个空Cursor
(您查询的行与id
0,但在数据库中是没有的)。
我不明白你的问题的第一部分中的一个插入/数据库中未插入并切换到默认值,所以我可以说怎么做你想做的。
下面是一些示例代码SharedPreferences
:
// When you want to check the status of the options
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this); //in an activity
// volumeStatus, vibrateStatus and themeStatus represent the current status of the options
boolean volumeStatus = prefs.getBoolean("volume_key", false); // if volumeStatus is false it is the first app run or the user put the volume to off
boolean vibrateStatus = prefs.getBoolean("vibrate_key", false); // the same as for volumestatus
String themeStatus = prefs.getString("theme_key", null); // if themeStatus is null it is the first run of the app or the user didn't choose a theme
// when the user modifies one of the preferences use this
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("volume_key", true); // the use sets the volume to on like in the database
editor.commit();
感谢我的其他问题,检查了.. :)我已经尝试过的显示值创建一个按钮,它显示所有我输入的数据,这意味着我的插入代码是正确的。然后我尝试了我的值检查器(我的代码如上),它仍然显示错误。我也尝试将我正在查找的行(之前为0)更改为1,仍然显示错误.. – 2012-04-08 17:51:33
@PhilipSy检查您的数据并在数据库中放入一个ID,然后使用该ID进行查询。问题是,我不明白你想做什么:用户在数据库中插入设置(只有一个,很多等?!?),但如果第一行是空的(?!?)切换到默认值? !? – Luksprog 2012-04-08 17:59:51
“我不明白你的问题的第一部分是插入/未插入数据库并切换到默认值,因此我可以说如何做你想做的事情。” - 我的意思是,如果您第一次使用该应用程序,它将设置默认选项(振动开启,音量开启等)。如果您设置了选项,它会检查您是否已经设置过。如果它检测到选项表有一个值,它只会更新您的选项,否则如果没有值,它会插入。基本上,我的选择表应包括1个排.. – 2012-04-08 18:00:13