一加手机二的数据库未能正确复制

22

我正在创建一个安卓应用程序,并在其中使用sqlite数据库。为此,我已将sqlite文件放置在项目的assets文件夹中,并在第一次执行应用程序时使用下面的代码将该文件复制到手机中。

 private void copyDataBase() throws IOException {
    new File(DB_PATH).mkdirs();
    InputStream myInput = appContext.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);
    }

    myOutput.flush();
    myOutput.close();
    myInput.close();
}

但是我遇到了这些错误。

 09-21 18:03:56.841: E/SQLiteLog(7850): (1) no such table: tbl_player

但是这个表存在于资源文件中。因此,我使用这种方法从手机中提取数据库文件。

public static void exportDB(String databaseName, Context context) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//" + context.getPackageName()
                    + "//databases//" + databaseName + "";
            String backupDBPath = "sensor_game.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB)
                        .getChannel();
                FileChannel dst = new FileOutputStream(backupDB)
                        .getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }

    } catch (Exception e) {

    }
}

我发现在提取的数据库文件中没有表。

注意:这个问题只会出现在OnePlus Two手机上,在Nexus 4Htc 820Moto EGalxy S3Galaxy Quottro手机上都正常工作。


void exportDB改为布尔类型,并添加代码以处理当前数据库不存在的情况。该代码将无法正常工作。 - greenapps
我正在开发一个应用程序,但在我的OP2上遇到了一些问题,这让我感到非常疯狂。 - Frildoren
你找到这个问题的解决方案了吗? - varun bhardwaj
我仍然遭受着这个问题的困扰。 - Jignesh Ansodariya
现在我总共有4个用户,在SQLite中更改区域设置时失败。所有用户都在OnePlus Two上运行。对于其他99.9%的设备,它可以正常工作。最新的Oxygen更新没有任何影响。 - David
显示剩余10条评论
3个回答

6

不同设备中的数据库路径可能不同。 您需要使用 Context.getDatabasePath(String) 来获取数据库路径。

例如:

File backupDB = context.getDatabasePath(backupDBPath);

1
如果那是正确的话,那么sqlite-asset-helper中的这行代码也是错误的:https://github.com/jgilfelt/android-sqlite-asset-helper/blob/master/library/src/main/java/com/readystatesoftware/sqliteasset/SQLiteAssetHelper.java#L109 - 对吗? - swalkner
在我看来,这仍然比完全硬编码的版本要好。至少当应用程序移动到SD卡时,它会正确地表现出来。无论如何,我认为没有必要尝试假定路径,因为系统已经提供了它。 - Ugur Ozmen
抱歉,我不理解你的评论;我的意思是:如果你说使用getDatabasePath()是正确的,那么在sqlite-asset-helper中也应该是默认的,对吗? - swalkner
1
在我看来,最好使用Context.getDatabasePath()。但这并不意味着context.getApplicationInfo().dataDir + "/databases"是错误的。 - Ugur Ozmen
在我看来,数据库应该放在哪里取决于Android系统而不是设备,除非厂商改变Android代码并构建自己的系统。 - frogatto

3

经过长时间的尝试和搜索,我不得不假设OP2的制造中存在一个错误,因为它在所有其他设备上都正常工作。

我改变了我的方法,使用查询而不是从资产中复制数据库文件来创建数据库。像下面的代码:

import java.io.File;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper implements DBConstants {

private static MySQLiteHelper mInstance = null;
private SQLiteDatabase myDataBase;
private static String DB_PATH = "";

public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    try {
        if (checkDataBase())
            openDataBase();
        else
            myDataBase = this.getReadableDatabase();
    } catch (Exception e) {
    }
}

public static MySQLiteHelper instance(Context context) {

    File outFile = context.getDatabasePath(DATABASE_NAME);
    DB_PATH = outFile.getPath();

    if (mInstance == null) {
        mInstance = new MySQLiteHelper(context);
    }

    return mInstance;
}

private void openDataBase() throws Exception {
    try {
        myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,
                SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLException e) {
        // TODO: handle exception
    }
}

private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        checkDB = SQLiteDatabase.openDatabase(DB_PATH, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {
        /** database does't exist yet. */
    } catch (Exception e) {
    }
    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

@Override
public void onCreate(SQLiteDatabase db) {

    Log.v("log_tag", "onCreate");
    myDataBase = db;

    // creating a sample table
    String CREATE_DEVICE_TABLE = "CREATE TABLE " + DEVICE + " ("
            + KEY_DEVICEID + " TEXT, " + KEY_OPERATOR + " TEXT, "
            + KEY_DEVICENAME + " TEXT, " + KEY_DEVICETOTALMEMORY
            + " INTEGER, " + KEY_SCREENWIDTH + " INTEGER, "
            + KEY_SCREENHEIGHT + " INTEGER, " + KEY_OPERATINGSYSTEM
            + " TEXT)";

    db.execSQL(CREATE_DEVICE_TABLE);

    // other tables also can be created from here.
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DEVICE);

    // Create tables again (as per requirement)
    this.onCreate(db);
}

public Cursor rawQuery(String qry) {
    return myDataBase.rawQuery(qry, null);
}

public long insert(String tableName, ContentValues cv) {
    return myDataBase.insert(tableName, null, cv);
}

public void insertWithOnConflict(String tableName, ContentValues cv,
        int flag) {
    myDataBase.insertWithOnConflict(tableName, null, cv, flag);

}

public long update(String tableName, ContentValues cv, String whereClose) {
    return myDataBase.update(tableName, cv, whereClose, null);

}

public int deleteData(String table_name, String whereClause) {
    return (int) myDataBase.delete(table_name, whereClause, null);
}

}

并且它对我有效。

谢谢!


3
我找到了解决方案,我使用了下面这个函数:
public void createDb() {
        boolean dbExist = checkDataBase();

        if (dbExist) {
            // do nothing - database already exist
        } else {
            // call close() for properly copy database file
            this.getReadableDatabase().close();
            try {
                copyDataBase();
            } catch (IOException e) {
                e.printStackTrace();
                throw new Error("Error copying database");
            }
        }
    }

根据这篇文章的说法,我们需要调用close()方法,并且您也可以将数据库推送到Oneplus two设备。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接