ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2019-05-15 20:12:00  阅读:194  来源: 互联网

标签:android sqlite


我不明白为什么我无法将我的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限制.

标签:android,sqlite
来源: https://codeday.me/bug/20190515/1110025.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有