Search code examples
androidmysqldatabasesqliteopenhelper

Android SQLiteDatabase Table


I am working on an android app and I have a problem i can't solve. I hope you guys can help me.

I get this error:

android.database.sqlite.SQLiteException: table FBFriends has no column named id (code 1): , while compiling: INSERT INTO FBFriends(id,name) VALUES (?,?)

Like you all know, the error is that it can't find the table. But I make the table.

  public DatabaseManager(Context context) {
            //referentie naar cursus
            super(context, DATABASE_NAME, null, 1);
        }

       @Override
        public void onCreate(SQLiteDatabase db) {
           //SQL for creating a new table

           Log.d(TAG, "Tabel gemaakd");
            String CREATE_DATABASE_TABLE ="CREATE TABLE Friends (id VARCHAR(255) PRIMARY KEY not null , name VARCHAR(255) )";
            db.execSQL(CREATE_DATABASE_TABLE);
       }
   @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older database if existed
        db.execSQL("DROP TABLE IF EXISTS Friends");
        Log.d(TAG, "Tabel verwijdert");
        // create new table
        this.onCreate(db);
    }

And this is the function for adding data to the database.

private static final String TABLE_FBFriends = "Friends";    
private static final String KEY_ID = "id";
private static final String KEY_Name = "name";


    private static final String[] COLUMNS = {KEY_ID,KEY_Name};
    public boolean addPersons(ArrayList<Person> listOfPersons)
    {
        Log.d(TAG, "add");
        //get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();
        Log.d(TAG, "toevoegen add");
        //create ContentValues to add key "column"/value
        for (Person p:listOfPersons) {
            Log.d(TAG, "FOREACH");
            ContentValues values = new ContentValues();
                values.put(KEY_ID, p.getId());
            Log.d(TAG, "first VALUE");
            values.put(KEY_Name, p.getName()); // get title
            Log.d(TAG, "second VALUE");
            Log.d(TAG, "add " + values.toString());
            try{
                // insert orThrow an exeption
                db.insertOrThrow(TABLE_FBFriends, null, values);
//key/value -> keys = column names/ values = column values
                }
                catch (SQLException e) {
                    Log.d(TAG,  e.toString());
                   return false;
                    }
        }
            db.close();
            return true;
        }

Thank you guys!

Regards, Stijn


Solution

  • it's because you still have your old table and dont have the new table. first to see, dont change the name table directly in your onCreate database helper after you create one. because it's only create table on the first time execute. if you want to change your name table, just create a function to use alter table query and change the old name table with the new one.