AUTOINCREMENT in SQLite

0 Mohamed Elkady · March 5, 2015
hi guys, i tried many times to make my id incremented automatically but i fails 

here is my problem 

i create my database with this query 

@Override
    public void onCreate(SQLiteDatabase db) {
        String create_book_tb = "create table books ( id INTEGER PRIMARY KEY," +
                "title TEXT," +
                "author_name TEXT) ";
        db.execSQL(create_book_tb);
    }

this is the toString method in Book class
   

 @Override 
public String toString() {
        return "Book [id="+ getId() +", title="+ getTitle() +","+ getAuthorName() +"]";
    }



adding my book  using 

public void addBook(Book book) {
        Log.d("addBook", book.toString());
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, book.getTitle());
        values.put(KEY_AUTHOR_NAME, book.getAuthorName());

        long i = db.insert(TABLE_BOOKS, null, values);
        db.close();
    }


in MainActivity.java


        mySQLiteHelper.addBook(new Book("Java","Elkady"));
        mySQLiteHelper.addBook(new Book("C#", "Elkady2"));
        mySQLiteHelper.addBook(new Book("Android", "Elkady3"));


finally this is the output

03-05 05:04:25.946  18420-18420/? D/addBook? Book [id=0, title=Java,Elkady]
03-05 05:04:25.971  18420-18420/? D/addBook? Book [id=0, title=C#,Elkady2]
03-05 05:04:25.986  18420-18420/? D/addBook? Book [id=0, title=Android,Elkady3]


why id = 0 in each book
thanks in advance

Post a Reply

Replies

Oldest  Newest  Rating
0 Mohamad Mirohamadi · March 7, 2015
Simply add autoincrement keyword to your id column:


@Override
   public void onCreate(SQLiteDatabase db) {
       String create_book_tb = "create table books ( id INTEGER PRIMARY KEY AUTOINCREMENT," +
               "title TEXT," +
               "author_name TEXT) ";
       db.execSQL(create_book_tb);
   }
  • 1

Java / Android Development

107,278 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator