I'm opening an SQLite database in Android using openOrCreateDatabase. The method works fine on Nexus 10 with KitKat (and several other tablets) but fails on Nexus 9 with Lollipop with an error "failed to change locale for db xyz to en_US". This only happens if I try to open database in a public directory like Downloads. If I open using private context.getDatabasePath location, it works on Nexus 9. On all the other tablets both locations work. The reason I try to open in a public location is to be able to examine database with DDMS file explorer. Is there a way to create a database in the public location on Nexus 9? Thanks.
Use this class. This will open your Database from any location you want.
import java.util.concurrent.atomic.AtomicInteger;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
public class DataBaseHandler {
private SQLiteDatabase mDatabase;
private static DataBaseHandler sDataBaseHandler;
public static String datapath = Environment.getExternalStorageDirectory().getPath() + "Your DataBase path";
private AtomicInteger mOpenCounter = new AtomicInteger();
public static synchronized DataBaseHandler getInstance() {
if (sDataBaseHandler == null) {
sDataBaseHandler = new DataBaseHandler();
}
return sDataBaseHandler;
}
public synchronized SQLiteDatabase openDatabase() {
if (mOpenCounter.incrementAndGet() == 1) {
// Opening new database
if (mDatabase == null) {
mDatabase = SQLiteDatabase.openDatabase(datapath, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} else if (!mDatabase.isOpen()) {
mDatabase = SQLiteDatabase.openDatabase(datapath, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
}
return mDatabase;
}
public synchronized void closeDatabase() {
if (mOpenCounter.decrementAndGet() == 0) {
if (mDatabase != null) {
mDatabase.close();
}
}
}
}
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.