【问题标题】:Titanium how to move DB to SD cardTitanium如何将DB移动到SD卡
【发布时间】:2014-07-09 08:58:43
【问题描述】:

我正在使用 Titanium for Android 进行编程。 我有 6 个 sqlite 数据库,我不想将它们存储在设备内存中,因为 DB 数量太大。

那么,如何以编程方式将 sqlite 文件移动到 SD 卡?或者当用户从 PlayStore 安装我的应用程序时,如何直接在 SD 卡上安装 Dbs?

PD:我尝试添加“PreferExternal”,但这并没有解决我的问题。

<manifest android:installLocation="preferExternal</manifest>

提前致谢!

【问题讨论】:

    标签: database sqlite titanium


    【解决方案1】:

    来自Ti.Database.open 的 Titanium 文档。

    在外部存储上打开数据库 (Android) 文件名为 mydb2Installed 且位于提供的绝对路径的数据库已打开。

    if (Ti.Platform.name === 'android' && Ti.Filesystem.isExternalStoragePresent()) {
      var db2 = Ti.Database.open(Ti.Filesystem.externalStorageDirectory + 'path' + Ti.Filesystem.separator + 'to' + Ti.Filesystem.separator + 'mydb2Installed');
    }
    

    希望这能解决问题。

    【讨论】:

    • 但我无法更新 sdcard 中的数据库。它说它是只读的
    • 你到底在做什么?意味着你如何手动修改 sdcard 中的数据库?
    • 当我尝试更新行时,我正在读取应用程序内 sdcard 中的数据库表。我有错误。 stackoverflow.com/questions/26333738/…
    【解决方案2】:

    我对钛一无所知。但在 android 中,您可以通过以下逻辑移动 DB:

    1. 将 Database.db 文件复制到项目资产文件夹中。
    2. 在清单文件中定义如下所示的权限:

       <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      
    3. 现在使用从 /asset 到设备外部存储的代码复制数据库文件

    复制文件使用下面的代码,

        try {
         // Open your local db as the input stream
         InputStream myInput = myContext.getAssets().open("your database file name");
    
         // Path to the just created empty db
         String outFileName = "path of external storage/<database_file_name>";
    
         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();
         } 
         catch (Exception e) 
          {
           Log.e("error", e.toString());
          } 
    

    【讨论】:

      【解决方案3】:

      根据这个问题:Android: use SQLite database on SD Card (not using internal Android Data Store at all)

      你可以使用:

       SQLiteDatabase.openOrCreateDatabase(String, SQLiteDatabase.CursorFactory) 
      

      将您的路径作为第一个参数,将 null 作为第二个参数。 要获取 sdcard 的路径,请执行以下操作:

       Environment.getExternalStorageDirectory();
      

      但请注意,对设备有物理访问权限的每个人都可以访问数据库文件...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 2020-01-11
        • 2023-03-18
        • 2021-02-18
        • 2012-10-17
        • 2012-06-07
        相关资源
        最近更新 更多