Pinakin Kansara
Pinakin Kansara

Reputation: 76

How to access sqlite database in the asset folder of an android project?

I need help to use use my existing sqlite database in android.

i am placing my sqlite database in "/assets/(mydatabase)" but unable to use it.

i am using following code. some times it show error "unable to open database" and some times shows error like "can not find table". when i pull out database file from ddms and open it using sqlite browser it dropes my table means my table do not exist any more.

so please help me to get the way how i can use my existing sqlite databse in android just for read and rite operations.

private SQLiteDatabase MyDataBase;
private String path="/data/data/mypackagename/mydatabase";
try{
      MyDataBase=SQLiteDatabase.openDatabase(path, null,SQLiteDatabase.OPEN_READWRITE);
      Cursor myDbCursor;
      myDbCursor=MyDataBase.rawQuery("select user,password from login_master", null);
      String username=myDbCursor.getString(0);
      String password=myDbCursor.getString(01);
      Toast.makeText(getBaseContext(), username, 10).show();
      Toast.makeText(getBaseContext(), password, 10).show();
      MyDataBase.close();
  }
  catch(SQLiteException e){
      Toast.makeText(getBaseContext(), e.getMessage(), 10).show();
  }

Upvotes: 1

Views: 2687

Answers (2)

Maxim
Maxim

Reputation: 4234

Duplication: SQLite Android . unable to open database file

Upvotes: 0

Hardik Nadiyapara
Hardik Nadiyapara

Reputation: 2446

not sure but this can help you

void checkDB() throws Exception {
    try {
        SQLiteDatabase dbe = SQLiteDatabase
                .openDatabase(
                        "/data/data/yourpackagename/databases/yourfilename.sqlite",
                        null, 0);
        Log.d("opendb", "EXIST");
        dbe.close();
    } catch (Exception e) {

        AssetManager am = getApplicationContext().getAssets();
        OutputStream os = new FileOutputStream(
                "/data/data/yourpackagename/databases/yourfilename.sqlite");
        byte[] b = new byte[100];

        int r;
        InputStream is = am.open("yourfilename.sqlite");
        while ((r = is.read(b)) != -1) {
            os.write(b, 0, r);
        }
        Log.i("DATABASE_HELPER", "Copying the database ");
        is.close();
        os.close();
    }

}

Upvotes: 1

Related Questions