2

I'm using below code to copy sqlite database from asset folder to /data/data/{package_name}/databases/and it works fine on most phones i tested it (HTC,Samsung,Sony,Huawei) but it does not work on some phones (like LG G2)

public void createDatabase() throws IOException {
    boolean dbExist = checkDatabase();
    try {
        if (dbExist)
            deleteDatabase();

        this.getReadableDatabase();
        copyDatabase();
    } catch (IOException e) {
        Log.v("db", e.toString());
        throw new Error(e.getMessage());
    }
}

also i tried below code instead of using this.getReadableDatabase();

private void createDirectory() {
    File dbDirectory = new File(DB_PATH);
    if (!dbDirectory.exists())
        dbDirectory.mkdirs();
}

but the same result, what is the problem ? and how can i solve it?

EDIT complete code :

public class SQLiteDBHelper extends SQLiteOpenHelper
{
private final Context myContext;

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

/**
 * Creates a empty database on the system and overwrite it with your own
 * database.
 **/
public void createDatabase() throws IOException {
    boolean dbExist = checkDatabase();
    if (dbExist) {
        try {
            deleteDatabase();
        } catch (IOException e) {
            Log.v("db", e.toString());
            throw new Error("Error copying database");
        }
    }
    // if (!dbExist) {
    try {
    super.getReadableDatabase();

        copyDatabase();
    } catch (IOException e) {
        Log.v("db", e.toString());
        throw new Error("Error copying database");
    }
    // }
}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 * 
 * @return true if it exists, false if it doesn't
 */
private boolean checkDatabase() {
    SQLiteDatabase checkDB = null;

    try {
        checkDB = SQLiteDatabase.openDatabase(G.DB_FULL_PATH, null,
                SQLiteDatabase.OPEN_READONLY
                        | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    } catch (SQLiteException e) {
        // database does't exist yet.
    }

    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

private void copyDatabase() throws IOException {
    String[] dbFiles = myContext.getAssets().list(G.ASSETS_DB_FOLDER);
    String outFileName = G.DB_FULL_PATH;
    Log.v("db", dbFiles[0]);
    Log.v("db", outFileName);
    InputStream in = myContext.getAssets().open(
            G.ASSETS_DB_FOLDER + "/" + dbFiles[0]);
    OutputStream out = new FileOutputStream(outFileName);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();

    /*
     * OutputStream myOutput = new FileOutputStream(outFileName); //for(int
     * i =0; i < dbFiles.length; i++) { InputStream myInput =
     * myContext.getAssets().open(G.ASSETS_DB_FOLDER+"/"+dbFiles[0]); byte[]
     * buffer = new byte[1024]; int length; while ((length =
     * myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); }
     * myInput.close(); //} myOutput.flush(); myOutput.close();
     */
}

public void deleteDatabase() throws IOException {
    if (checkDatabase())
        G.context.deleteDatabase(G.DB_FULL_PATH);
}

public void openDatabase() throws SQLException {
    // Open the database
    G.database = SQLiteDatabase.openDatabase(G.DB_FULL_PATH, null,
            SQLiteDatabase.OPEN_READONLY
                    | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}

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

@Override
public void onCreate(SQLiteDatabase db) {
}

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

@Override
public synchronized SQLiteDatabase getReadableDatabase() {
    try {
        createDatabase();
        openDatabase();
    } catch (SQLException e) {
        G.database = null;
        e.printStackTrace();
    } catch (IOException e) {
        G.database = null;
        e.printStackTrace();
    }
    return G.database;
}
}

and it gives me a IOException on this.getReadableDatabase() i think the problem is related to the sdcard

Mostafa Jamareh
  • 1,389
  • 4
  • 22
  • 54
  • 2
    Please [use `SQLiteAssetHelper`](https://github.com/jgilfelt/android-sqlite-asset-helper) rather than rolling your own solution to packaging a database as an asset. – CommonsWare Sep 30 '14 at 20:18
  • 1
    You have not shown how you determine the path and you have not shown complete code. And you have not told what does not work. So there is little to say. – greenapps Oct 01 '14 at 06:28
  • and it gives me a IOException on `this.getReadableDatabase()` i think the problem is related to the sdcard – Mostafa Jamareh Oct 01 '14 at 06:44
  • Why do you think so? – greenapps Oct 01 '14 at 07:26
  • because it works on all phones that support sdcard but it does not support lg g2 that does not support sdcard – Mostafa Jamareh Oct 01 '14 at 07:54
  • Do you **hardcode** `/data/data/{package_name}/databases/` or do you determine it **dynamically**? Can you show how do you get that path? – Phantômaxx Oct 01 '14 at 09:11
  • You should try so: `String DB_PATH = ctx.getDatabasePath(DB_NAME).getPath();` where ctx is a context and DB_Name is something like `"your.db"` – Phantômaxx Oct 01 '14 at 11:33
  • related [Android P - 'SQLite: No Such Table Error' after copying database from assets](https://stackoverflow.com/q/50476782/1820553) – kelalaka Oct 07 '19 at 09:05

1 Answers1

0

I think the problem is the path of your db file used to locate your db:

DB_PATH = Environment.getExternalStorageDirectory()+ context.getApplicationContext().getPackageName() +File.separatorChar+ "databases" + File.separatorChar + "/test.db";

and to get

/data/data/pkgname/databases/dbname

use the following

ContextWrapper c = new ContextWrapper(this);
String DBPath = c.getDatabasePath(DB_NAME).getPath();

I hope this is helpful.

Durai Amuthan.H
  • 31,670
  • 10
  • 160
  • 241
Alireza Rahimi
  • 489
  • 3
  • 6