我正在创建一个应用程序并使用SQLite来保存我的设置数据。但我一直收到这个错误: android.database.CursorIndexOutOfBoundsException:请求索引0,大小为0
我尝试插入默认值但仍然出现此错误。也许有些事我误解了。这是文件
public static final String DATABASE_NAME = "AppData.db";
/**
* table note contain id, title, content
*/
public static final String TABLE_DATA_NAME = "tb_mydata";
public static final String TABLE_SETTING_NAME = "tb_mysetting";
public static final String NOTE_COLUMN_ID = "id";
public static final String NOTE_COLUMN_COLOR = "color";
public static final String NOTE_COLUMN_SENSORID = "sensorid";
public static final String NOTE_COLUMN_TITLE = "title";
public static final String NOTE_COLUMN_VALUE = "value";
public static final String NOTE_COLUMN_TIME = "time";
public static final String NOTE_SETTING_LOC = "loc";
public static final String NOTE_SETTING_LANG = "lang";
public static final String NOTE_SETTING_SENS = "sensitive";
/**
* string for create table note
*/
public static final String CREATE_TABLE_DATA_NOTE =
"CREATE TABLE " + TABLE_DATA_NAME + "(" +
NOTE_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" +
"," + NOTE_COLUMN_SENSORID + "INTEGER" +
"," + NOTE_COLUMN_TITLE + " TEXT NOT NULL" +
"," + NOTE_COLUMN_VALUE + " TEXT NOT NULL" +
"," + NOTE_COLUMN_TIME + "DATETIME" +
"," + NOTE_COLUMN_COLOR + "TEXT" +
")";
public static final String CREATE_TABLE_SETTING_NOTE =
"CREATE TABLE " + TABLE_SETTING_NAME + "(" +
NOTE_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" +
"," + NOTE_SETTING_LANG + "TEXT NOT NULL" +
"," + NOTE_SETTING_LOC + " TEXT NOT NULL" +
"," + NOTE_SETTING_SENS + " TEXT NOT NULL" +
")";
/**
* value for update database
*/
public static final int DATA_VERSION = 1;
/**
* Sqlite database
*/
private SQLiteDatabase db;
public MySQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATA_VERSION);
}
/**
* create db when app start, and only call when database don't create
* When database created, it will not call
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_DATA_NOTE);
db.execSQL(CREATE_TABLE_SETTING_NOTE);
}
/**
* call when change DATA_VERSION
* help we update database
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
/**
* open database
*/
public void open() {
try {
db = getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* close database
*/
public void close() {
if (db != null && db.isOpen()) {
try {
db.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Cursor getAll(String sql) {
open();
Cursor cursor = db.rawQuery(sql, null);
if (cursor != null) {
cursor.moveToFirst();
}
close();
return cursor;
}
public boolean insertNote(String sensorid, String title, String value, String time, String color) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NOTE_COLUMN_SENSORID,sensorid);
contentValues.put(NOTE_COLUMN_TITLE, title);
contentValues.put(NOTE_COLUMN_VALUE, value);
contentValues.put(NOTE_COLUMN_TIME,time);
contentValues.put(NOTE_COLUMN_COLOR, color);
try {
db.insert(TABLE_DATA_NAME, null, contentValues);
return true;
} catch (Exception e) {
return false;
}
}
public boolean insertSettingNote(String lang, String loc, String sens) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NOTE_SETTING_LANG,lang);
contentValues.put(NOTE_SETTING_LOC, loc);
contentValues.put(NOTE_SETTING_SENS, sens);
try {
db.insert(TABLE_SETTING_NAME, null, contentValues);
return true;
} catch (Exception e) {
return false;
}
}
/**
* update values to table
*
* @return index row update
*/
public boolean update(String table, ContentValues values, String where) {
open();
//values.put();
long index = db.update(table, values, where, null);
close();
return index > 0;
}
/**
* delete id row of table
*/
public boolean delete(String table, String where) {
open();
long index = db.delete(table, where, null);
close();
return index > 0;
}
public Note getNote(String sql) {
Note note = null;
Cursor cursor = getAll(sql);
if (cursor != null) {
note = cursorToNote(cursor);
cursor.close();
}
return note;
}
public SettingNote getSettingNote(String sql) {
SettingNote stnote = null;
Cursor cursor = getAll(sql);
if (cursor != null) {
stnote = cursorToSettingNote(cursor);
cursor.close();
}
return stnote;
}
/**
* @param sql get all notes with sql command
* @return arraylist of note
*/
public ArrayList<Note> getListNote(String sql) {
ArrayList<Note> list = new ArrayList<>();
Cursor cursor = getAll(sql);
while (!cursor.isAfterLast()) {
list.add(cursorToNote(cursor));
cursor.moveToNext();
}
cursor.close();
return list;
}
/**
* insert note to table
*
* @param note note to insert
* @return id of note
*/
/**
* @param note note to update
* @return id of note update
*/
public boolean updateNote(Note note) {
return update(TABLE_DATA_NAME, noteToValues(note), NOTE_COLUMN_ID + " = " + note.getId());
}
/**
* delete id row of table
*/
public boolean deleteNote(Note note) {
return delete(TABLE_DATA_NAME, NOTE_COLUMN_ID + " = " + note.getId());
}
/**
* convert note to contentvalues
* don't put id of note because
* when insert id will auto create
* when update we don't update id
*/
private ContentValues noteToValues(Note note) {
ContentValues values = new ContentValues();
values.put(NOTE_COLUMN_TITLE, note.getTitle());
values.put(NOTE_COLUMN_VALUE, note.getValue());
return values;
}
private ContentValues noteToValues(SettingNote stnote) {
ContentValues values = new ContentValues();
values.put(NOTE_SETTING_SENS, stnote.getSensitive());
values.put(NOTE_SETTING_LOC, stnote.getLoc());
values.put(NOTE_SETTING_LANG, stnote.getLang());
return values;
}
/**
* convert cursor to note
*/
private Note cursorToNote(Cursor cursor) {
Note note = new Note();
note.setId(cursor.getInt(cursor.getColumnIndex(NOTE_COLUMN_ID)))
.setTitle(cursor.getString(cursor.getColumnIndex(NOTE_COLUMN_TITLE)))
.setvalue(cursor.getString(cursor.getColumnIndex(NOTE_COLUMN_VALUE)));
return note;
}
private SettingNote cursorToSettingNote(Cursor cursor) {
SettingNote Stnote = new SettingNote();
Stnote.setId(cursor.getInt(cursor.getColumnIndex(NOTE_COLUMN_ID)));
Stnote.setLang(cursor.getString(cursor.getColumnIndex(NOTE_SETTING_LANG)));
Stnote.setLoc(cursor.getString(cursor.getColumnIndex(NOTE_SETTING_LOC)));
Stnote.setSensitive(cursor.getString(cursor.getColumnIndex(NOTE_SETTING_SENS)));
return Stnote;
}
public long getProfilesCount(String databasename) {
SQLiteDatabase db = this.getReadableDatabase();
long cnt = DatabaseUtils.queryNumEntries(db, databasename);
db.close();
return cnt;
}
RadioButton mRGLangEng, mRGLangViet, mRGLocHN, mRGLocDN;
CheckBox Sens;
Locale myLocale;
MySQLHelper sqlHelper;
SettingNote stNote;
Button Save;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_setting, container, false);
Sens = (CheckBox) view.findViewById(R.id.SensCheck);
mRGLangEng = (RadioButton) view.findViewById(R.id.Lang_Eng);
mRGLangViet = (RadioButton) view.findViewById(R.id.Lang_Vie);
mRGLocHN = (RadioButton) view.findViewById(R.id.locHanoi);
mRGLocDN = (RadioButton) view.findViewById(R.id.locDanang);
Save = (Button) view.findViewById(R.id.save);
sqlHelper = new MySQLHelper(this.getActivity());
sqlHelper.getSettingNote(MySQLHelper.TABLE_SETTING_NAME);
if (stNote.getLang() == "en") {
mRGLangViet.setChecked(false);
mRGLangEng.setChecked(true);
} else {
mRGLangViet.setChecked(true);
mRGLangEng.setChecked(false);
}
if (stNote.getSensitive() == "no") {
Sens.setChecked(false);
Constants.USER_LIMITATION = 200;
} else {
Sens.setChecked(true);
Constants.USER_LIMITATION = 150;
}
if (stNote.getLang() == "hn") {
mRGLocHN.setChecked(true);
mRGLocDN.setChecked(false);
Constants.API_TYPE_AQI = 1; // Sensor's ID at HN_RDC
Constants.API_TYPE_TMP = 2;
Constants.API_TYPE_HUM = 3;
} else {
mRGLocHN.setChecked(false);
mRGLocDN.setChecked(true);
Constants.API_TYPE_AQI = 7;
Constants.API_TYPE_TMP = 8;
Constants.API_TYPE_HUM = 9;
}
mRGLocHN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRGLocDN.setChecked(false);
Constants.STR_LOC = "hn";
}
});
mRGLocDN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRGLocHN.setChecked(false);
Constants.STR_LOC = "dn";
}
});
mRGLangViet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRGLangEng.setChecked(false);
Constants.STR_LANG = "vi";
setLocale("vi");
}
});
mRGLangEng.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRGLangViet.setChecked(false);
Constants.STR_LANG = "en";
setLocale("en");
}
});
Sens.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Sens.isChecked()){
Sens.setChecked(false);
Constants.STR_SENS = "no";
}else{
Sens.setChecked(true);
Constants.STR_SENS = "yes";
}
}
});
Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
cv.put(MySQLHelper.NOTE_SETTING_LANG,Constants.STR_LANG);
cv.put(MySQLHelper.NOTE_SETTING_LOC, Constants.STR_LOC);
cv.put(MySQLHelper.NOTE_SETTING_SENS, Constants.STR_SENS);
sqlHelper.update(MySQLHelper.TABLE_SETTING_NAME,cv,"id = 1");
}
});
return view;
}
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
}
这是错误
11-10 21:54:14.487 2174-2174/com.journaldev.viewpager E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.journaldev.viewpager, PID: 2174
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:68)
at com.journaldev.viewpager.MyApplication.MyApp.MySQLHelper.cursorToSettingNote(MySQLHelper.java:270)
at com.journaldev.viewpager.MyApplication.MyApp.MySQLHelper.getSettingNote(MySQLHelper.java:191)
at com.journaldev.viewpager.MyApplication.MyApp.TabSetting.onCreateView(TabSetting.java:41)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
11-10 21:54:42.516 2174-2174/com.journaldev.viewpager I/Process: Sending signal. PID: 2174 SIG: 9
答案 0 :(得分:0)
您需要检查光标是否有值,并且需要在获取值之前将光标移动到第一个位置以避免此问题。还有一件事尝试使用try catch块并在finally块中关闭光标,在关闭光标之前检查光标是否关闭如下:
Cursor cursor = null;
try {
String selectQuery = "your query";
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
//Looping cursor and fetching the value...
} while (cursor.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
希望这有用:)
答案 1 :(得分:0)
这样做
sqlHelper.getSettingNote("select * from "+MySQLHelper.TABLE_SETTING_NAME);