Monday, July 29, 2013

Android Json file read instead of property file read


While I am building an Android application. I wanted to read a property file and wanted to act my app depends on the property file configuration. But, property file can't handle array unless I add dependency Apache Common Configuration. As I am building an mobile application, it should be compact. for the reason, I just used Android JSONObject to resolve this.

Create "country.json" file and locate it Android device "/" directory

{
    "country": [
        {
            "name": "germany",
            "code": "DE",
            "continent": "Europe",
            "eat": "sausage"
        },    
        {
            "name": "france",
            "code": "FR",
            "continent": "Europe",
            "eat": "croissant"
        },
        {
            "name": "korea",
            "code": "KR",
            "continent": "ASIA",
            "eat": "rice"
        },
        {
            "name": "japan",
            "code": "JP",
            "continent": "ASIA",
            "eat": "fish"
        }
    ]
}


Create 2 method and use "getCountryList()" on your need.
private List<Country> getCountryList() throws Exception {

 File dirSDCard = Environment.getExternalStorageDirectory();
 File yourFile = new File(dirSDCard, "country.json");
 InputStream jsonStream = new FileInputStream(yourFile);
 JSONObject jsonObject = new JSONObject(InputStreamToString(jsonStream));
 JSONArray jsonArray = jsonObject.getJSONArray("country");
 List<Country> countryList = new ArrayList<Country>();

 for (int i = 0; i < jsonArray.length(); i++) {

  JSONObject jsonCountry = jsonArray.getJSONObject(i);
  Country country = new Country();
  country.setName(jsoncountry.getString("name"));
  country.setCode(jsoncountry.getString("code"));
  country.setContinent(jsoncountry.getString("continent"));
  country.setEat(jsoncountry.getString("eat"));

  countryList.add(country);
 }

 return countryList;
}

private String InputStreamToString(InputStream is) {

 BufferedReader r = new BufferedReader(new InputStreamReader(is));
 StringBuilder total = new StringBuilder();
 String line;
 try {
  while ((line = r.readLine()) != null) {
   total.append(line);
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 return total.toString();

}