2

I have searched StackOverFlow and found no solution for my problem.

SQLite Exception: no such table Error

No Such Table error

Android SQLite "no such table" exception

My Database Code:

package com.example.mylifeinformationsharedsocial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyUsersDatabase extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 7;
    private static final String DATABASE_NAME = "usersDatabase.db"; // Name of the file i save on the device
    private static final String TABLE_NAME = "usersTable"; // Name of the table

    // User columns
     private static final String UID = "_id"; // User identification number column
     private static final String FIRST_NAME = "firstName"; // User first name column
     private static final String LAST_NAME = "lastName"; // User last name column

     private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.DATABASE_NAME + " ( " 
    + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + MyUsersDatabase.FIRST_NAME + " TEXT, " 
    + MyUsersDatabase.LAST_NAME + " TEXT" + ");";

    private static final String DROP_TABLE = "DROP TABLE IF EXIST " + TABLE_NAME;

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

    // Creating tables
    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        try
        {
             db.execSQL(CREATE_TABLE);
        }
        catch (SQLException e)
        {
             e.printStackTrace();
        }
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        try
        {
            db.execSQL(DROP_TABLE);
            onCreate(db);
            Log.d("OnCreate", "OnCreate called");
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }

    public void addUser(User user) // Add a new row to the users table
    {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(MyUsersDatabase.UID,user.getId()); 
        contentValues.put(MyUsersDatabase.FIRST_NAME,user.getFirstName());      
        contentValues.put(MyUsersDatabase.LAST_NAME,user.getLastName());

       db.insert(MyUsersDatabase.TABLE_NAME, null, contentValues);

       db.close(); // Closing database connection
    }

    public void deleteUser(int userId) // Delete a row from the users table
    {
         SQLiteDatabase db = this.getWritableDatabase();

         db.execSQL("DELTE FROM " + DATABASE_NAME + " WHERE " + UID + "=\"" + userId + "\";");

        db.close(); // Closing database connection
    }

    public User getUser(int userId) 
    {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(MyUsersDatabase.TABLE_NAME, new String[] {MyUsersDatabase.UID,MyUsersDatabase.FIRST_NAME,
                 MyUsersDatabase.LAST_NAME},MyUsersDatabase.UID + "=?",
                 new String[] {String.valueOf(userId)}, null, null, null, null);
            if (cursor != null)
            {
                cursor.moveToFirst();
            }

            User user = new  User(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));

            return user;
    }
}

My Object(User) Class:

package com.example.mylifeinformationsharedsocial;

public class User 
{
    private int _id;
    private String firstName;
    private String lastName;

    public User(int id,String firstName,String lastName)
    {
        this._id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public User()
    {

    }

    public int getId() 
    {
        return _id;
   }
    public void setId(int id) 
    {
        this._id = id;
    }
    public String getFirstName() 
    {
        return firstName;
    }
    public void setFirstName(String firstName) 
    {
        this.firstName = firstName;
    }
    public String getLastName() 
    {
        return lastName;
    }
    public void setLastName(String lastName) 
    {
        this.lastName = lastName;
    }

    public String toString()
    {
       return "ID - " + this._id + " ,First name - " + this.firstName + " ,Last name - " + this.lastName;
    }
}

My Activity:(where I'm trying to add a row to the table database and get the SQLiteException: no such table)

package com.example.mylifeinformationsharedsocial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class SignUpActivity extends AppCompatActivity
{   
    Button signUpButton;

    EditText firstNameEditText;
    EditText lastNameEditText;
    EditText usernameEditText;
    EditText passwordEditText;
    EditText emailEditText;

    MyUsersDatabase myUsersDatabase;

    String userFirstName;
    String userLastName;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        viewsInitialization();

         getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        myUsersDatabase = new MyUsersDatabase(SignUpActivity.this);

        signUpButton.setOnClickListener(new View.OnClickListener()
        {   
            @Override
            public void onClick(View v) 
            {
                myUsersDatabase.addUser(new User(0,"Dan","Riman")); // Here the exception
               firstNameEditText.setText(myUsersDatabase.getUser(0).toString());
            }
        });
    }


    private void viewsInitialization()
    {
        signUpButton = (Button) findViewById(R.id.sign_up_button_id);

         firstNameEditText = (EditText) findViewById(R.id.sign_up_first_name_edit_text_id);
         lastNameEditText = (EditText) findViewById(R.id.last_name_edit_text_id);
         usernameEditText = (EditText) findViewById(R.id.username_edit_text_id);
        passwordEditText = (EditText) findViewById(R.id.password_edit_text_id);
        emailEditText = (EditText) findViewById(R.id.email_edit_text_id);
    }
}

So when i execute the line myUsersDatabase.addUser(new User(0,"Dan","Riman")); i get the SQLiteException: no such table when trying to add an Object to a table.

LogCat:

11-27 15:51:58.567: E/SQLiteLog(20624): (1) no such table: usersTable
11-27 15:51:58.568: D/AndroidRuntime(20624): Shutting down VM
11-27 15:51:58.569: E/AndroidRuntime(20624): FATAL EXCEPTION: main
11-27 15:51:58.569: E/AndroidRuntime(20624): Process: com.example.mylifeinformationsharedsocial, PID: 20624
11-27 15:51:58.569: E/AndroidRuntime(20624): android.database.sqlite.SQLiteException: no such table: usersTable (code 1):     , while compiling: SELECT _id, firstName, lastName FROM usersTable WHERE _id=?
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConne    ction.java:894)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:505)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.jav    a:1417)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1    264)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1135)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1341)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at com.example.mylifeinformationsharedsocial.MyUsersDatabase.getUser(MyUsersData    base.java:93)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at com.example.mylifeinformationsharedsocial.SignUpActivity$1.onClick(SignUpActi    vity.java:61)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.view.View.performClick(View.java:4763)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.view.View$PerformClick.run(View.java:19821)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.os.Handler.handleCallback(Handler.java:739)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.os.Handler.dispatchMessage(Handler.java:95)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.os.Looper.loop(Looper.java:135)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at android.app.ActivityThread.main(ActivityThread.java:5274)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at java.lang.reflect.Method.invoke(Native Method)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at java.lang.reflect.Method.invoke(Method.java:372)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:90    9)
11-27 15:51:58.569: E/AndroidRuntime(20624):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
6
  • db.execSQL("DELTE FROM " It should be DELETE not DELTE Commented Nov 27, 2015 at 15:20
  • @StefanBeike Thanks. But its not the problem right now :)) Commented Nov 27, 2015 at 15:23
  • @Andremoniy How do i know that? I think my onCreate method is never called and i dont know why. Commented Nov 27, 2015 at 15:24
  • ye I know. Thats the reason why I make a comment and no answer. Commented Nov 27, 2015 at 15:24
  • 1
    @StefanBeike Got you. Commented Nov 27, 2015 at 16:02

4 Answers 4

4

Your table creation is wrong.
Instead of

     private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.DATABASE_NAME + " ( " 

you have to write

     private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.TABLE_NAME + " ( " 

And also this one

db.execSQL("DELTE FROM " + DATABASE_NAME + " WHERE " + UID + "=\"" + userId + "\";");

has to be changed to

db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + UID + "=\"" + userId + "\";");
Sign up to request clarification or add additional context in comments.

15 Comments

Changed it. Still the same LogCat. Maybe i need to upgrade the version?
Yes. It has to be done every time you touch the database structure. Or uninstall and reinstall your app.
Its still the same problem and LogCat. I really think my onCreate() is never called.
After uninstalling and reinstallin i get android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
DONE. Its working. Thanks a lot to you and all the users who helped :).
|
2
private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.DATABASE_NAME + " ( "  // it should be Table name not database name
    + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + MyUsersDatabase.FIRST_NAME + " TEXT, " 
    + MyUsersDatabase.LAST_NAME + " TEXT" + ");";

Comments

1

The following line has issue

private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.DATABASE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MyUsersDatabase.FIRST_NAME + " TEXT, " + MyUsersDatabase.LAST_NAME + " TEXT" + ");";

After "CREATE TABLE " you have give Database Name change it to table name

private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " 
    + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + MyUsersDatabase.FIRST_NAME + " TEXT, " 
    + MyUsersDatabase.LAST_NAME + " TEXT" + ");";

Comments

1

You most likely forgot to upgrade your database.

OnCreate() is not called when you change the database version number. It is called only when the database does not already exist.

Changing the database version number causes OnUpgrade() to be called and it is here you need to write code to change your database schema from the old to the new version.

If you have added the new table to your onCreate code after the database already exists but have not written the code to perform an upgrade, the table will never exist.

Uninstall\reinstall your app (which will remove the current database and allow it to be recreated in your onCreate) or write code to upgrade your schema.

3 Comments

After uninstalling and reinstallin i get android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
That's a different issue and needs a new question.
So i will ask. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.