android.database.sqlite.SQLiteException:Can';t将只读数据库从版本0升级到2
所以我不能升级我的数据库,因为某些原因。我不需要保存我的previos db,用户不会更改它,所以我只需要替换它。这里有一些代码,似乎不起作用。 在我的活动的onCreate()中,我这样做android.database.sqlite.SQLiteException:Can';t将只读数据库从版本0升级到2,android,sqlite,android-sqlite,Android,Sqlite,Android Sqlite,所以我不能升级我的数据库,因为某些原因。我不需要保存我的previos db,用户不会更改它,所以我只需要替换它。这里有一些代码,似乎不起作用。 在我的活动的onCreate()中,我这样做 private AchieveDbHelper mDBHelper; mDBHelper = new AchieveDbHelper(this); try { mDBHelper.updateDataBase(); } catch (IOException mIOExcep
private AchieveDbHelper mDBHelper;
mDBHelper = new AchieveDbHelper(this);
try {
mDBHelper.updateDataBase();
} catch (IOException mIOException) {
throw new Error("UnableToUpdateDatabase");
}
下面是实现的bHelper代码
public class AchieveDbHelper extends SQLiteOpenHelper {
private static String DB_NAME = "achievements.db";
private static String DB_PATH = "";
private static final int DB_VERSION = 2;
private SQLiteDatabase mDataBase;
private final Context mContext;
private boolean mNeedUpdate = false;
public AchieveDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
this.mContext = context;
copyDataBase();
this.getReadableDatabase();
}
public void updateDataBase() throws IOException {
if (mNeedUpdate) {
File dbFile = new File(DB_PATH + DB_NAME);
if (dbFile.exists())
dbFile.delete();
copyDataBase();
mNeedUpdate = false;
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() {
if (!checkDataBase()) {
this.getReadableDatabase();
this.close();
try {
copyDBFile();
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private void copyDBFile() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
mOutput.write(mBuffer, 0, mLength);
mOutput.flush();
mOutput.close();
mInput.close();
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
mNeedUpdate = true;
}
我在onUpgrade中尝试了不同的解决方案,但都不起作用。您看到了什么错误?运行时异常?java.lang.RuntimeException:无法启动activity ComponentInfo{com.bletter.algoprog/com.bletter.algoprog.activities.MainActivity}:android.database.sqlite.SQLiteException:无法将只读数据库从版本0升级到2:Acquisitions.db您正在以可读模式打开数据库。但是如果你想升级或删除它,你需要在可写模式下打开它。