Android无法从资产复制数据库
我有个问题。我有两个android项目。一个是“主要”项目。另一个是一个项目,我试图实现一个基于互联网上的教程的基本测验应用程序 测验应用程序工作正常,所以我想在“Main”项目上实现它。(在“Main”项目中,我有两个包,一个用于测验的类)我创建了类、布局,将数据库复制到assets文件夹。一切都和第二个项目一样。但是它不能复制数据库。我发现表未找到错误 它生成了数据库,我用ddms检查了它(拉取了数据库),但无法复制表。“主项目”中的代码与第二个项目中的代码相同(!)。(在第二个项目中,一切都很好) 以下是代码片段:Android无法从资产复制数据库,android,database,copy,Android,Database,Copy,我有个问题。我有两个android项目。一个是“主要”项目。另一个是一个项目,我试图实现一个基于互联网上的教程的基本测验应用程序 测验应用程序工作正常,所以我想在“Main”项目上实现它。(在“Main”项目中,我有两个包,一个用于测验的类)我创建了类、布局,将数据库复制到assets文件夹。一切都和第二个项目一样。但是它不能复制数据库。我发现表未找到错误 它生成了数据库,我用ddms检查了它(拉取了数据库),但无法复制表。“主项目”中的代码与第二个项目中的代码相同(!)。(在第二个项目中,一切
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
}
}
package.com.thesis.quick;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.util.ArrayList;
导入java.util.List;
进口商品论文.剔除.R;
导入android.content.Context;
导入android.database.Cursor;
导入android.database.SQLException;
导入android.database.sqlite.SQLiteDatabase;
导入android.database.sqlite.SQLiteException;
导入android.database.sqlite.SQLiteOpenHelper;
导入android.util.Log;
公共类DbHelperForQuike扩展了SQLiteOpenHelper{
//Androids是应用程序数据库的默认系统路径。
私有静态字符串DB_PATH=“/data/data/com.thesis.eliminations/databases/”;
私有静态字符串DB_NAME=“QuizDB”;
私有SQLiteDatabase-myDataBase;
私有最终上下文myContext;
/**
*建造师
*获取并保留传递的上下文的引用,以便访问应用程序资产和资源。
*@param上下文
*/
public DbHelperForQuike(上下文){
super(上下文,DB_名称,null,1);
this.myContext=上下文;
}
/**
*在系统上创建一个空数据库,并用您自己的数据库重写它。
* */
public void createDataBase()引发IOException{
布尔值dbExist=checkDataBase();
//SQLiteDatabase db_Read=null;
//SQLiteDatabase db=null;
if(dbExist){
//不执行任何操作-数据库已存在
//db=super.getReadableDatabase();
}否则{
这是.getReadableDatabase();
//db_Read=this.getReadableDatabase();
//db_Read.close();
试一试{
copyDataBase();
//db=super.getReadableDatabase();
}捕获(IOE异常){
//抛出新错误(“复制数据库时出错”);
e、 printStackTrace();
}
}
}
/**
*检查数据库是否已存在,以避免每次打开应用程序时重新复制文件。
*@如果存在则返回true,如果不存在则返回false
*/
私有布尔校验数据库(){
SQLiteDatabase checkDB=null;
试一试{
字符串myPath=DB_PATH+DB_NAME;
checkDB=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN\u READONLY);
}catch(sqlitee异常){
//数据库还不存在。
}
if(checkDB!=null){
checkDB.close();
}
return checkDB!=null?true:false;
}
/**
*将数据库从本地资产文件夹复制到中刚创建的空数据库
*系统文件夹,从中可以访问和处理它。
*这是通过传输bytestream来完成的。
* */
私有void copyDataBase()引发IOException{
//打开本地数据库作为输入流
//InputStream myInput=myContext.getAssets().open(DB_NAME);
InputStream myInput=myContext.getResources().getAssets().open(数据库名称);
//刚创建的空数据库的路径
字符串outFileName=DB_路径+DB_名称;
//打开空数据库作为输出流
OutputStream myOutput=新文件OutputStream(outFileName);
//将字节从输入文件传输到输出文件
字节[]缓冲区=新字节[1024];
整数长度;
而((长度=myInput.read(缓冲区))>0){
写入(缓冲区,0,长度);
}
//关闭溪流
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase()引发SQLException{
//打开数据库
字符串myPath=DB_PATH+DB_NAME;
myDataBase=SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN\u READONLY);
}
@凌驾
公共同步作废关闭(){
if(myDataBase!=null)
myDataBase.close();
super.close();
}
公共列表getQuestionsList(整数难度,整数个问题){
Log.d(“NOQ”,Integer.toString(numberOfQuestions));
列表问题列表=新的ArrayList();
游标c=myDataBase
.rawQuery(“从难度=”的问题中选择*”
+难度+“按随机顺序()限制”
+numberOfQuestions,空);
while(c.moveToNext()){
问题q=新问题();
q、 setQuestionText(c.getString(1));
q、 setRightAnswer(c.getString(2));
q、 设置应答选项1(c.getString(3));
q、 setAnswerOption2(c.getString(4));
q、 设置应答选项3(c.getString(5));
q、 设置问题等级(难度);
问题列表。添加(q);
}
返回问题列表;
}
@凌驾
public void onCreate(SQLiteDatabase db){
//TODO自动生成的方法存根
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
//TODO自动生成的方法存根
}
}
以及:
公共类QuizaActivityMain扩展活动实现OnClickListener{
按钮bStar
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;
}
}
this.getReadableDatabase();
SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
db.close();
}