android – 将我自己的SQLite DB从Asset文件夹复制到

我不明白为什么我无法将我的db文件(abic_)复制到应用程序目录(“/ data / data /”context.getPackageName()“/ databases”)

这是我的DataBaseHelper类:


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;


public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private String DB_PATH;

    private static String DB_NAME = "abic_";
    private static final Integer DB_VERSION = 1;

    private SQLiteDatabase mydb; 

    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, DB_VERSION);
        this.myContext = context;
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases";
    }   

    @Override
    public void onCreate(SQLiteDatabase db) {;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

public void apriDatabase() throws SQLException {
    try {
            String percorso = DB_PATH + DB_NAME;
            mydb = SQLiteDatabase.openDatabase(percorso, null, SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) {
            e.printStackTrace();
    }
}

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) {
                    e.printStackTrace();
            }
    }
}

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;

    // if the path doesn't exist first, create it
    File f = new File(outFileName);
    if (!f.exists()){
            f.mkdir();
            f.createNewFile();
    }

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

}

private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }catch(SQLiteException e){

            //database does't exist yet.

    }

    if(checkDB != null){

            checkDB.close();

    }

    return checkDB != null ? true : false;
} 

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

}

这是使用此类的listview:

  import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleCursorAdapter; 

public class abicabList extends ListActivity { 

        protected EditText searchText; 
        protected SQLiteDatabase mydb; 
        protected Cursor cursor; 
        protected ListAdapter adapter; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        mydb = (new DataBaseHelper(this)).getWritableDatabase(); 
        searchText = (EditText) findViewById (R.id.searchText); 
    } 

    public void search(View view) { 

     String text = searchText.getText().toString();
     String cap = "CAP";
     // || is the concatenation operation in SQLite 
      if (text.length()14) {      
 cursor = mydb.rawQuery("SELECT _id, ABI, BANCA, CAB, CAP, Filiale, City FROM abicab WHERE ABI || CAB LIKE ? LIMIT 30",  
          new String[]{"%" + searchText.getText().toString().substring(6,10) + "%" + searchText.getText().toString().substring(11,15) + "%"});     
     adapter = new SimpleCursorAdapter( 
                                this,  
                                R.layout.abicab_list_item,  
                                cursor,  
                                new String[] {"BANCA", "Filiale", "City", "CAP"},  
              new int[] {R.id.BANCA, R.id.Filiale, R.id.City ,R.id.CAP});
      setListAdapter(adapter);
    } 

   }  

因此,当我运行应用程序时,db在文件夹中创建,但它不包含我在资产文件夹中的数据库中的表(参见图片[1]:http://i.stack.imgur.com/AaFj8.jpg).
在此先感谢您的帮助.

最佳答案:

我已经解决了这个问题.

1)我使用了Almanac 0.0.17(开源项目)中使用的AlmanacSQLiteDatabaseAdapter.java类,您可以在这里找到:
link.您可以满足您的需求(在我的情况下,我已经重命名为DatabaseHelper);

2)这是使用Helper的类(它是一个listview,它在EditText中执行sql rawquery读取字符串 – 它是本教程的一个安排“coenraets.org/blog/android-samples/androidtutorial/”:

public class MiaList extends Activity { 

        protected EditText searchText; 
        protected SQLiteDatabase db; 
        protected Cursor cursor; 
        protected ListAdapter ladapter; 
        protected ListView miaList; 
        private static final String DATABASE_NAME = "miodb.jpg";
/*
L'ESTENSIONE JPG (o mp3, mov) questo perchè android ha il limite di 1 mb per i file di testo 
o simili nella asset, mentre NON HA limiti per i file multimediali! Nel mio caso si tratta di 4mb
*/

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 

//qui sotto richiamo la classe DatabaseHelper

        DatabaseHelper dbAdapter = DatabaseHelper.getInstance(this, DATABASE_NAME);
        /*note di Vytek*/
        // OK Dovrei usare aSQLiteDatabaseAdapter.getDatabase(); ma questo crea
        // problemi nella fase di OnPause quando premo Back cosi' invece non
        // ottengo errori
        // e viene fatta la normale copia del DB (13/8/2010 23.18)
        // db = aSQLiteDatabaseAdapter.getWritableDatabase();
        // Per ovviare a questo problema controllo se e' la prima volta che
        // chiamo applicazione
        if (getFirstRun()) {
                db = dbAdapter.getDatabase();
                setRunned();
        } else {
                db = dbAdapter.getWritableDatabase();
        }

        searchText = (EditText) findViewById (R.id.searchText); 
        miaList = (ListView) findViewById (R.id.list); 
    } 


    private void setRunned() {
                // TODO Auto-generated method stub

        }

        private boolean getFirstRun() {
                // TODO Auto-generated method stub
                return false;
        }

        public void search(View view) { 

        String text = searchText.getText().toString();
        // || è l'operatore "concatena" in SQLite 
         if (text.length()<15){
                    cursor = db.rawQuery("SELECT *FROM miatable WHERE AAA || ' ' || BBB || ' ' || CCC LIKE ? LIMIT 30",  
                            new String[]{"%" + searchText.getText().toString() + "%"}); 
                                ladapter = new SimpleCursorAdapter( 
                                                this,  
                                                R.layout.mialist_list_item,  
                                                cursor,  
                                                new String[] {"_id", "AAA", "BBB", "CCC"},  
                                                new int[] {R.id._id, R.id.AAA, R.id.BBB, R.id.CCC}); 
                                miaList.setAdapter(ladapter); 
                                //istruzione da eseguire
                }
         else {         
                   cursor = db.rawQuery("SELECT * FROM miatable WHERE AAA || BBB LIKE ? LIMIT 30",  
                           new String[]{"%" + searchText.getText().toString().substring(6,10) + "%" + searchText.getText().toString().substring(11,15) + "%"});         
                                ladapter = new SimpleCursorAdapter( 
                                                this,  
                                                R.layout.mialist_list_item,  
                                                cursor,  
                                                new String[] {"_id", "AAA", "BBB", "CCC"},  
                                                new int[] {R.id._id, R.id.AAA, R.id.BBB, R.id.CCC}); 
                                miaList.setAdapter(ladapter); 
                                //istruzione da eseguire
                  } 


        }

}

当然,SQLite DB“miodb.jpg”必须位于eclipse工作区的资产文件夹中.

PS
我使用jpg扩展名为db,因为资产文件夹对db或txt或xml扩展名有1Mb限制.

原文地址:https://codeday.me/bug/20190515/1110025.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


SQLite架构简单,又有Json计算能力,有时会承担Json文件/RESTful的计算功能,但SQLite不能直接解析Json文件/RESTful,需要用Java代码硬写,或借助第三方类库,最后再拼成insert语句插入数据表,代码非常繁琐,这里就不展示了。参考前面的代码可知,入库的过程比较麻烦,不能只用SQL,还要借助Java或命令行。SPL是现代的数据计算语言,属于简化的面向对象的语言风格,有对象的概念,可以用点号访问属性并进行多步骤计算,但没有继承重载这些内容,不算彻底的面向对象语言。...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制。本教程将告诉您如何使用 SQLite 编程,并让你迅速上手。.................................
安卓开发,利用SQLite实现登陆注册功能
相比大多数数据库而言,具有等优势,广泛应用于、等领域。
有时候,一个项目只有一个数据库,比如只有SQLite,或者MySQL数据库,那么我们只需要使用一个固定的数据库即可。但是一个项目如果写好了,有多个用户使用,但是多个用户使用不同的数据库,这个时候,我们就需要把软件设计成可以连接多个数据库的模式,用什么数据库,就配置什么数据库即可。4.Users实体类,这个实体类要和数据库一样的,形成一一对应的关系。11.Sqlite数据库,需要在代码里面创建数据库,建立表,再建立数据。8.我们开启MySQL数据库,然后进行调试,看程序的结果。2.安装SqlSugar。
基于Android的背单词软件,功能强大完整。
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统。说白了就是使用起来轻便简单,
Android的简单购物车案例
SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库...
Qt设计较为美观好看的登录注册界面(包含SQLite数据库以及TCP通信的应用)
SQLite是用C语言开发的跨平台小型数据库,可嵌入其他开发语言,也可在单机执行。SPL是用Java开发的跨平台的数据计算语言,可嵌入Java,可在单机执行,可以数据计算服务的形式被远程调用。两者的代码都是解释执行的。...
新建库.openDATA_BASE;新建表createtableLIST_NAME(DATA);语法:NAME关键字...<用逗号分割>删除表droptableNAME;查看表.schema查看表信息新建数据insertintoLIST_NAMEvalues();语法:CLASS,PARAMETER...,CLASS是类别,PARAMETER是参数<用逗号分割新建的
importsqlite3classDemo01:def__init__(self):self.conn=sqlite3.connect("sql_demo_001.db")self.cursor1=self.conn.cursor()self.cursor1.execute("select*fromtable_001wherename=?andid=?",('ssss&#0
 在客户端配置文件<configuration>节点下,添加:<connectionStrings>      <add name="localdb" connectionString="Data Source=config/local.db;Version=3;UseUTF16Encoding=True;" providerName="System.Data.SQLite.SQLiteFactory"/&g
提到锁就不得不说到死锁的问题,而SQLite也可能出现死锁。下面举个例子:连接1:BEGIN(UNLOCKED)连接1:SELECT...(SHARED)连接1:INSERT...(RESERVED)连接2:BEGIN(UNLOCKED)连接2:SELECT...(SHARED)连接1:COMMIT(PENDING,尝试获取EXCLUSIVE锁,但还有SHARED锁未释放,返回SQLITE_BUSY)连接2:INSERT...
SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。在使用SQLite前,我们先要搞清楚几个概念:表
设计思想————首先要确定有几个页面、和每个页面的大致布局由于是入门,我也是学习了不是很长的时间,所以项目比较low。。。。第一个页面,也就是打开APP的首页面:今天这个博客,先实现添加功能!:首先对主界面进行布局:其中activity_main.xml的代码为<?xmlversion="1.0"encoding="