如何从CSV文件读取数据并将数据插入Room数据库?

时间:2018-07-15 09:37:32

标签: android database csv android-room

 InputStream is = getResources().openRawResource(R.raw.babynames);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(is, Charset.forName("UTF-8"))
    );
    String line = "";

    try {
        reader.readLine();

        while ((line = reader.readLine()) != null) {
            Log.d("MyActivity", "Line: " + line);

            String[] tokens = line.split(",");

            BabyName name = new BabyName();
            name.setGender(tokens[1]);
            name.setMeaning(tokens[2]);
            name.setName(tokens[3]);
            name.setOrigin(tokens[4]);


            babyNames.add(name);
            Log.d(TAG, "Just created: " + name);

        }
    } catch (IOException e) {
        Log.wtf("MyActivity", "Error reading data file on line" + line, e);
        e.printStackTrace();
    }

我正在尝试此操作,但应用程序崩溃了,并且出现了数组索引错误,并且在日志中我正在获取数据

1 个答案:

答案 0 :(得分:1)

BabyName name = new BabyName();
name.setGender(tokens[1]);
name.setMeaning(tokens[2]);
name.setName(tokens[3]);
name.setOrigin(tokens[4]);

索引不应该从0开始

name.setGender(tokens[0]);