You are currently viewing Differentiating between received file formats for Event Apps

Differentiating between received file formats for Event Apps

Sometimes we need to operate on files of different formats in the same app itself for example Giggity app parses the file in iCal, xCal, pentabarf and now in Open Event JSON format.

It could be problematic as every format needs different type of manipulation to read and get the relevant data from it, for example the JSON format is based on objects and arrays in it from which we can get the data by referencing titles of the data while pentabarf XML identifies the elements with tags. Also it is not evident from the link itself which format is being received. So to see which type of file is received instead of analyzing the entire file we look for the few initials of the syntax from which it becomes evident.

I recently used this method to differentiate between the JSON and iCal format to display sessions of an event in the Giraffe app in Open Event JSON format which is also being used in Giggity.

Let’s have a look on how to actually implement this. It is simple after you get the data from the url. Instead of iterating for the entire data we read the initial data only to see what kind of file we have received.

BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String line = r.readLine();

if(line.contains("BEGIN:VCALENDAR")) {
 SharedPreferences.Editor edit = prefs.edit();
 edit.putString("type", "ical");
 edit.commit();
 Log.e("Response type","ical");
} 
else if(line.contains("{")) {
 SharedPreferences.Editor edit = prefs.edit();
 edit.putString("type", "json");
 edit.commit();
 Log.e("Response type","json");
}

We saved the type of response received in the shared preferences so we retrieve it later from anywhere in the app to see what kind of data we have received instead of passing it in between functions or activities.

See this to check as you download the data from the URL asynchronously, so you don’t need to do it later or manipulations needs to be done asynchronously too.

So when you are checking in asynchronously using AsyncTask class get shared preferences in onPreExecute() and update it in doInBackground() as we download the data and check.

The other advantage of this method is that we can close the thread or return to the main activity if the file format found is not readable or not of desired format.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.