如果它不包含单个行(空表),我需要向表中插入值。如果表中已存在数据,则无需插入。我使用了以下代码。
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + SAMPLE_TABLE_NAME
+ " (rowid INT , songname VARCHAR," + " count INT);");
int len = MP3Activity.songlist.size();
Log.v("songlist len", Integer.toString(len));
cur = sampleDB.rawQuery("SELECT COUNT(*) FROM "+ SAMPLE_TABLE_NAME ,null);
if (cur != null) {
if(cur.getInt(0)<=1) //exception at this line.
{
for (int s = 0; s < MP3Activity.songlist.size(); s++) {
Log.v("Before insert", "1");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ("
+ row_id++ + ",\"" + MP3Activity.songlist.get(s) + "\","
+ count + ");");
Log.v("After insert", "1");
}
}
else
{
Log.v("inside else......","");
}
}
cur.close();
c = sampleDB.rawQuery("SELECT songname, count, rowid FROM "
+ SAMPLE_TABLE_NAME + " where count=0 ", null);
if (c != null) {
if (c.moveToFirst()) {
do {
String songName = c.getString(c.getColumnIndex("songname"));
int count = c.getInt(c.getColumnIndex("count"));
int rid=c.getInt(c.getColumnIndex("rowid"));
results.add("Rowid: " + rid + ",Song Name: " + songName + ",Count: " + count);
} while (c.moveToNext());
}
}
c.close();
int reslen = results.size();
Log.v("Length of result", Integer.toString(reslen));
for (int i = 0; i < results.size(); i++) {
Log.v("Element in result", results.get(i));
}
/*for (int k = 0; k < results.size(); k++) {
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
}*/
sampleDB.close();
我遇到以下异常。
01-19 15:22:42.059: E/AndroidRuntime(464): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
01-19 15:22:42.059: E/AndroidRuntime(464): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
01-19 15:22:42.059: E/AndroidRuntime(464): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:172)
01-19 15:22:42.059: E/AndroidRuntime(464): at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:84)
01-19 15:22:42.059: E/AndroidRuntime(464): at com.mp3.Frequent.onCreate(Frequent.java:46)
01-19 15:22:42.059: E/AndroidRuntime(464): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
01-19 15:22:42.059: E/AndroidRuntime(464): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
答案 0 :(得分:0)
您需要将光标移动到第一个元素(如果有),就像您为第二个查询所做的那样:即在访问列值的游标之前检查c.moveToFirst()的结果。
答案 1 :(得分:0)
如果您的表为空,那么如何在此行中获取列索引
if(cur.getInt(0)<=1) //exception at this line.
所以用
替换它if(cur.getCount()<=1) //exception at this line.
编辑:
而不是检查上述条件,你也可以像这样检查
if(cur.getCount()>0) //exception at this line.
{
//Already Inserted value
}
else
{
for (int s = 0; s < MP3Activity.songlist.size(); s++) {
Log.v("Before insert", "1");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAME + " Values ("
+ row_id++ + ",\"" + MP3Activity.songlist.get(s) + "\","
+ count + ");");
Log.v("After insert", "1");
}
}