dimanche 31 mai 2015

Save sqlite db in external memory

I want to save sqlite db file in external memory.

I written code to save in internal memory like below.But I want to extract that "xxx.db" in run time and check whether my DB fields are saved or not.

manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

and DBHelper.java

private static String DB_PATH           =   "data/data/com.example.myApp/databases/";
private static final String DATABASE_TABLE  =   "myDB";
private static final int DATABASE_VERSION   =    1;
private static final String DATABASE_NAME   =   "mydb.db";

public void createDatabase() throws IOException{

        boolean doesDbExist = checkDatabase();

        if(doesDbExist){
            Toast.makeText(ourContext, "DB Already Created", Toast.LENGTH_SHORT).show();
        }else{
            this.getReadableDatabase();
            try{
                copyDatabase();
            }catch(Exception e){
                Log.d("DBError", "Copy DB error");
            }
            Toast.makeText(ourContext, "New DB created.", Toast.LENGTH_SHORT).show();
        }
    }

    private void copyDatabase() throws IOException{
            //Open your local db as the input stream
            InputStream myInput     =   ourContext.getAssets().open(DATABASE_NAME);

            // Path to the just created empty db
            String outFileName      =   DB_PATH + DATABASE_NAME;

            //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 len;

            while ((len = myInput.read(buffer))>0) {

                myOutput.write(buffer, 0, len);

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

        }

Please help me and suggest me for required changes.

Aucun commentaire:

Enregistrer un commentaire