简体   繁体   中英

Android work with db file from SD card

I wrote an app which logged data and saved it via SQL into a .db File. I had a method copying it from internal memory to SD card.

Now i wrote a second app, which needs to work with this particular .db file. As i think, that apps can't get access to package files from other apps

(in this case

 /data/data/app1_package/databases/my_database.db 

) i need somehow to work with my DB on the SD Card. How do i do that?

Can i use this path in my SQLiteHelper class? Should i copy it from SD to my package, is that even possible (access rights etc.)?

I'm a beginner in databases, some help would be nice.

You can open any readable file path as a database:

File dbFile = new File( Environment.getExternalStorageDirectory(), "myfile.db" );
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbFile,null,null);

Note: check if sd-card is mounted before using this code.

yes place the DB file in your assets folder and get it this way :

     DB_PATH="/data/data/app1_package/databases/my_database.db" 

in your create :

            is = getAssets().open("Meaniningss.db");
            write(is);

the method :

               public void write(InputStream is) {
    try {
        OutputStream out = new FileOutputStream(new File(DB_PATH));
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = is.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        is.close();
        out.flush();
        out.close();
        System.err.println(out + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM