SQLite Room快速插入JSON数组

问题描述 投票:1回答:1

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

基于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;
    }
}
android json sqlite android-room
1个回答
2
投票

推荐的解决方法是什么?

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.