简体   繁体   中英

Can I use a pre-build SQLite Database from assets file with room database library?

I'm building a launcher app. In that app, some apps(package name, the icon) will be pre-added to SQLite and later users can add more apps(package name, the icon) in that SQLite database, and for updating data live. I want to use room database.

So, my question is, Can I use a pre-build SQLite Database from assets file with room database library?

Please help me.

You could bundle a json file with the app. Then read it like so

 try {
        InputStream inputStream = mContext.getAssets().open(mContext.getPackageName() + ".json");

        int size = inputStream.available();
        byte[] buffer = new byte[size];

        if (inputStream.read(buffer) != size) {
            throw new IndexOutOfBoundsException();
        }
        inputStream.close();

        JSONObject jsonObject = new JSONObject(new String(buffer, StandardCharsets.UTF_8));

        List<SomeClass> classList = new ArrayList<>();
        JSONArray jsonElements = jsonObject.getJSONArray("dataset1");
        for(int i =0; i < jsonElements.length(); i++){
            SomeClass someClass = new SomeClass(jsonElements.get(i));
            classList.add(someClass);
        }

        appDatabase.insert(classList);
        } catch(Exception exception){
        }

That would be the manual way of doing it. However you can build a backup/restore and only use the restore side by following: Backup/Restore Room Database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM