mardi 29 mars 2016

how can i import external large sqlite to my new android project

i have db xxx.sqlite (8Mo) that i want use in my android project so i use this code but it didn't work Datahelper.java

public class Datahelper extends SQLiteOpenHelper {

private String dbName;
private String db_path;
private Context context;


public Datahelper(Context context, String dbName) {
    super(context, dbName, null, 1);
    this.dbName = dbName;
    this.context = context;
    db_path = "/data/data" + context.getPackageName() + "/databases/";

}

/**
 * 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
 */
public boolean checkExist() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = db_path + dbName;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {
        e.printStackTrace();
        // database does't exist yet.

    } catch (Exception ep) {
        ep.printStackTrace();
    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public int importIfNotExist() throws IOException {
      int a=0;
    boolean dbExist = checkExist();

    if (dbExist) {
        a=0;
        // do nothing - database already exist
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDatabase();
          a=2;
        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }
    return a;

}

private void copyDatabase() throws IOException {
    InputStream is = context.getAssets().open(dbName);

    OutputStream os = new FileOutputStream(db_path + dbName);

    byte[] buffer = new byte[4096];
    int length;
    while ((length = is.read(buffer)) > 0) {
        os.write(buffer, 0, length);
    }
    os.flush();
    os.close();
    is.close();
    this.close();
}

@Override
public void onCreate(SQLiteDatabase db) {


}

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


} }

and in my activity.java i put

Datahelper dbHelper = new Datahelper(
            getBaseContext(), "xxx.sqlite");
    try {
        dbHelper.importIfNotExist();
    } catch (IOException e) {
        e.printStackTrace();
    }

some friends tell that my db is very large 8Mo and i try to put it in res/raw and it doesn't work and i put it in assets folder and it doesn't work . please if someone can help .

Aucun commentaire:

Enregistrer un commentaire