20

I'm starting into SQLite and databases in Android and I just found this issue. I have read a lot of similar questions but I have not found a solution yet.

This is the error I'm getting:

E/AndroidRuntime(529): Caused by: android.database.sqlite.SQLiteException: no such table: ligas_bd: , while compiling: SELECT * FROM ligas_bd

This is my code.

DBHelper myDbHelper = new DBHelper(this);
myDbHelper = new DBHelper(this);
try {
    myDbHelper.createDataBase();
} catch (IOException ioe) {
    throw new Error("Unable to create database");
}
try {
    myDbHelper.open();
    SQLiteDatabase db = null;
    db = myDbHelper.getWritableDatabase();
    String[] args = new String[] {""};
    Cursor c = db.rawQuery(" SELECT * FROM ligas_bd", args); <---- Error in this line
    if (c.moveToFirst()) {
        do {
            String cod = c.getString(0);
            String nombre = c.getString(1);
            String flag = c.getString(0);
            String cod_url = c.getString(0);
            ligas.add(new Item_Liga(nombre, flag, cod, cod_url));
        } while(c.moveToNext());
    }
}catch(SQLException sqle){
    throw sqle;
}

DBHelper.java

public class DBHelper extends SQLiteOpenHelper{
private static String DB_NAME = "ligas_bd";
private SQLiteDatabase myDataBase;
private final Context myContext;

public DBHelper(Context context) {
    super(context, DB_NAME, null, 1);
    this.myContext = context;
}

public void createDataBase() throws IOException{
    boolean dbExist = checkDataBase();
    if(dbExist){ }
    else {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copiando Base de Datos");
        }
    }
}
private boolean checkDataBase(){
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch(SQLiteException e) { }
    if(checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException{
    InputStream myInput = myContext.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0) {
        myOutput.write(buffer, 0, length);
    }
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

public void open() throws SQLException{
    try {
        createDataBase();
    } catch (IOException e) {
        throw new Error("Ha sido imposible crear la Base de Datos");
    }
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

@Override
public synchronized void close() {
    if(myDataBase != null)
    myDataBase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) { }

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }

I also checked in my phone with root explorer data/data/mypackagename/databases and the database appears there as normal.

My database and the main table have the same name, as you can see in this pic of SQLite database browser:

screen capture

I am not creating the table, I created it before using SQLite Database Browser and I am just trying to read from it


I don't know how, but I finally fixed it. I just started again, this time following this tutorial. Hope it helps!

1
  • is the path where the database has to be. It is /data/data/mypackagename/databases Commented Mar 29, 2012 at 8:04

11 Answers 11

19

This is only a guess but I can see three possible things are happening here...

  1. Calling this.getReadableDatabase() in your createDatabase() method is automatically creating an empty database.
  2. Your attempt to copy your pre-created database from your assets folder is failing or the database is being copied to the wrong place.
  3. The empty database created in step 1 (above) is the one that is being queried when you call db.rawQuery(...) from your main code.

To explain further it is usefult to look at the source for SQLiteOpenHelper

When you create an instance of SQLiteOpenHelper it sets things like the database name and version but it does not create the database. Instead, the first call to either getReadableDatabase() or getWritableDatabase() checks to see if the database exists and if it doesn't it creates it. After creating the empty database, the onCreate(...) method is called which, in your case, does nothing.

On to point 2 (above) - you say that DB_PATH is /data/data/mypackagename/databases. If that is really the case and you have no trailing / then the line...

String myPath = DB_PATH + DB_NAME;

...will set myPath to /data/data/mypackagename/databasesligas_db. In that case, even if the copy from assets succeeds, the copied database isn't going to be where you expect it to be.

Finally on point 3 (above) when you call db.rawQuery(...) the instance that db points to is returned by the previous call to getWritableDatabase(). Assuming the copy from assets has failed or that it has been copied to the incorrect path, db will be pointing at the empty database created in step 1.

The error you get is that the table doesn't exist and it isn't an error indicating the database doesn't exist - the only logical explanation is that it's performing a query on an empty database and not the one that has been copied from assets.

EDIT: One other thing I meant to mention. It isn't a good idea to use hard-coded paths to any of the Android directories. For example - although on most devices, the directory where databases are created will be /data/data/<package-name>/databases this is not a guarantee. It is much safer if you call the getDatabasePath(...) method as it will return a File object which can be used to get the path to the databases directory used by the Android database classes.

Sign up to request clarification or add additional context in comments.

3 Comments

the path is OK, it has the "/" at the end, so that's not the mistake. If I change the path is throws another exception so the path is ok and it is finding correctly the database. It is a weird thing
@koneX: In that case, try calling File dbFile = getDatabasePath("ligas_bd") and log the path of the dbFile object using logcat or simply show it using a Toast. Do this immediately before calling db.rawQuery(...) in your main code. This will at least show you the path that the SQLiteOpenHelper is using to access the database.
@Squonk : man you are right. I have faced same problem and i used public SQLiteDatabase opendatabase(){ try{ String mypath = DB_PATH + DB_NAME; database = SQLiteDatabase.openDatabase(mypath, null,SQLiteDatabase.OPEN_READWRITE); }catch(SQLiteException sle){ System.out.println("Exception while opning database : "+sle); } return database; } Instead of getWritableDatabase();
17

I had the same problem and fixed it by cleaning the project and deleting the app off my testing device and reinstalling it. I believe it occurred because I followed another tutorial that created an empty database by mistake. The corrected code was retrieving the old empty database.

4 Comments

You sir, deserve many more upvotes than I am able to give. I had this error too, and your advice is what solved the issue. Thank you!!!!
In my case I had to use an entirely new emulator but this is what worked for me too
Most likely to be the answer
I tried with app uninstallation/ reinstallation But same error after reinstalling the app . what should I do now
13

If you are running your app in your device, go to >>Settings (in Android device)>>>application>>>locate your application>>clear data and cache. After that, debug or install again your new application..

I solved this problem by doing that...

Comments

0

The exception is very clear, you've created the database (ligas_db) but not a table within it (no such table exception = there is not a table named ligas_db)

Check this: http://www.vogella.de/articles/AndroidSQLite/article.html

(¿Eres Antonio Recio? jaja)

1 Comment

The database name and the table name are the same, see the photo above in the edit. Thanks (Y no, no soy Antonio Recio jajajajaja)
0

You have ligas_bd as the name of the database and you are trying to SELECT from it.

1 Comment

The database and the table have the same name, see the edit in the above post please. Thanks
0

You need to create table first before you selecting from it. May you have created before but you need to create it after opening database connection.

5 Comments

I dont know what you mean. I created it before using its own editor, and now I have to create it in the code? And how to do that?
you are using this : db = myDbHelper.getWritableDatabase(); After this write code to create table if not exist. or open db connection before your create table statement.
I want to get the tables from a existing db that i put on assets folder, I dont want to create any table
okey.then you need to copy your database to /data/data/your_package_name/database/ path from your assets folder . And then can open database.check your DB PATH. and you should copy .sqlite file . Rename to .sqlite.
I also doing that if you see the code shown above. I also tried renaming the file to .sqlite and it was just the same. Anyway, I could finally fix it.
0

My problem was I left "/databases/" off the end of my path name. What was so confusing for me is the code worked before when I was loading a dbconnection and storing it as an instance variable. Then when I needed to make use of the getReadableDatabase() and getWritableDatabase () methods, they kept pulling in the empty database created in the "real" databases path.

INCORRECT /data/data/mypackagename/

CORRECT /data/data/mypackagename/databases/

+1 to @Squonk who's answer finally helped me track this down!

Comments

0

I had the same problem try to include .db extension in the file name like:

private static String DB_NAME = "ligas_bd.db";

Comments

0

Faced same problem i suggest don't use rawQuery

SQLiteDatabase DB=this.getWritableDatabase();
Cursor data;
String[] columns = {"deviceid"};
String selection = "deviceid" + " =?";
String[] selectionArgs = { devicename };
data=DB.query("Btconnection",columns,selection,selectionArgs,null,null,null);

Comments

0

Use TFDQuery.Open('commands') or TFDQuery.ExecSql('commands') This resolve my problem.

Comments

0

i had copied the "DatabaseManager" class from somewhere and modified it, my problem as 'Squonk' said was that there was somewhere in the code that was using getReadableDatabase() before it get the chance to copy the database and it was creating an empty database by itself...

!!also another problem was that my assets folder was in the "/src/androidTest/assets" and it should be inside "/src/main" next to "res"!!

herer is the working class im using now :

package com.haghshenas.mafatih.Adapters;

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

import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class DatabaseManager extends SQLiteOpenHelper {

    private static String TAG = "DataBaseHelper";
    public SQLiteDatabase mDataBase;
    private final Context mContext;

    private static String DB_PATH = "";
    private static String DB_NAME ="mafatihdbv14.db";

    public DatabaseManager(@Nullable Context context) {
        super(context, DB_NAME, null, 1);
        this.mContext = context;
        DB_PATH = "/data/data/" + context.getPackageName() + "/";
        createDataBase();
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    private boolean checkDataBase()
    {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    public void createDataBase()
    {
        boolean mDataBaseExist = checkDataBase();
        if(!mDataBaseExist)
        {
            try
            {
                copyDataBase();
            }
            catch (IOException mIOException)
            {
                Log.i(TAG, "createDataBase "+mIOException+"");
            }
        }else{
            openDataBase();
        }
    }

    private void copyDataBase() throws IOException
    {
        try
        {
            InputStream mInput = mContext.getAssets().open("mafatihdbv14.db");
            String outFileName = DB_PATH + DB_NAME;
            OutputStream mOutput = new FileOutputStream(outFileName);
            byte[] mBuffer = new byte[1024];
            int mLength;
            while ((mLength = mInput.read(mBuffer))>0)
            {
                mOutput.write(mBuffer, 0, mLength);
            }
            mOutput.flush();
            mOutput.close();
            mInput.close();
            openDataBase();
        }
        catch (IOException mIOException)
        {
            Log.i(TAG,"copyDataBase "+ mIOException+"");
        }
    }

    public boolean openDataBase() throws SQLException
    {
        String mPath = DB_PATH + DB_NAME;
        mDataBase = SQLiteDatabase.openDatabase(mPath,null, SQLiteDatabase.OPEN_READWRITE);
        return mDataBase != null;
    }

    @Override
    public synchronized void close()
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }
}

Comments

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.