Reputation: 780
My program is suppose to check the options table if it already set(inserted) an option(e.g. volume, vibration). Basically, if an option is not set, the first column at the table is 0. If the first row is empty, then switch to default option, else, switch to the option set. I surround my option checker with a try catch an receive this error:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0.
I'm still newb to this sql stuff so I'm not sure if my codes are right to my needs.
This is my option checker at the 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);
}
This is my getId() in my DBFunctions. 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;
}
`
Upvotes: 0
Views: 3892
Reputation: 87064
You're trying to get data from a Cursor
that is empty(0 rows) and this throws that exception. I saw your other questions and I've seen that your id
column in the options
table is set as INTEGER PRIMARY KEY AUTOINCREMENT
. AUTOINCREMENT means that this column will increment its value each time a row is inserted in the database and I think it is also starting at a value above 0(not sure). This means that the query you make in the getId
method will always return an empty Cursor
(you query for the rows with id
0 but there are none in the database).
I didn't understand the first part of your question the one with inserted/not inserted in the database and switching to defaults so I can say how to do what you want.
Here is some sample code with 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();
Upvotes: 2