Saving Data from CSV to Realm

我是研究僧i 提交于 2019-12-06 09:47:13

Use 1 transaction instead of 146800 transactions. Also consider using 1 instance to save your Realm object, instead of creating 146800 objects.

    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            String csvFile = "longevity.csv";
            BufferedReader br = null;
            String line = "";
            String cvsSplitBy = ",";
            try {
                br = new BufferedReader(new InputStreamReader(getAssets().open(csvFile)));
                Word user = new Word();
                while((line = br.readLine()) != null) {
                    // use comma as separator
                    final String[] oneWord = line.split(cvsSplitBy);
                    user.setWord(oneWord[1]);
                    user.setMeaning(oneWord[2]);
                    user.setSynonyms(oneWord[3]);
                    bgRealm.insert(user);
                }
            } catch(Throwable e) {
                e.printStackTrace();
                throw e;
            } finally {
                if(br != null) {
                    try {
                        br.close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            Log.v("TAGGED", "SAVED");
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            Log.v("TAGGED", "FAILED");
        }
    });

EDIT: You should consider using a CSV parser library, because String.split() is memory-intensive.

Instead of

while ((line = br.readLine()) != null) {

Consider this

final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
for (final CSVRecord record : parser) {
    ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!