Friday, January 07, 2011

Android: Using csv file as config/resource

While working on Android projects, I constantly need a way to save external configurations or simply some String value resource. For iPhone we have the "plist" file but this is not so clear cut for Android.

The best simplest way is to just use a plain CSV file to store these resources. This is easy to do in Android without using any 3rd party library.

Lets start by putting the csv file in "/res/raw". So I have a csv file named as "ref_codes.csv". Inside the file I have a simple "name,code,date" format.

Next is, create a method to load the CSV content.

private List loadCSV() throws IOException {
     InputStream inputStream = getResources().openRawResource(R.raw.ref_codes);
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while ((line = reader.readLine()) != null) {
       //process the line, stuff to List
       String[] values = line.split(",");

** Do note that CSV usage as shown here has many shortcomings and it's recommended that if you config need is complex then I suggest you look into JSON or XML. (Thanks for the feedback from Mark Murphy)


Anonymous said...

"The best way is to just use a simple CSV file to store these resources."

This is your opinion. I, for one, do not agree with it. I would recommend JSON or XML over CSV any day of the week and twice on Sundays. Or, for strings, use string or string-array resources, rather than a raw resource.

"This is easy to do in Android without using any 3rd party library."

Parsing JSON or XML, or using string/string-array resources, is built into Android as well.

"Next is, create a method to load the CSV content."

Bear in mind that your implementation will not support values with commas in them. There is a reason why there are CSV parsing libraries for Java.

Seymour Cakes said...

Hi Mark,

Thanks for the feedback.

I am aware of the shortcomings of the use of CSV or for that matter a very very simplistic CSV loading. But for a very quick and dirty way to load up config data (and any additional JAR file) the way I describe is the "best".

But "best" is probably a misleading and potentially harmful word to use in this context. For that I shall update my blog post. :-)


Anonymous said...

thanks for that! it gave me a quick and effective help!!!

regards from austria

Ton Snoei said...

You should close your reader and inputstream. Don't forget that.