2015-11-12 52 views
1

所以我知道类似的问题已经被问到,但我找不到适合我的确切情况的东西。将现有SQLite数据库导入Android应用程序

我有一个应用程序创建一个数据库并填充它等,但我没有在我的设备上的根访问,所以这是我的问题。我需要用一些值填充这个数据库,然后将其导入到我的应用程序/设备中。

如果我有root用户访问权限,我可以直接替换/data/data/com.my.application/databases文件夹中的数据库,但由于我没有root权限,我需要能够导入此数据库我改变了这个位置并且替换了标准的位置。

任何人都可以帮助我一起代码或如何将数据库导入到此文件夹的示例?我只需要能够导入和替换现有的。

感谢, 的Wihan

+0

在这里找到了答案,似乎工作。 http://stackoverflow.com/questions/2078710/android-adb-access-to-application-databases-without-root –

回答

4

你可以使用这个库到您的设备上使用导入的数据库:

https://github.com/jgilfelt/android-sqlite-asset-helper

正如你只需要把你的数据库文件在文件上注明assets目录下的资产文件夹/assets/databases/database.db

然后创建一个DBHelper类,它从SQLiteAssetHelper延伸如下:

public class DBHelper extends SQLiteAssetHelper { 

    private static final String DATABASE_NAME = "example.db"; 
    private static final int DATABASE_VERSION = 1; 

    public DBHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

} 

您现在可以访问您的数据与内容提供商和所有的东西。

此外,您可以使用http://sqlitebrowser.org/在您的计算机上创建预加载的数据库。

希望它有帮助。

0
public String loadJSONFromAsset(Context context) { 
     String json = null; 
     try { 
      InputStream is = context.getAssets().open("Hospital.db"); 
      int size = is.available(); 
      OutputStream myoutput = new FileOutputStream("/data/data/-----PACKAGE NAME------/databases/Hospital.db"); 

      byte[] buffer = new byte[size]; 
      int length; 
      while ((length = is.read(buffer)) > 0) { 
       myoutput.write(buffer, 0, length); 
      } 

      //Close the streams 
      myoutput.flush(); 
      myoutput.close(); 
      is.close(); 
//   byte[] buffer = new byte[size]; 
//   is.read(buffer); 
//   is.close(); 
//   json = new String(buffer, "UTF-8"); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
      return null; 
     } 
     return json; 
    } 
+0

是需要注释的行吗? – user7294900

+0

用您的包名替换它! @ user7294900 – Xenolion

相关问题