Android external database in assets folder

后端 未结 5 1669
故里飘歌
故里飘歌 2020-12-31 23:21

I have an android application that is supposed to read and expand a database that is already created on sqlite...it works fine on emulator by putting database in \"data/data

5条回答
  •  青春惊慌失措
    2020-12-31 23:35

    you cant access the database from asset folder directly you need to copy it first to the path data/data/(packagename)/database then using it :

     private String DB_PATH = "/data/data/" + "yourpackaename" + "/databases/" + "db.db";
    

    in your onCreate()

     is = getAssets().open("db.db");
     write(is);
    

    Then the method to call:

    public void write(InputStream is) {
        try {
            OutputStream out = new FileOutputStream(new File(DB_PATH));
            int read = 0;
            byte[] bytes = new byte[1024];
    
            while ((read = is.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            is.close();
            out.flush();
            out.close();
            System.err.println(out + "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题