Populate Android Database From CSV file?

前端 未结 2 908
失恋的感觉
失恋的感觉 2020-11-30 19:48

Is it possible to take a csv file stored in the res/raw resource directory and use it to populate a table in the sqlite3 database?

My thought was that, if there was

2条回答
  •  既然无缘
    2020-11-30 20:07

    I spent a lot of time looking for a simple solution and came up with this little bit of code myself. For future people looking for this like I was you can use this:

    BufferedReader in = new BufferedReader(your csv file source here);
    String reader = "";
    while ((reader = in.readLine()) != null){
        String[] RowData = reader.split(",");
        date = RowData[0];
        value = RowData[1];
        ContentValues values = new ContentValues();
        values.put(CsvProvider.DATE, date);
        values.put(CsvProvider.VALUE, value);
        getContentResolver().insert(CsvProvider.CONTENT_URI, values);
    }
    in.close();
    

    My CSV file has no titles and only has 2 columns but more than two columns should not be a problem. Just remember to specify what is splitting your columns and for each column add another RowData[#](you have to start with 0). You want to make sure whatever you are going to do with each line is done before you call in.close(). I am using a content provider but you can really do whatever you want with the data like append it to a String[] or whatever else.

    While I am using an input stream you can point the BufferedReader to wherever you want. As long as the BufferedReader can read it then it will work.

提交回复
热议问题