gpt4 book ai didi

Android 无法从 Assets 复制数据库

转载 作者:行者123 更新时间:2023-11-30 04:14:29 26 4
gpt4 key购买 nike

我有一个问题。我有 2 个安卓项目。一个是“主要”项目。另一个项目是我尝试根据在 Internet 上找到的教程实现基本的测验应用程序。

测验应用程序运行正常,所以我想在“主”项目上实现它。 (在“主”项目中,我有 2 个包,一个用于测验的类)我创建了类、布局,将数据库复制到 Assets 文件夹。一切都和第二个项目一样。但它不能复制数据库。我有找不到表的错误。

它生成了数据库,我用 ddms 检查了它(拉出数据库)但无法复制表格。 “主项目”中的代码与第二个项目相同(!)。 (在第二个项目中一切都很好)

代码 fragment 如下:

package com.thesis.Quiz;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.thesis.eliminations.R;
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 DBHelperForQuiz extends SQLiteOpenHelper{

//The Androids default system path of your application database.
private static String DB_PATH = "/data/data/com.thesis.eliminations/databases/";
private static String DB_NAME = "QuizDB";
private SQLiteDatabase myDataBase;
private final Context myContext;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DBHelperForQuiz(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}

/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{

boolean dbExist = checkDataBase();
//SQLiteDatabase db_Read = null;
//SQLiteDatabase db = null;
if(dbExist){
//do nothing - database already exist
//db = super.getReadableDatabase();
}else{
this.getReadableDatabase();
//db_Read = this.getReadableDatabase();
//db_Read.close();
try {
copyDataBase();
// db = super.getReadableDatabase();
} catch (IOException e) {
//throw new Error("Error copying database");
e.printStackTrace();
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
//InputStream myInput = myContext.getAssets().open(DB_NAME);
InputStream myInput = myContext.getResources().getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}

public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}

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

public List<Question> getQuestionsList(int difficulty, int numberOfQuestions) {
Log.d("NOQ",Integer.toString(numberOfQuestions));
List<Question> questionsList = new ArrayList<Question>();
Cursor c = myDataBase
.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY="
+ difficulty + " ORDER BY RANDOM() LIMIT "
+ numberOfQuestions, null);

while (c.moveToNext()) {
Question q = new Question();
q.setQuestionText(c.getString(1));
q.setRightAnswer(c.getString(2));
q.setAnswerOption1(c.getString(3));
q.setAnswerOption2(c.getString(4));
q.setAnswerOption3(c.getString(5));
q.setQuestionDiffLevel(difficulty);
questionsList.add(q);
}
return questionsList;
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}

和:

public class QuizActivityMain extends Activity implements OnClickListener {

Button bStart, bQuit, bSetDiff;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quizmenu);
initialize();
}

private void initialize() {
bStart = (Button) findViewById(R.id.bStartQuiz);
bQuit = (Button) findViewById(R.id.bExitQuiz);
bSetDiff = (Button) findViewById(R.id.bSetDiff);
bSetDiff.setOnClickListener(this);
bQuit.setOnClickListener(this);
bStart.setOnClickListener(this);
Log.d("init", "initialize..");
}

@Override
public void onClick(View v) {
Intent i;
switch (v.getId()) {
case R.id.bStartQuiz:
List<Question> questionsList = getQuestionsFromDB();
QuizGame currentQuizGame = new QuizGame();
currentQuizGame.setNumberOfRounds(this.getNumOfQuestions());
currentQuizGame.setQuestions(questionsList);
Log.d("ql set", "ql set");
/* ((QuizApplication) getApplication())
.setCurrentQuizGame(currentQuizGame);*/

((QuizApplication)getApplication()).setCurrentQuizGame(currentQuizGame);
Log.d("cqg set", "cqg set");
i = new Intent(this, AskedQuestion.class);
Log.d("i started", "intent");
startActivity(i);
Log.d("i started", "intent started");
break;

case R.id.bExitQuiz:
finish();
break;

case R.id.bSetDiff:
i = new Intent(this, QuizSettings.class);
startActivity(i);
break;
}
}

private List<Question> getQuestionsFromDB() throws Error{
int tmpDifficulty = getDifficulty();
int tmpNumberOfQuestions = getNumOfQuestions();
DBHelperForQuiz myDbHelper = new DBHelperForQuiz(this.getApplicationContext());
myDbHelper = new DBHelperForQuiz(this);

try {
myDbHelper.createDataBase();
} catch (IOException e) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
Log.d("openeddb", "open db success");
} catch (SQLException sqle) {
throw sqle;
}

Log.d("ql try", "ql making");
List<Question> qL = myDbHelper.getQuestionsList(tmpDifficulty, tmpNumberOfQuestions);

Log.d("TMPNOQ",Integer.toString(tmpNumberOfQuestions));
Log.d("ql rdy", "ql done");
myDbHelper.close();
Log.d("db cls", "closed");
return qL;
}

private int getNumOfQuestions() {
return 5;
}

private int getDifficulty() {
return 2;
}
}

最佳答案

在 createDataBase() 中有以下检查;

this.getReadableDatabase();

这会检查是否已经存在具有所提供名称的数据库,如果没有,则创建一个空数据库,以便可以用 Assets 文件夹中的数据库覆盖它。在较新的设备上,这可以完美运行,但有些设备无法运行。主要是旧设备。我不知道为什么,但似乎 getReadableDatabase() 函数不仅获取数据库而且打开它。如果您随后将数据库从 Assets 文件夹复制到它上面,它仍然具有指向空数据库的指针,您将收到表不存在的错误。

因此,为了使其适用于所有设备,您应该将其修改为以下几行:

SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
db.close();
}

即使在检查时打开了数据库,之后关闭了,也不会再给你添麻烦。

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

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