Can't copy sqlite database from assets folder in Android

前端 未结 1 893
星月不相逢
星月不相逢 2021-01-16 11:58

I have been trying to copy a sqlite database file from assets folder so that i create a sqlite database and use it in my program, here is the code:-

first the

相关标签:
1条回答
  • 2021-01-16 12:38

    Make your DbHelper like this,

    public class DBHandler extends SQLiteOpenHelper {
    protected static final String DATABASE_NAME_PRODUCTION = "productionComments.db";
    private Context context;
    
    public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory,
                         int version) {
            super(context, name, factory, DATABASE_VERSION);
            this.context = context;
        }
    
           //copy database from assets folder (.sqlite) file to an empty database
            public void copyDataBase() throws IOException{
    
            //Open your local db as the input stream
            InputStream myInput = context.getAssets().open("prod.db");
    
            // Path to the just created empty db
            String outFileName = "/data/data/com.qarun.qpcbeta/databases/"+DATABASE_NAME_PRODUCTION;
    
            //Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);
    
            //transfer bytes from the input file to the output file
            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();
        }
    
    0 讨论(0)
提交回复
热议问题