3

So I know similar questions have been asked but I cannot find something that is for my exact case.

I have an application that creates a database and populates it etc but I have no root access on my device, so here is my problem. I need to populate this database with some values and then import this into my application/device.

If I had root access I could simply go and replace the database in the /data/data/com.my.application/databases folder, but since I do not have root access I need to be able to import this database that I changed into this location and replace the standard one.

Can anyone help me along with some code or an example of how to import a database into this folder? I just need to be able to import and replace the existing one.

Thanks, Wihan

1

2 Answers 2

5

You can use this library to use an imported database on your device:

https://github.com/jgilfelt/android-sqlite-asset-helper

As stated on the documentation you just need to put your database file on the assets folder under a directory called databases /assets/databases/database.db

Then make a DBHelper class that extends from SQLiteAssetHelper like this:

public class DBHelper extends SQLiteAssetHelper {

    private static final String DATABASE_NAME = "example.db";
    private static final int DATABASE_VERSION = 1;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

}

And you can access now to your data with content providers and all the stuff.

Also you can use http://sqlitebrowser.org/ for creating your pre loaded database on your computer.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0
public String loadJSONFromAsset(Context context) {
    String json = null;
    try {
        InputStream is = context.getAssets().open("Hospital.db");
        int size = is.available();
        OutputStream myoutput = new FileOutputStream("/data/data/-----PACKAGE NAME------/databases/Hospital.db");

        byte[] buffer = new byte[size];
        int length;
        while ((length = is.read(buffer)) > 0) {
            myoutput.write(buffer, 0, length);
        }

        // Close the streams
        myoutput.flush();
        myoutput.close();
        is.close();
        // byte[] buffer = new byte[size];
        // is.read(buffer);
        // is.close();
        // json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

2 Comments

are the commented lines needed?
Replace it with your package name! @user7294900

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.