Skip to content

Instantly share code, notes, and snippets.

@MohammadSamandari
Created April 1, 2019 09:18
Show Gist options
  • Save MohammadSamandari/122706c4f73a4f98fb7ad35ef46b8886 to your computer and use it in GitHub Desktop.
Save MohammadSamandari/122706c4f73a4f98fb7ad35ef46b8886 to your computer and use it in GitHub Desktop.
Learning: Working With JSON - Extracting Info Out Of It.
try {
//Converting result To Json and extracting Parts of it.
JSONObject myJSON = new JSONObject(weatherInfo);
// Checking if the City is found:
int resultCod = Integer.parseInt(myJSON.getString("cod"));
if (resultCod == 200) {
Log.i("Lord", "resultCod Is 200 - Continuing . . .");
//Getting The Information We Need.
String weatherExtracted = myJSON.getString("weather");
String sysExtracted = myJSON.getString("sys");
String cityName = myJSON.getString("name");
// Getting Weather Information out of the Json File.
JSONArray weatherJsonArray = new JSONArray(weatherExtracted);
JSONObject weatherMainJson = weatherJsonArray.getJSONObject(0);
String weatherMain = weatherMainJson.getString("main");
String weatherDescription = weatherMainJson.getString("description");
// Getting Country Name out of Json File.
JSONObject sysJson = new JSONObject(sysExtracted);
String countryName = sysJson.getString("country");
//Creating a Map object to pass to UI
Map weatherInfoMap = new HashMap();
weatherInfoMap.put("countryName", countryName);
weatherInfoMap.put("cityName", cityName);
weatherInfoMap.put("weatherMain", weatherMain);
weatherInfoMap.put("weatherDescription", weatherDescription);
Log.i("Lord", "Json Function Ended - Updating ui Function");
//Update UI
updateUi(weatherInfoMap);
} else if (resultCod != 200) {
Log.i("Lord", "resultCod Is 404 - Continuing . . .");
String message = myJSON.getString("message");
updateUiWithError(message);
}
} catch (Exception e) {
e.printStackTrace();
Log.i("Lord", String.valueOf(e));
updateUiWithError("City Not Found - Please Try Again.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment