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

2024-03-14

我不明白为什么我无法将数据库文件(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();
    }

}

这是使用此类的列表视图:

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

   }  

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


我已经解决了这个问题。

1)我使用了Almanac 0.0.17(开源项目)中使用的类AlmanacSQLiteDatabaseAdapter.java,您可以在这里找到:link http://code.google.com/p/almanac/source/browse/trunk/Almanac/src/it/almanac/AlmanacSQLiteDatabaseAdapter.java?r=56。您可以满足您的需求(在我的例子中,我已重命名为DatabaseHelper);

2)这是使用Helper的类(它是一个列表视图,在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 工作区的 asset 文件夹中。

PS 我对 db 使用了 jpg 扩展名,因为 asset 文件夹对 db 或 txt 或 xml 扩展名有 1Mb 的限制。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将我自己的 SQLite DB 从 Asset 文件夹复制到 的相关文章

  • 使用workmanager时Firestore脱机持久性错误

    我正在使用一个WorkManger定期从我的中检索信息Firestore当应用程序处于后台和前台时的数据库 此信息用于根据状态更新 UI 因此不同的状态会添加或删除 UI 的不同部分 第一次运行时效果很好 但是 一旦应用程序处于后台并且Wo
  • 卸载后 Web 应用程序不显示“添加到主屏幕”

    这是我第一次创建网络应用程序 我设法解决了这个问题 所以我得到了实际的 chrome 提示 将其添加到主屏幕 然后我从手机上卸载了该网络应用程序 因为我想将其展示给我的同事 但是 屏幕上不再出现提示 问题 这是有意为之的行为还是我的应用程序
  • 找不到 com.google.firebase:firebase-core:9.0.0 [重复]

    这个问题在这里已经有答案了 在遵循有些不一致的指示之后here https firebase google com docs admob android quick start name your project and here http
  • CardView 圆角获得意想不到的白色

    When using rounded corner in CardView shows a white border in rounded area which is mostly visible in dark environment F
  • 是否可以将数组或对象添加到 Android 上的 SharedPreferences

    我有一个ArrayList具有名称和图标指针的对象 我想将其保存在SharedPreferences 我能怎么做 注意 我不想使用数据库 无论 API 级别如何 请检查SharedPreferences 中的字符串数组和对象数组 http
  • Android Activity 生命周期函数基础知识

    我正在测试这段代码 它显示活动所处的状态 public class Activity101Activity extends Activity String tag Lifecycle Called when the activity is
  • Android 中 Kotlin 协程的正确使用方式

    我正在尝试使用异步更新适配器内的列表 我可以看到有太多的样板 这是使用 Kotlin 协程的正确方法吗 这个可以进一步优化吗 fun loadListOfMediaInAsync async CommonPool try Long runn
  • 在 HTTPResponse Android 中跟踪重定向

    我需要遵循 HTTPost 给我的重定向 当我发出 HTTP post 并尝试读取响应时 我得到重定向页面 html 我怎样才能解决这个问题 代码 public void parseDoc final HttpParams params n
  • 如何使用 Cordova 获取当前安装的应用程序的版本?

    我已经找到了应用程序可用性插件 https github com ohh2ahh AppAvailability它主要检查用户是否在其设备上安装了某个应用程序 是否有可能获得应用程序的当前版本 开发者名称 重要 以及所有可能的信息 一般来说
  • 发布android后更改应用内购买项目的价格

    在 Google Play 上发布后 是否可以更改应用内购买商品的价格 我假设该应用程序也已发布 完整的在线文档位于http developer android com http developer android com也http sup
  • 原色(有时)变得透明

    我正在使用最新的 SDK 版本 API 21 和支持库 21 0 2 进行开发 并且在尝试实施新的材料设计指南时遇到了麻烦 材料设计说我需要有我的primary color and my accent color并将它们应用到我的应用程序上
  • 如何使用InputConnectionWrapper?

    我有一个EditText 现在我想获取用户对此所做的所有更改EditText并在手动将它们插入之前使用它们EditText 我不希望用户直接更改中的文本EditText 这只能由我的代码完成 例如通过使用replace or setText
  • 如何默认在 ActionOpenDocument 意图中显示“内部存储”选项

    我需要用户选择一个自定义文件类型的文件 并将其从 Windows 文件资源管理器拖到 Android 设备上 但默认情况下内部存储选项不可用 当我使用以下命令启动意图时 var libraryIntent new Intent Intent
  • Android Studio - Windows 7 上的 Android SDK 问题

    我对 Google i o 2013 上发布的最新开发工具 Android Studio 有疑问 我已经成功安装了该程序并且能够正常启动 我可以导入现有项目并对其进行编辑 但是 当我尝试单击 SDK 管理器图标或 AVD 管理器图标时 或者
  • iphone sqlite 静态链接?

    有人静态链接 sqlite 而不是使用动态链接 吗 我遇到的问题是 越狱手机的用户没有与普通 iPhone 所采用的 sqlite 版本相同的版本 因此导致崩溃 我假设在我的应用程序中静态链接已知版本的 sqlite 就是答案 我需要全文支
  • Android 中麦克风的后台访问

    是否可以通过 Android 手机上的后台应用程序 服务 持续监控麦克风 我想做的一些想法 不断聆听背景中的声音信号 收到 有趣的 音频信号后 执行一些网络操作 如果前台应用程序需要的话 后台应用程序必须能够智能地放弃对麦克风的访问 除非可
  • 如何根据 gradle 风格设置变量

    我想传递一个变量test我为每种风格设置了不同的值作为 NDK 的定义 但出于某种原因 他总是忽略了最后味道的价值 这是 build gradle apply plugin com android library def test andr
  • 将两个文本视图并排放置在布局中

    我有两个文本视图 需要在布局中并排放置 并且必须遵守两条规则 Textview2 始终需要完整显示 如果布局中没有足够的空间 则必须裁剪 Textview1 例子 文本视图1 文本视图2 Teeeeeeeeeeeeeeeeeextview1
  • Crashlytics 出现 Android Studio 构建错误

    我正在尝试将 CrashLytics 与 Android Studio 和 gradle 一起使用 但出现一个令人困惑的错误 java lang NoSuchMethodError 我的 build gradle 是 buildscript
  • 按日期对 RecyclerView 进行排序

    我正在尝试按日期对 RecyclerView 进行排序 但我尝试了太多的事情 我不知道现在该尝试什么 问题就出在这条线上适配器 notifyDataSetChanged 因为如果我不放 不会显示错误 但也不会更新 recyclerview

随机推荐