Contacts_table has no column named contacts_name,though I insert it

I was wondering if someone could help me. I'm getting an error saying that column_name doesn't exist. But I included it in my DatabaseCleint .I can not find any error.

My DatabaseClass:

    public final class DatabaseClient extends SQLiteOpenHelper {
private SQLiteDatabase db;
private static final int DATABASE_VERSION=2;
private static final String DATABASE_NAME = "Contacts";
private static final String TABLE_NAME = "Contacts_table";
private static final String COLUMN_NAME = "contacts_name";
private static final String COLUMN_NUMBER = "contacts_number";

public DatabaseClient(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}




@Override
public void onCreate(SQLiteDatabase db) {

     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    //execute the create table query
    db.execSQL( "CREATE TABLE  " + TABLE_NAME + " ( " + COLUMN_NAME + " TEXT, " + COLUMN_NUMBER + " TEXT " + " );" );


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);

}
//add row to database
public  void addContact(String ContactName,String ContactNumber){
    ContentValues values=new ContentValues();
    values.put(COLUMN_NAME,ContactName);
    values.put(COLUMN_NUMBER,ContactNumber);
    db=getWritableDatabase();
    db.insert(TABLE_NAME,null,values);
    db.close();
}

public Cursor getallData(){
    //open db for writting
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor res=db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
    return res;
}
public int isTableExist(){
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor cursor=db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
    int count=cursor.getCount();
    return count;
}

}

My Main Class is:

    public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {


private static final String TAG = "MainActivity";
RecyclerView contactList;
ArrayList<Contact> shareContacts;
PhoneBookAdapter adapter;
DatabaseClient mydatabase;
Boolean permission=false;
int exist;
private String mOrderBy=ContactsContract.Contacts.DISPLAY_NAME_PRIMARY;
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS=99;
//TextView textView = null;
// String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
//String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //textView = (TextView) findViewById(R.id.out);
    mydatabase=new DatabaseClient(this);
    exist=mydatabase.isTableExist();
    contactList = findViewById(R.id.contact_list);
    permission=checkContactsPermission();
    if (permission){
        if (exist == 0) {

            getSupportLoaderManager().initLoader(1, null, this);
            displayAllContacts();
        }
    }else {
        if (exist==0){
            getSupportLoaderManager().initLoader(1, null, this);
            displayAllContacts();
        }
    }
    displayAllContacts();

}

private void displayAllContacts() {
    List<Contact> contactListitems=new ArrayList<>();
    Contact contactitems;
    Cursor c=mydatabase.getallData();
    if(c!=null && c.getCount()>0){
        while (c.moveToNext()){
            String name=c.getString(0);
            String number=c.getString(1);
            contactitems=new Contact();
            contactitems.setName(name);
            contactitems.setPhoneNumber(number);
            contactListitems.add(contactitems);
        }
    }

    PhoneBookAdapter adapter=new PhoneBookAdapter(contactListitems,getApplicationContext());
    contactList.setLayoutManager(new LinearLayoutManager(this));
    contactList.setAdapter(adapter);
}


@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if(id==1){
        return  new CursorLoader(this,ContactsContract.Contacts.CONTENT_URI,
                null,
                null,
                null,
                "upper(" +
                        Phone.DISPLAY_NAME + ")ASC");
    }
    return null;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if(data!=null && data.getCount()>0){
        while (data.moveToNext()){
            int hasPhoneNumber=Integer.parseInt(data.getString(data.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            if (hasPhoneNumber>0){
                String id=data.getString(data.getColumnIndex(ContactsContract.Contacts._ID));
                String name=data.getString(data.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
                ContentResolver contentResolver=getContentResolver();
                Cursor phone_cursor=contentResolver.query(Phone.CONTENT_URI,
                        null, Phone.CONTACT_ID + "=?",new String[]{id},null);
                if (phone_cursor.moveToNext()){
                    String phoneNumber=phone_cursor.getString(
                            phone_cursor.getColumnIndex(Phone.NUMBER)
                    );
                    phone_cursor.close();
                    mydatabase.addContact(name,phoneNumber);
                }

            }
        }
        displayAllContacts();
    }

}

@Override
public void onLoaderReset(Loader<Cursor> loader) {


}
public boolean checkContactsPermission(){
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
        return false;
    }else {
        return true;

    }
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case MY_PERMISSIONS_REQUEST_READ_CONTACTS:{
            if ((grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)==PackageManager.PERMISSION_GRANTED){
                    exist=mydatabase.isTableExist();
                    if(exist==0){
                        getLoaderManager().initLoader(1,null, (android.app.LoaderManager.LoaderCallbacks<Object>) getApplicationContext());
                    }
                    return;
                }
            }else {
                Toast.makeText(this,"permission denied",Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}

}

It show me error:

   01-14 17:09:08.163 9576-9576/com.demo.democontactlist E/SQLiteLog: (1) table Contacts_table has no column named contacts_name
01-14 17:09:08.164 9576-9576/com.demo.democontactlist E/SQLiteDatabase: Error inserting contacts_name=Amma contacts_number=+880 1787-586488
                                                                        android.database.sqlite.SQLiteException: table Contacts_table has no column named contacts_name (code 1): , while compiling: INSERT INTO Contacts_table(contacts_name,contacts_number) VALUES (?,?)
                                                                            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:898)
                                                                            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:509)
                                                                            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1499)
                                                                            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1371)
                                                                            at com.demo.democontactlist.DatabaseClient.addContact(DatabaseClient.java:54)
                                                                            at com.demo.democontactlist.MainActivity.onLoadFinished(MainActivity.java:121)
                                                                            at com.demo.democontactlist.MainActivity.onLoadFinished(MainActivity.java:32)

3 answers

  • answered 2018-01-14 11:38 JamesNickel

    Did you increase DATABASE_VERSION number after changing your database? onUpgrade() gets called everytime version number increases.

  • answered 2018-01-14 11:38 MikeT

    The issue is that the onCreate method is only automatically run when the database is created. Just changing the SQL used by onCreate will not apply the changes.

    There are 3 quick and easy solutions, all will result in the loss of data. The solutions are:-

    • Delete the App's data via settings.
    • Uninstall the App via settings.
    • If the onUpgrade is the typical DROP table(s) followed calling onCreate, then increase the Database version number.

    After doing one the above rerun the App.

    If you need to preserve the data then this SQL As Understood By SQLite - ALTER TABLE, may be helpful.

  • answered 2018-01-14 11:38 Adriana

    Just uninstall and install the app again and should work. Happen to me lots of times :)