SQLite Room快速插入JSON数组

时间:2017-12-20 11:45:58

标签: android json sqlite android-room

我正在创建一个词汇表应用程序,它将JSON文件中的单词/定义加载到JSON数组中。然后我遍历JSON数组以将数据加载到房间数据库中。

基于Log语句,JSON数组加载速度非常快(可能最多1-2秒),但Room数据库需要很长时间才能在异步线程中加载(大约40秒)。

我的MainActivity类尝试将数据库中的单词加载到onCreate中的布局中,但显然应用程序崩溃了,因为数据库还没有完成加载。

解决这个问题的推荐方法是什么?仅供参考,数据库只需要创建一次,并且只能在第一次加载后读取。

我对可能的解决方案的想法:

1)用户首次打开应用程序时使用JSONArray数据,然后在

之后使用数据库

2)将数据文件文件的副本添加到assets文件夹并从那里访问它(不确定这对于Room是如何工作的)

3)也许我的代码效率低下,加载Room DB的速度更快?

private String fileName = "majortests_words.json";
private JSONArray wordBankAry;
Word currentWord = new Word();
int totalWords = 1000;
Random rand = new Random();
int currentWordIndex = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    deleteDatabase("word-database");
    loadWords();
    DatabaseInitializer.populateAsync(AppDatabase.getAppDatabase(this), wordBankAry);

    currentWordIndex = rand.nextInt(totalWords);
    currentWord = AppDatabase.getAppDatabase(this).wordDao().getWord(currentWordIndex);

    // code to add attributes of currentWord to the layout

public String loadJSONData() {
    String jsonStr = null;
    try {
        InputStream iStream = getAssets().open(fileName);
        int size = iStream.available();
        byte[] buffer = new byte[size];
        iStream.read(buffer);
        iStream.close();

        jsonStr = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return jsonStr;
}

public void loadWords() {
    try {
        String jsonStr = loadJSONData();
        JSONObject jsonObj = new JSONObject(jsonStr);
        wordBankAry = jsonObj.getJSONArray("wordBank");
        totalWords = wordBankAry.length();
        Log.d("MainActivity", "JSON Count:" + wordBankAry.length());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Database(entities = {Word.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase INSTANCE;
    static String DB_NAME = "word-database";

    public abstract WordDao wordDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME).allowMainThreadQueries().build();
    }
    return INSTANCE;
}

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

@Dao
public interface WordDao {
    @Insert
    public void insertWords(Word word);

    @Query("SELECT * FROM words")
    List<Word> getAll();

    @Query("SELECT * FROM words WHERE id = :id")
    public Word getWord(int id);
}

public class DatabaseInitializer {

    private static final String TAG = DatabaseInitializer.class.getName();

    public static void populateAsync(@NonNull final AppDatabase db, JSONArray wordBankAry) {
        PopulateDbAsync task = new PopulateDbAsync(db, wordBankAry);
        task.execute();
    }

    public static Word addWord(final AppDatabase db, Word word) {
        db.wordDao().insertWords(word);
        return word;
    }

    private static void populateWordBank(AppDatabase db, JSONArray wordBankAry) {
        Word word = new Word();
        try {
            for (int wordIndex = 0; wordIndex < wordBankAry.length(); wordIndex++) {
                JSONObject jsonObj = wordBankAry.getJSONObject(wordIndex);
                word.setWordName(jsonObj.getString("word"));
                word.setWordDefinition(jsonObj.getString("definition"));

                addWord(db, word);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        List<Word> wordList = db.wordDao().getAll();
        Log.d(DatabaseInitializer.TAG, "Rows Count:" + wordList.size());
    }

    private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {

        private final AppDatabase mDb;

        private JSONArray mWordBankAry;

        PopulateDbAsync(AppDatabase db, JSONArray wordBankAry) {
            mDb = db;
            mWordBankAry = wordBankAry;
        }

        @Override
        protected Void doInBackground(final Void... params) {
            populateWordBank(mDb, mWordBankAry);
            return null;
        }
    }
}

@Entity(tableName = "words")
public class Word {
    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "word_name")
    private String wordName;

    @ColumnInfo(name = "word_definition")
    private String wordDefinition;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getWordName() {
        return wordName;
    }

    public void setWordName(String wordName) {
        this.wordName = wordName;
    }

    public String getWordDefinition() {
        return wordDefinition;
    }

    public void setWordDefinition(String wordDefinition) {
        this.wordDefinition = wordDefinition;
    }
}

1 个答案:

答案 0 :(得分:2)

  

推荐的解决方法是什么?

将其替换为预先打包的数据库。 SQLiteAssetHelper可以与Room一起使用,虽然不像我想的那样干净。有关该技术的演示,请参阅this sample app

  

也许我的代码效率低下,加载Room DB的速度更快?

现在,您正在为每个单词执行一次数据库事务。那将是缓慢的。相反,使用以insert()@Insert作为参数的List<Word>方法进行一次Word[]调用。这应该自动将这些插入的所有包装到单个事务中。一项大型交易将比N次交易更有效率。