Populate Android Database From CSV file? Populate Android Database From CSV file? sqlite sqlite

Populate Android Database From CSV file?


If you want to package static data with your application, I recommend preparing the database at development time (using any UI or csv-import command you like) and shipping the sqlite file inside the assets folder. You can then simply copy the entire sqlite file onto the device when your application is first run. These posts take you through this idea which is most likely the fastest way to setup a database (file copy speed).

If, for some reason you do need to insert a lot of data at run time, I recommend you look at ways to bulk insert using transactions to speed it up.


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.