Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import SQLite database from sdcard to android - Without Assets Folder

I am trying to import my sqlite database from sdcard or any external location to my Android application. My application requires a database import such that database schema will not change but records change as per the database being imported.

(For example, I might import DatabaseA at a given time having 10 records and another time I might import DatabaseA having 25 records. DatabaseA is always imported from the same external location).

The import methods that I have seen so far using the assets folder does not help. I would like to import my database that points to an external location.

like image 422
Prabha Avatar asked Jul 01 '16 20:07

Prabha


2 Answers

I used the following code to import my database from sdcard.

Please note: A database folder needs to be created inside the application for the database to be imported successfully.

public void importDB() {

String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
File sd = new File(dir);
File data = Environment.getDataDirectory();
FileChannel source = null;
FileChannel destination = null;
String backupDBPath = "/data/com.example.mine.move/databases/A.db";
String currentDBPath = "A.db";
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
    source = new FileInputStream(currentDB).getChannel();
    destination = new FileOutputStream(backupDB).getChannel();
    destination.transferFrom(source, 0, source.size());
    source.close();
    destination.close();
    Toast.makeText(this, "Please wait", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    e.printStackTrace();
}

Also, add the following permission.

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

If your import is not successful, downgrade your sdk version or include runtime permissions.

like image 58
Prabha Avatar answered Nov 14 '22 23:11

Prabha


import database from external | internal directory :

public class DataBaseHelper extends SQLiteOpenHelper {

private static String DataBaseName = "dbname";
private static String DB_PATH =  "" ;
SQLiteDatabase database ;
Context  context ;

public DataBaseHelper(Context context) {
    super(context, DataBaseName, null, 1);
    this.context =context ;
    String x = context.getDatabasePath("1").getPath() ;
    x = (String) x.subSequence(0 ,x.length()- 1);
    DB_PATH = x + DataBaseName ;

    if (checkExist()){
        Log.e("DATA_BASE", " Exist");
    }else{
        try {
            createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

boolean checkExist(){
    boolean is = false ;
    try{
        File file = new File(DB_PATH);
        if (file.exists()){
            is= true ;
        }
    }catch (SQLiteException e){
        Log.e("DATABESE_ERR" ,  e.getMessage() ) ;
    }


    return is ;
}

private void createDataBase() throws IOException{
    if (checkExist()){

    }else {
        getReadableDatabase() ;
        try{
            copyDataBase();
        }catch (IOException e){
            Log.e("DATABASE-COPY-ERR", e.getMessage());
        }
    }
}

private void copyDataBase()throws IOException {
    Uri fileUri = "your database file uri" ; 
    File file = new File(fileUri.getPath());
    FileInputStream inputStream = new FileInputStream(file);

    OutputStream outputStream = new FileOutputStream(DB_PATH);

    byte[] buffer = new byte[1024] ;
    int length  =0 ;

    while( (length = inputStream.read(buffer) ) >0 ){
        outputStream.write(buffer ,0 ,length);
    }

    outputStream.flush();
    outputStream.close();
    inputStream.close();

}

public void openDataBase() throws SQLiteException{
    database = SQLiteDatabase.openDatabase(DB_PATH ,null ,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDataBase(){
    if (database!= null){
        database.close();
    }
    try {
        super.clone() ;
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
}

}

how to use this class :

public class DataBaseInterface {
public DataBaseInterface(Context activity) {
    context = activity;
}

private void openDataBase() {
    try {
        dataBaseHelper = new DataBaseHelper(context);
        dataBaseHelper.openDataBase();
    } catch (Exception e) {
        Log.e("DataBaseError", e.getMessage());
    }
}

private void closeDataBase() {
    dataBaseHelper.close();
}
}

and example method for querying database :

public ArrayList<String> getSomeThing() {
    buffer = new ArrayList<>();
    openDataBase();
    query = "SELECT * FROM table_name";

    cursor = dataBaseHelper.database.rawQuery(query, null);

    for (int i = 0; i < cursor.getCount(); i++) {
        cursor.moveToPosition(i);
        buffer.add(i, cursor.getString(0));
    }

    closeDataBase();
    cursor.close();

    return buffer;
}
like image 32
Kapta Avatar answered Nov 14 '22 22:11

Kapta