Like Sergey, I found that the included org.json.* library on Android is much easier to use than GSON .
For example, in your scenario, your JSON parsing code would look like this.
String jsonData = readUrl("http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo"); JSONObject weatherJSONObject = new JSONObject( jsonData ); try {
You would also benefit from AsyncTask or Thread . You never want to run lengthy operations on a user interface thread, because the user interface will seem unresponsive and sluggish.
The following is an example of how you can use AsyncTask to achieve your goal. Read more about it here.
private class FetchJSONDataTask extends AsyncTask<String, Void, JSONObject> {
And to complete your task, you must run this code in your activity.
FetchJSONDataTask task = new FetchJSONDataTask(); task.execute( new String[] { "http://api.geonames.org/weatherIcaoJSON?ICAO=LSZH&username=demo" } );
Note. This code has not been tested, but it should be a general idea.
source share