I know this question is very common and many people have already asked it. but even after doing alot of search i could not make it work. The idea is same, I have created a sqlite database with sqlite browser and added into my project assets directory in android studio.
Here is my class that I wrote and I check DB_PATH and DB_NAME etc, and all possible things but it is not working and throwing this error
open failed: ENOENT (No such file or directory)
code
public class DataBaseHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
public DataBaseHelper(Context context){
super(context, DB_NAME, null, 1);
this.ctx = context;
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
accessDatabase();
}
private void accessDatabase(){
if(checkDatabase()) {
Log.d(TAG, "CHECK DB existence" + checkDatabase());
} else {
copyDataBase();
Log.d(TAG, "DATABase Copied");
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String dbPath = DB_PATH+DB_NAME;
File file = new File(dbPath);
if (file.exists() && !file.isDirectory())
checkDB = SQLiteDatabase.openDatabase(dbPath, null,SQLiteDatabase.OPEN_READWRITE);
}catch (SQLiteException exception){
exception.printStackTrace();
}
return checkDB != null ? true : false;
}
private void copyDataBase() {
try {
InputStream myInput = ctx.getAssets().open(DB_NAME);
Log.d(TAG, "DB_PATH- "+DB_PATH+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);
}
myOutput.flush();
myOutput.close();
myInput.close();
}catch (IOException exception){
exception.printStackTrace();
}
}
private static String DB_PATH = null;
private static String DB_NAME = "database.db";
private Context ctx;
private static String TAG = "DataBaseHandler";
}
PATH(s) and NAME(s) are correct and I am running it on Android Lollipop
Aucun commentaire:
Enregistrer un commentaire