mardi 28 avril 2015

copy sqlite DB from assets to package path for "one time"

I use copy file method in my android app for coping a fill sqlite DB to my package path.so my question is how to do that for one time? because every time when my app running my DB copy again in package path and my data lost. i am trying SharedPreferences like below and also (file.exist()) in "if" statement.

public static Context               context;
public static SharedPreferences     pre;
public static SQLiteDatabase        database_s;
public static final String          DIR_SDCARD     = Environment.getExternalStorageDirectory().getAbsolutePath();
public static String                DIR_DATABASE_s = DIR_SDCARD + "/database-s";

        context = getApplicationContext();
        pre = PreferenceManager.getDefaultSharedPreferences(context);

        boolean first = pre.getBoolean("first-time", true);
        if ( !first) {
        SharedPreferences.Editor editor = pre.edit();
        editor.putBoolean("first-time", false);
        editor.commit();

        try {
            //Open your local db as the input stream
            InputStream myInput = context.getAssets().open("database_mystate.sqlite");

            // Path to the just created empty db
            String outFileName = DIR_DATABASE_s + "/database_mystate.sqlite";

            //Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            //Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
        catch (Exception e) {
            // Log.e("error", e.toString());
        }

         }

Aucun commentaire:

Enregistrer un commentaire