I have followed several tutorials on importing an external SQLite DB on an Android App and it looks I do everything "good" but I always get the same error:
Caused by: android.database.sqlite.SQLiteException: no such table: games (code 1): , while compiling: SELECT * FROM games
I created the DB on "DB Browser for SQLite: Here
I saved the DB as "testDB.db" and I put it on "assets" folder of Android Studio Project.
Here the code:
public class DatabaseHelper extends SQLiteOpenHelper{
private static String DB_NAME = "testDB.db";
SQLiteDatabase mDb;
private final Context myContext;
//The Android's default system path
private static String DB_PATH = "/data/data/com.example.jack.testimport/databases/";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
mDb = this.getReadableDatabase();
if (mDb.isOpen()){
mDb.close();
}
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public boolean checkDataBase(){
File dbFile = myContext.getDatabasePath(DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput = myContext.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);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
mDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(mDb != null)
mDb.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//Query all data:
public Cursor fetchGames(){
return mDb.query("games", null,null,null,null,null,null);
}
public static String getDbName(){
return DB_NAME;
}
}
And from my activity I call this method:
int counter=0;
DatabaseHelper myDbHelper = new DatabaseHelper(ImportDatabase.this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
counter=myDbHelper.fetchGames().getCount();
} catch (SQLException sqle) {
throw sqle;
}
Counter is always 0 and I get the error on top of this thread. I tried to clean/rebuild the project, delete all data and reinstalling the app, changing the path, I followed all the related question (so I hope you don't report it as duplicate), etc...I'm becoming crazy! What can I do to fix this error?
Thank you in advance.