开发者

My Android application is crushing if the database is not populated

I got some problem with my database in my Android application. Perhaps, my application is working but let me explain you.

Here are just parts of the code from my app.. i don't want to paste the whole it's not needed.

private SQLiteStatement insertStmt;
   private static final String INSERT = "insert into "
      + TABLE_NAME + "(name,surname) values (?,?)";


public DataHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
    }

public long insert(String name, String surname) {
      this.insertStmt.bindString(1, name);
      this.insertStmt.bindString(2, surname);
      retur开发者_JAVA技巧n this.insertStmt.executeInsert();
   }

@Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + 
          "(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, surname TEXT)");
      }

So when i try to run my app i get Force close, but when i put manually :

dh.insert("test", "ooo");

..in the onCreate method in my main activity everything is fine and working. So, the conclusion is that i must put some value for the first time i run the app so it can work properly. I thought maybe to update that row with the new informations that i insert later through some TextView's from the app but i'm wondering if there is smarter solution than this?


Obviously there is no error with your insert, at least it's not what crashes your App.

Since you're getting a CursorIndexOutOfBoundsException, it means you have somewhere a select query and try to move or set it before checking if it's has any rows at all.

This usually happens if you move the cursor to a non-existing index, i.e. cursor.moveToFirst() while your cursor is empty or cursor.move(n) where n is bigger than cursor.getCount()-1

Before moving or accessing a cursor you ALWAYS have to check if any rows are returned!

Cursor c = db.query(...);
if(c!=null && c.getCount()>0) {
    c.moveToFirst(); // (or c.move(0))

    // Do your cursor operations here!
}

Obviously your insert fails for some reason, you can easily check this, with:

long insertId = dh.insert("test", "ooo");

if(insertId > 0) {
    // insert was successfull 
} else {
    // insert failed
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜