0

I have DB in assets folder i want to copy it in database folder during the installation, Is there any way to do that?

OR if there aren't way to do that is there a way to make progress bar while the app coping the database after the app launched ?

Edit:

I have problem with database logcat "shows cannot open file at line 30176" i tried this

    if(android.os.Build.VERSION.SDK_INT >= 4.2){
        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";         
    } else {
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }

but it's not working :(

Samad
  • 1,776
  • 2
  • 20
  • 35
  • it's not my code work fine but i want to coping the database before the app launched not after – Samad Feb 19 '14 at 11:35
  • You can't run any code of your application before it is launched. Your best option would be trying to copy it from the static constructor of an `Application` class (you might not have access to a `Context` here) or the beginning of your `Application`'s `onCreate` method. – lucian.pantelimon Feb 19 '14 at 11:45

2 Answers2

1

This is my DataBaseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper {

private static String DB_PATH="data/data/yourPackageName/databases/";
private static final String DB_NAME="yourDbName.db";
private SQLiteDatabase myDatabase;
private final Context myContext;

public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, 1);
    // TODO Auto-generated constructor stub
    this.myContext = context; 
}

public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    SQLiteDatabase db_read = null;

    if(dbExist){
        //Do nothing

    }else{

        db_read = this.getReadableDatabase();
        db_read.close();

        try {
            copyDataBase();
        } catch (Exception e) {
            // TODO: handle exception
            throw new Error("Error copying database (createDataBase)");
        }
    }

}

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

}

public void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);
    // Path to the just created empty db. Destination folder (where we created the DB empty)
    String outFileName = DB_PATH+DB_NAME;
    //Open the empty db as the output stream. //We opened it BBDD empty as OutputStream
    OutputStream myOutPut = new FileOutputStream(outFileName);

    Log.e("LocAndroid", "ESTOY EN copyDataBase");


    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int lenght;


    while((lenght = myInput.read(buffer))!=-1){
        if(lenght > 0){

            myOutPut.write(buffer, 0, lenght);


        }

    }
    //Close the streams
    myOutPut.flush();
    myOutPut.close();
    myInput.close();

}

public void openDataBase() throws SQLException{


    //Open the database
    String myPath = DB_PATH+DB_NAME;
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}


public synchronized void close(){

    if(myDatabase != null){
        myDatabase.close();
    }
    super.close();
}

LoadDbASync.java

public class LoadDbAsync extends AsyncTask <Void, Void, Boolean>{

    Context context;
    boolean loadedDb = false;
    //private Activity mActivity;

    //constructor
     public LoadDbAsync(Context context) {
            //mActivity = activity;
         this.context = context;
        }

    private DataBaseHelper myDbHelper;
    private ProgressDialog pDialog; 

    //Se ejecutará antes del código principal de nuestra tarea. 
    //Se suele utilizar para preparar la ejecución de la tarea, inicializar la interfaz, etc
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        Log.i("LocAndroid", "Entra en PreExecute");

        pDialog = new ProgressDialog(context);
        pDialog.setMessage("Cargando Base de datos...");
        pDialog.setCancelable(false);//erabiltzaileak atzera botoia sakatuz ez kantzelatzeko
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//barrarewn estiloa. Espiral bat izango da

    }

    //Se ejecutará cada vez que llamemos al método publishProgress() desde el método doInBackground().
    //se usa para poder realizar cambios en la interface. En doInBackground no se pueden realizar cambios en la interface
    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);

        Log.i("LocAndroid", "Entra en onProgressUpdate");

        pDialog.show();
    }


    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO Auto-generated method stub
        Log.i("LocAndroid", "Entra en doInBackground");

        myDbHelper = new DataBaseHelper(context);
        boolean dbExist = myDbHelper.checkDataBase();

        if(dbExist){
            loadedDb = true;


        }else{

            publishProgress(null);
        }



        try {
            myDbHelper.createDataBase();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            throw new Error ("No se puede crear. Boton Crear. try. doInBAckground");
        }
        myDbHelper.close();


        return null;
    }


    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.i("LocAndroid", "Entra en onPostExecute");

        if(!loadedDb){
        pDialog.dismiss();
        Log.i("LocAndroid", "Se termino de cargar la BD");
        Toast.makeText(context, "Base de datos cargada", Toast.LENGTH_SHORT).show();
        }else{
            Log.i("LocAndroid", "La BD ya estaba cargada");

        }
            try {
                    finalize();
                } catch (Throwable e) {
                    // TODO Auto-generated catch block
                            e.printStackTrace();
                }
    }

}

And then, in MainActivity.java in onCreate:

LoadDbAsync task = new LoadDbAsync(this);
task.execute();
aldakur
  • 419
  • 4
  • 16
0

it's not my code work fine but i want to coping the database before the app launched not after

That's not possible. None of your code runs before the app is launched for the first time.

OR if there aren't way to do that is there a way to make progress bar while the app coping the database after the app launched ?

Have a look at ProgressDialog and AsyncTask:

  • Set up a ProgressDialog in AsyncTask onPreExecute()
  • Copy the database in doInBackground(), possibly updating progress with publishProgress() and onProgressUpdate()
  • Dismiss the ProgressDialog in onPostExecute()
laalto
  • 150,114
  • 66
  • 286
  • 303