Showing posts with label external sqlite import. Show all posts

How to use External SQLite DB in Android

How to use External SQLite DB in Android

In this Post, I will explain how to import and use External SQLite DB in Android.
You can import and use SQLite database with the extensions like .db, .db3,sqlite and sqlite3.
The External DB is created with some desktop applications like SQLite Browser, SQLite Converter and so on.
After Generating the DB paste that into your App's assets folder.
Code:
DBHelper.class
Create a class named as DBHelper extending with SQLiteHelper. Paste the following code in that class.
public class DBHelper extends SQLiteOpenHelper {
    Context context;
    String DB_PATH;
    String divider = "/";
    String DB_NAME;

    public DBImporterExporter(Context context, String DB_NAME) {
        super(context, DB_NAME, null, 1);
        this.context = context;
        this.DB_NAME = DB_NAME;
        DB_PATH = divider + "data" + divider + "data" + divider + context.getPackageName() + divider + "databases/";
    }

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

    public void importDataBaseFromAssets() throws IOException {

        this.getReadableDatabase();

        InputStream myInput = context.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        Toast.makeText(context.getApplicationContext(), "Successfully Imported", Toast.LENGTH_SHORT).show();
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }
 
}
The DB is Imported by using the following code
DBImporterExporter dbImporterExporter = new DBImporterExporter(getApplicationContext(), "external_db_android.sqlite");
 try {
  dbImporterExporter.importDataBaseFromAssets();
    } catch (IOException e) {
  e.printStackTrace();
}
To Check the Existence of DB use the following snippet in your class
dbImporterExporter.isDataBaseExists()
Download Source Code



Having trouble while using this code or any doubt, comment me