gpt4 book ai didi

Android 无法将数据库复制到 Assets 文件夹

转载 作者:行者123 更新时间:2023-11-29 01:19:01 25 4
gpt4 key购买 nike

我有一个手动创建的数据库 (.sqlite3)。我已尝试根据此 question/answer 将其合并到我的应用程序中

我不确定为什么,但它一直向我抛出“ErrorCopyingdatabase”错误。我正在使用模拟器进行测试。

这是将我的数据库合并到应用程序中的代码。我做了 2 节课。

public class DataBaseHelper extends SQLiteOpenHelper {
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private static String DB_PATH = "";
private static String DB_NAME ="Characters";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;

public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1); // 1? Its database 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;
}

public void createDataBase() throws IOException {
//If the database does not exist, copy it from the assets.

boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist) {
this.getReadableDatabase();
this.close();
try {
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}

//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}

//Copy the database from assets
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}

//Open the database, so we can query it
public boolean openDataBase() throws SQLException {
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}

@Override
public synchronized void close() {
if(mDataBase != null)
mDataBase.close();
super.close();
}
}

和...

public class TestAdapter {
protected static final String TAG = "DataAdapter";

private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;

public TestAdapter(Context context){
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}

public TestAdapter createDatabase() throws SQLException{
try {
mDbHelper.createDataBase();
}
catch (IOException mIOException)
{
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}

public TestAdapter open() throws SQLException{
try{
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
}
catch (SQLException mSQLException){
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}

public void close(){
mDbHelper.close();
}

public ArrayList getTestData(int numberId){
try {
ArrayList<String> details = new ArrayList<>();
String name = "";
String summary = "";
String trivia = "";
String abilities = "";
Cursor mcur = mDb.rawQuery("SELECT Name FROM CharactersInfo WHERE _id=?", new String[]{numberId + ""});

if (mcur.getCount() > 0) {

mcur.moveToFirst();
name = mcur.getString(mcur.getColumnIndex("Name"));
summary = mcur.getString(mcur.getColumnIndex("Summary"));
trivia = mcur.getString(mcur.getColumnIndex("Trivia"));
abilities = mcur.getString(mcur.getColumnIndex("Abilities"));


details.add(name);
details.add(summary);
details.add(trivia);
details.add(abilities);

}
return details;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
}

我尝试稍微修改一下代码以满足我的需要...正如我所说,它似乎无法复制数据库,并不断向我发送 ErrorCopyingDatabase 错误(第一个代码 fragment )。

因此,在随后的尝试中,首先没有数据库来执行我的查询。

顺便说一句,我通过 fragment 上的按钮激活所有内容。

TestAdapter mDbHelper = new TestAdapter(getActivity());
mDbHelper.createDatabase();
mDbHelper.open();
ArrayList cursor = mDbHelper.getTestData(indentifier);
TextView textView = (TextView) view.findViewById(R.id.character_trivia);
String string = "" + cursor;
textView.setText(string);

mDbHelper.close();

我已经调查了一下,非常感谢您的帮助。

编辑:这是 logcat(只有致命异常部分),很抱歉迟到:

FATAL EXCEPTION: main
Process: com.lumberjackapps.dailyhero, PID: 2395
java.lang.Error: ErrorCopyingDataBase
at com.lumberjackapps.dailyhero.DataBaseHelper.createDataBase(DataBaseHelper.java:57)
at com.lumberjackapps.dailyhero.TestAdapter.createDatabase(TestAdapter.java:34)
at com.lumberjackapps.dailyhero.CharacterInfo$1.onClick(CharacterInfo.java:46)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
E/EGL_emulation: tid 955: eglCreateSyncKHR(1294): error 0x3004 (EGL_BAD_ATTRIBUTE)
E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa15d3f80
E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000

最佳答案

要将数据库与预定义数据一起使用,最好使用 AndroidSqliteAssetHelper .

这是自述文件的一部分:

An Android helper class to manage database creation and version management using an application's raw asset files.

This class provides developers with a simple way to ship their Android app with an existing SQLite database (which may be pre-populated with data) and to manage its initial creation and any upgrades required with subsequent version releases.

It is implemented as an extension to SQLiteOpenHelper, providing an efficient way for ContentProvider implementations to defer opening and upgrading the database until first use.

Rather than implementing the onCreate() and onUpgrade() methods to execute a bunch of SQL statements, developers simply include appropriately named file assets in their project's assets directory. These will include the initial SQLite database file for creation and optionally any SQL upgrade scripts.

关于Android 无法将数据库复制到 Assets 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38001520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com