Skip to content
Advertisement

How to access database on Android app without root

I’m developing a small app with a database of 100 elements. I import the database but only in one emulator (of 3 witch I have) runs correctly. I found that it runs without problems because the “Songs.db” database exists in data/data/myapppackage/databases/ folder witch I can’t have access without rooting the device.

I search through internet for different approaches and solutions to this problem but nothing is working. I am new to android programming and for this kind of problem there isn’t any tutorial.

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "Songs.db";
    public static final String TABLE_NAME = "songs_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "TITLE";

    public DatabaseHelper (Context context) {
        super( context, DATABASE_NAME, null, 1 );
        SQLiteDatabase db = this.getWritableDatabase();
    }

    public Cursor getData(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select TITLE from songs_table where ID="+id+"", null );
        return res;
    }
}

and on PlayerTurn class

myDb = new DatabaseHelper( this );
Cursor rs = db.getData( b );
rs.moveToFirst();
tit = rs.getString( rs.getColumnIndex( db.COL_2 ) );

The error message I get most of the times is android.database.sqlite.SQLiteException: no such table: songs_table (code 1): Can anyone help me? I spend almost 15 hours about that…

Advertisement

Answer

You can copy the DB into SD card, From SD card you can always access the DB

Try this code:

 try {
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    if (sd.canWrite()) {
        String currentDBPath = "data/"+sPackageName+"/databases/"+sDBName;
        String backupDBPath = "/.appname-external-data-cache/"+sDBName; //"{database name}";
        File dir = new File(sd,backupDBPath.replace(sDBName,""));
        if(dir.mkdir()) {

        }
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);
        if (currentDB.exists()) {
            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
        }
    } 

   } catch (Exception e) {
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement