1

I found a lot of question about this problem, but I can't fix it. I have a sqlite db in assets folder:

assets/data/data/{package_name}/databases/dbtest.sqlite

I tried to:

  1. Uninstall the project
  2. Clean the project
  3. Refresh and also restarted the ecilipse
  4. i checked my package name
  5. i checked my db file name

But i cant able to solve it. I dont know where i am wrong.

Thanks in Advance

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.exasmple.dbexam/databases/";
    private static String DB_NAME = "dbtest.sqlite";
    public static final String APP_TABLE = "land";

    private static final int DATABASE_VER5ION = 1;
    private static final String TYPE = "type";
    private static final String ID = "id";

    private SQLiteDatabase myDataBase;
    private final Context myContext;
    public static String state;

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

    public void createDataBase() throws IOException {
        // System.out.println("Creating database");
        boolean dbExist = checkDataBase();
        if (!dbExist) {
            this.getReadableDatabase();

            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    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();
        System.out.println("Database copied into system data");

    }

    public void openDataBase() throws SQLException {

        System.out.println("Open database");
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);// SQLiteDatabase.NO_LOCALIZED_COLLATORS);

    }

    @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) {

        db.execSQL("DROP TABLE IF EXISTS report");
        db.execSQL("DROP TABLE IF EXISTS appstatus");
        onCreate(db);
    }

    public ArrayList<String> GetGroupName() {
        String sql = "";
        // System.out.println("Inside Database");
        sql = "select chapterid from content";

        ArrayList<String> list = new ArrayList<String>();

        Cursor cursor = myDataBase.rawQuery(sql, null);

        try {
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        list.add(cursor.getString(0));
                        System.out.println("dblist value==" + list);
                    } while (cursor.moveToNext());
                }
                if (cursor != null && !cursor.isClosed()) {
                    cursor.close();
                }
            } else
                Toast.makeText(myContext, "No values in DB", Toast.LENGTH_SHORT)
                        .show();
        } catch (Exception e) {
            System.out.println("GetGradeNames(): " + e);
        }
        return list;
    }

}

Logcat :

07-09 14:57:27.834: E/AndroidRuntime(987): FATAL EXCEPTION: main
07-09 14:57:27.834: E/AndroidRuntime(987): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exasmple.dbexam/com.exasmple.dbexam.MainActivity}: android.database.sqlite.SQLiteException: unable to open database file
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.os.Looper.loop(Looper.java:130)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.ActivityThread.main(ActivityThread.java:3683)
07-09 14:57:27.834: E/AndroidRuntime(987):  at java.lang.reflect.Method.invokeNative(Native Method)
07-09 14:57:27.834: E/AndroidRuntime(987):  at java.lang.reflect.Method.invoke(Method.java:507)
07-09 14:57:27.834: E/AndroidRuntime(987):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-09 14:57:27.834: E/AndroidRuntime(987):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-09 14:57:27.834: E/AndroidRuntime(987):  at dalvik.system.NativeStart.main(Native Method)
07-09 14:57:27.834: E/AndroidRuntime(987): Caused by: android.database.sqlite.SQLiteException: unable to open database file
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1849)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:820)
07-09 14:57:27.834: E/AndroidRuntime(987):  at com.exasmple.dbexam.DBHelper.openDataBase(DBHelper.java:138)
07-09 14:57:27.834: E/AndroidRuntime(987):  at com.exasmple.dbexam.MainActivity.onCreate(MainActivity.java:21)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-09 14:57:27.834: E/AndroidRuntime(987):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-09 14:57:27.834: E/AndroidRuntime(987):  ... 11 more
prabhakaran
  • 668
  • 2
  • 10
  • 33

6 Answers6

1

Finally i found the answer from chat room. This may help someone..

MY updated DBHelper

public class DBHelper extends SQLiteOpenHelper {
    public int GetCursor;
    // ****************** Declare all the global variable
    // ****************************//
    private Context myContext;
    public String DB_PATH = "data/data/com.exasmple.dbexam/databases/"; // path
    // of
    // your
    // datbase
    public static String DB_NAME = "Test.sqlite";// your database name
    static String ASSETS_DB_FOLDER = "db";
    private SQLiteDatabase db;

    public DBHelper(Context context) {
        super(context, DB_NAME, null, 2);
        if (db != null && db.isOpen())
            close();

        this.myContext = context;
        //DB_NAME = db_name;

        try {
            createDataBase();
            openDataBase();
        } catch (IOException e) {
            // System.out.println("Exception in creation of database : "+
            // e.getMessage());
            e.printStackTrace();
        }

    }

    

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();

        if (dbExist) {
            // System.out.println("Database Exist");
        } else {
            this.getReadableDatabase();

            try {
                copyDatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private void copyDatabase() throws IOException {
        InputStream input = myContext.getAssets().open(DB_NAME);
        String outputFileName = DB_PATH + DB_NAME;
        OutputStream output = new FileOutputStream(outputFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Close the streams
        output.flush();
        output.close();
        input.close();
        // System.out.println(DB_NAME + "Database Copied !");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public boolean isOpen() {
        if (db != null)
            return db.isOpen();
        return false;
    }

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

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            // System.out.println("My Pathe is:- " + myPath);
            // System.out.println("Open");
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
            // System.out.println("checkDB value:" + checkDB);
            // System.out.println("My Pathe is:- " + myPath);
        } catch (Exception e) {
            // database does't exist yet.
        }

        if (checkDB != null) {
            // System.out.println("Closed");
            checkDB.close();
            // System.out.println("My db is:- " + checkDB.isOpen());
        }

        return checkDB != null ? true : false;
    }

    public Cursor execCursorQuery(String sql) {
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, null);
            GetCursor = cursor.getCount();
            Log.i("Inside execCursorQuery try", sql);
        } catch (Exception e) {
            Log.i("Inside execCursorQuery exception", e.getMessage());
        }
        return cursor;
    }

    public void execNonQuery(String sql) {
        try {
            db.execSQL(sql);
            // Log.d("SQL", sql);
        } catch (Exception e) {
            // Log.e("Err", e.getMessage());
        } finally {
            // closeDb();
        }
    }

    public ArrayList<String> GetchapterID(){
        String sql="";
            //System.out.println("Inside Database");
            sql="select distinct(ChapterId) from contents";
        
        ArrayList<String> list = new ArrayList<String>();
        Cursor cursor=db.rawQuery(sql, null);
        
        try{
        if(cursor != null){
        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(0));
            }
            while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        }
     else
            Toast.makeText(myContext, "No values in DB", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e){
            System.out.println("GetGradeNames(): " +e);
        }
        return list;
    }
}
Community
  • 1
  • 1
prabhakaran
  • 668
  • 2
  • 10
  • 33
0
  1. Try to uninstall the app and re-install the app
  2. Check if the SQLite version with which the DB was created is the same as the current version
  3. Check if you are trying to access the DB from several threads in your code. It may be possibly blocked by one of the threads.
    • You have to close the connection with the database of process A first before you start using database with process B.
    • This will solve your concurrency.
    • Use db.close(); to close such connections
ngrashia
  • 9,869
  • 5
  • 43
  • 58
0

DB_NAME should be -

DB_NAME="dbtest";

For DB_PATH, you used the package com.exasmple.dbexam,

DB_PATH = "/data/data/com.exasmple.dbexam/databases/";

is probably wrong.

NOTE: Put correct package name(you can check it from your manifest file).

UPDATE:

Do like -

 public void createDataBase() throws IOException {
            // System.out.println("Creating database");
            boolean dbExist = checkDataBase();
            if (dbExist == true) {
                this.getReadableDatabase();

            try {
                  this.openDataBase();
            } catch (SQLException e) {

              e.printStackTrace();
            }

                try {
                    copyDataBase();
                } catch (IOException e) {
                    throw new Error("Error copying database");
                }
            }
        }

For more on handling Sqlite database on Android.

sjain
  • 23,126
  • 28
  • 107
  • 185
  • Package name is correct, since even in exception, the package name is specified as 'com.exasmple.dbexam.'. Also, does the DB name has any issue? – ngrashia Jul 09 '14 at 10:55
  • DB name should be without extension. Just use `DB_NAME="dbtest";` and not `DB_NAME="dbtest.sqlite";`. – sjain Jul 09 '14 at 10:56
  • @NishanthiGrashia i have sample package so i just named as `com.exasmple.dbexam`i recheck my manifest also – prabhakaran Jul 09 '14 at 10:58
  • Don't go over the exception to check the package name. Check the android manifest file to confirm the package. Your package name may be mis-spelled. For example - the right one may be `com.examples.dbexam` and not `com.exasmple.dbexam`. – sjain Jul 09 '14 at 10:58
  • no no i rechecked its `` i only named like tht – prabhakaran Jul 09 '14 at 11:00
  • Check the update. You haven't used boolean check properly to read the database. – sjain Jul 09 '14 at 11:08
  • @VedPrakash oh wait i will check – prabhakaran Jul 09 '14 at 11:09
  • Check my update. You forgot to open the database using `openDataBase()`. – sjain Jul 09 '14 at 11:30
  • `sqlite3_open_v2("/data/data/com.exasmple.dbexam/databases/dbtest", &handle, 2, NULL) failed` i am getting this error now – prabhakaran Jul 09 '14 at 11:39
  • Now you are very close to the problem - Check http://www.itsalif.info/content/check-if-database-exist-android-sqlite3openv2-failed. Also check the link mentioned in that blog for handling sqlite database on Android. I assume that your DB_Name is without extension as is mentioned in the blog link. – sjain Jul 09 '14 at 11:43
0

NO way

Open a database file located in the assets folder. Always the main point of the - correct - answer is: databases located in assets cannot be opened since such folder (as the entire content of the APK) is read only.

However, what if the database file in fact does not have to be modified ?. In that case it does not matter the restriction that the assets folder is read only.

so copied your db file into some other location like sdcard,data\data folder then it will be readable

  • refer this link http://stackoverflow.com/questions/8914673/opening-a-read-only-database-directly-in-the-assets-folder – Rajaji subramanian Jul 09 '14 at 11:06
  • you cant able to read the db file from the asset folder and modified ,because the asset folder reside inside of the apk file once its build so, the android system not allow the user to access the file in asset folder – Rajaji subramanian Jul 09 '14 at 11:09
  • thats why i'm saying you copied the db file from the data/data folder to asset why you do that like that you directly access the db file from the data\data folder itself it will work – Rajaji subramanian Jul 09 '14 at 11:13
  • where i do like tht.. i just copying from assets only – prabhakaran Jul 09 '14 at 11:18
0

Try this, it will help you:-

http://blog.softeq.com/2012/12/using-pre-populated-sqlite-database-in.html

Just take database file from assets folder and insert your data using sqlite browser and again paste that file inside that folder

Note:- And don't forget to change the column name according to you..

Laxmeena
  • 780
  • 2
  • 7
  • 28
0

Try changing this:

   private static String DB_NAME = "dbtest.sqlite";

for this

   private static String DB_NAME = "dbtest.db";
Miguel87
  • 3
  • 1