Thursday, April 17, 2014

android sqlite query problem


Code:
package com.cxw.sqliteopenhelper;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class OpenHelperMainActivity extends Activity {

@ Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_open_helper_main);
MyDBHelper helper = new MyDBHelper (this);

helper.insert ();
helper.query ();
}
class MyDBHelper extends SQLiteOpenHelper {
private static final String CREATE_TABLE_SQL = "create table TempTb1 (_id integer, name text)";
private SQLiteDatabase db;
MyDBHelper (Context c)
{
super (c, "test.db", null, 2);

}
@ Override
public void onCreate (SQLiteDatabase db) {
/ / TODO Auto-generated method stub

db.execSQL (CREATE_TABLE_SQL);

}
@ Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
/ / TODO Auto-generated method stub

}
private void insert ()
{
String sql = "insert into TempTb1 (_id, name) values ​​(1, 'zhangsan')";
getWritableDatabase () execSQL (sql);.
}
private void query ()
{
. Cursor c = getWritableDatabase () query ("TempTb1", null, null, null, null, null, null);
if (c.moveToFirst ())
{
for (int i = 0; i {
c.move (i);
int id = c.getInt (0);

String name = c.getString (1);

System.out.println (id + ":" + name);


}
c.close ();
}
}

}


@ Override
public boolean onCreateOptionsMenu (Menu menu) {
/ / Inflate the menu; this adds items to the action bar if it is present
.getMenuInflater () inflate (R.menu.activity_open_helper_main, menu);.
return true;
}

}
Error:

09-20 06:21:55.300: W / dalvikvm (2302): threadid = 1: thread exiting with uncaught exception (group = 0x40a70930)
09-20 06:21:55.330: E / AndroidRuntime (2302): java.lang.RuntimeException: Unable to start activity ComponentInfo {com.cxw.sqliteopenhelper / com.cxw.sqliteopenhelper.OpenHelperMainActivity}: android.database.CursorIndexOutOfBoundsException: Index 17 requested, with a size of 17
09-20 06:21:55.330: E / AndroidRuntime (2302): at android.app.ActivityThread.performLaunchActivity (ActivityThread.java: 2180)
09-20 06:21:55.330: E / AndroidRuntime (2302): at android.database.AbstractWindowedCursor.getInt (AbstractWindowedCursor.java: 68)
09-20 06:21:55.330: E / AndroidRuntime (2302): at com.cxw.sqliteopenhelper.OpenHelperMainActivity $ MyDBHelper.query (OpenHelperMainActivity.java: 57)

<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->

No comments:

Post a Comment