复制SQLite数据库的Andr​​oid应用程序 [英] Copy Sqlite database for android application

查看:141
本文介绍了复制SQLite数据库的Andr​​oid应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用本教程中的http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

我有我的数据库在我的资产文件夹中已经工作了5小时,以避开工作,但徒劳的。我始终保持让

 四月一日至17日:09:07.111:E /数据库(1060):sqlite3_open_v2(/数据/数据​​/ com.rahul.besttracker /数据库/路由,&安培;手柄1,NULL)失败

 四月一日至17日:09:07.271:E / AndroidRuntime(1060):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.rahul.besttracker / com.rahul。 besttracker.Busdisplay}:android.database.sqlite.SQLiteException:无法打开数据库文件

我的code

 公共类Busdisplay扩展ListActivity {
TextView的源,目的;
的字符串src,DEST;
ArrayList的<串GT; mArrayList;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);    在里面();
    包抓= getIntent()getExtras()。
    SRC = caught.getString(源);
    DEST = caught.getString(目标);    DataBaseHelper进入= NULL;    进入=新DataBaseHelper(Busdisplay.this);    entry.openDataBase();    mArrayList = entry.readEntry(SRC,DEST);    entry.close();    setListAdapter(新ArrayAdapter<串GT;(这一点,
            android.R.layout.simple_list_item_1,mArrayList));
}@覆盖
保护无效onListItemClick(ListView中升,视图V,INT位置,长的id){
    // TODO自动生成方法存根
    super.onListItemClick(L,V,位置ID);
}无效的init(){
    来源=(的TextView)findViewById(R.id.textView1);
    目的地=(的TextView)findViewById(R.id.textView2);
}   }

我DBhelper类

 公共类DataBaseHelper扩展SQLiteOpenHelper {//你的应用程序数据库的Andr​​oid的默认系统路径。
私有静态最后弦乐DB_PATH =/data/data/com.rahul.besttracker/databases/;私有静态最后弦乐DB_NAME =route.db;
私有静态最后弦乐DB_TABLE1 =ROUTE1;
私有静态最后弦乐DB_TABLE2 =路径2;
私人SQLiteDatabase MYDATABASE;私人最终上下文myContext;/ **
 *构造函数和不断传递的上下文中的一个参考,以
 *访问应用程序的资产和资源。
 *
 * @参数方面
 * /
公共DataBaseHelper(上下文的背景下){    超级(上下文,DB_NAME,空,1);
    this.myContext =背景;
}/ **
 *在系统上创建一个空数据库,然后用自己的重写它
 *数据库。
 * * /
公共无效的CreateDatabase()抛出IOException    布尔dbExist = checkDataBase();    如果(dbExist){
        //什么也不做 - 已存在于数据库
    }其他{        //通过调用此方法与空的数据库将被创建成
        //默认的系统路径
        //你的应用程序,所以我们要能够覆盖
        //数据库与我们的数据库。
        this.getReadableDatabase();        尝试{            copyDataBase();        }赶上(IOException异常五){            抛出新的错误(错误复制数据库);        }
    }}/ **
 *检查是否已存在于数据库,以避免重新复制每个文件
 *一次打开应用程序。
 *
 *如果存在返回:真的,假的,如果它不
 * /
私人布尔checkDataBase(){    SQLiteDatabase CHECKDB = NULL;    尝试{
        字符串mypath中= DB_PATH + DB_NAME;
        CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,
                SQLiteDatabase.OPEN_READONLY);    }赶上(SQLiteException E){        System.out.print(错误);
    }    如果(CHECKDB!= NULL){        checkDB.close();    }    返回CHECKDB!= NULL?真假;
}/ **
 *副本数据库从本地资产文件夹复制到刚创建
 *在系统文件夹,空数据库从那里可以访问和
 *处理。这是通过转流的字节流进行。
 * * /
私人无效copyDataBase()抛出IOException    //打开本地数据库的输入流
    InputStream的myInput = myContext.getAssets()开(DB_NAME)。    //路径刚刚创建的空分贝
    字符串outFileName = DB_PATH + DB_NAME;    //打开空分贝的输出流
    的OutputStream myOutput =新的FileOutputStream(outFileName);    //传递从inputfile中字节到OUTPUTFILE
    字节[]缓冲区=新的字节[1024];
    INT长;
    而((长度= myInput.read(缓冲液))大于0){
        myOutput.write(缓冲液,0,长度);
    }    //关闭流
    myOutput.flush();
    myOutput.close();
    myInput.close();}公共无效的openDatabase()抛出的SQLException {    //打开数据库
    字符串mypath中= DB_PATH + DB_NAME;
    MYDATABASE = SQLiteDatabase.openDatabase(mypath中,空,
            SQLiteDatabase.OPEN_READONLY);}@覆盖
公共同步无效的close(){    如果(MYDATABASE!= NULL)
        myDataBase.close();    super.close();}@覆盖
公共无效的onCreate(SQLiteDatabase DB){
    尝试{
        的CreateDatabase();
    }赶上(IOException异常五){
        // TODO自动生成catch块
        e.printStackTrace();
    }
}@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
    db.execSQL(DROP TABLE IF EXISTS+ DB_TABLE1);
    db.execSQL(DROP TABLE IF EXISTS+ DB_TABLE2);
    的onCreate(DB);
}公众的ArrayList<串GT; readEntry(SRC字符串,字符串DEST){    // TODO自动生成方法存根
    光标C = myDataBase.rawQuery(+ DB_TABLE1从选择route_no
            +WHERE停止LIKE'%+ SRC +%,%+ DEST +%;,NULL);
    ArrayList的<串GT; mArrayList =新的ArrayList<串GT;();
    INT指数= c.getColumnIndex(route_no);
    为(c.moveToFirst();!c.isAfterLast(); c.moveToNext()){
        //光标现设置到合适的位置
        mArrayList.add(c.getString(指数));
    }
    返回mArrayList;
}//添加您的公开辅助方法来访问,并从一开始的内容
//数据库。
//你可以做返回游标返回myDataBase.query(....),所以它会
// 放轻松
//你创建你的意见适配器。  }


解决方案

使用 SQLiteAssetHelper 解决了这个问题。

I am trying to use my own created database in my android application using this tutorial http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

I have my database in my assets folder have been working for 5 hours to get the work around but in vain.. i always keep getting

01-17 04:09:07.111: E/Database(1060): sqlite3_open_v2("/data/data/com.rahul.besttracker/databases/route", &handle, 1, NULL) failed

and

01-17 04:09:07.271: E/AndroidRuntime(1060): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rahul.besttracker/com.rahul.besttracker.Busdisplay}: android.database.sqlite.SQLiteException: unable to open database file

my code

    public class Busdisplay extends ListActivity {
TextView source, destination;
String src, dest;
ArrayList<String> mArrayList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    init();
    Bundle caught = getIntent().getExtras();
    src = caught.getString("source");
    dest = caught.getString("dest");

    DataBaseHelper entry = null;

    entry = new DataBaseHelper(Busdisplay.this);

    entry.openDataBase();

    mArrayList = entry.readEntry(src, dest);

    entry.close();

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, mArrayList));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
}

void init() {
    source = (TextView) findViewById(R.id.textView1);
    destination = (TextView) findViewById(R.id.textView2);
}

   }

My DBhelper class

    public class DataBaseHelper extends SQLiteOpenHelper {

// The Android's default system path of your application database.
private static final String DB_PATH =   "/data/data/com.rahul.besttracker/databases/";

private static final String DB_NAME = "route.db";
private static final String DB_TABLE1 = "route1";
private static final String DB_TABLE2 = "route2";
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 DataBaseHelper(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();

    if (dbExist) {
        // do nothing - database already exist
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

/**
 * 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) {

        System.out.print("ERROR");
    }

    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);

    // 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();

}

@Override
public void onCreate(SQLiteDatabase db) {
    try {
        createDataBase();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

public ArrayList<String> readEntry(String src, String dest) {

    // TODO Auto-generated method stub
    Cursor c = myDataBase.rawQuery("SELECT route_no from " + DB_TABLE1
            + " WHERE stops LIKE '%" + src + "%,%" + dest + "%';", null);
    ArrayList<String> mArrayList = new ArrayList<String>();
    int index = c.getColumnIndex("route_no");
    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
        // The Cursor is now set to the right position
        mArrayList.add(c.getString(index));
    }
    return mArrayList;
}

// Add your public helper methods to access and get content from the
// database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd
// be easy
// to you to create adapters for your views.

  }

解决方案

Using SQLiteAssetHelper solved the problem.

这篇关于复制SQLite数据库的Andr​​oid应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆