Search code examples
javaandroidjsonandroid-ionion-koush

Using network library to pull down JSON


I don't work with JSON often, but I was having a bit of trouble just doing it in Android with no other libraries. I stumbeled upon Ion by Koush and I'd like to use it to retrieve weather data for London. The JSON api I will be using is from OpenWeather here. As far as I can tell the JSON is valid, so I am now stuck on the Android side of things. My end goal is to have an object/String that reports londons Main > temp. This is my Android code, but I am unsure of what to do next. Any ideas?

private void getTemperature() {
Log.d(TAG, "2");
final JsonObject json = new JsonObject();
Ion.with(this, "http://api.openweathermap.org/data/2.5/weather?q=London,uk")
.asJsonObject().setCallback(new FutureCallback<JsonObject>() {
    @Override
    public void onCompleted(Exception e, JsonObject result) {
    // do stuff with the result or error
    Log.d("TAG", "Complete");
    //json = result;
    }
    });
}

My code gets to the "Complete" log statement, but now I'm trying to set result to my json Object I created, so I un-comment //json = result, but I get an error in Eclipse. Any help? I would like this method to simply output the Main -> Temp which (as of right now) is 284.51.


Solution

  • Typical ion usage is aynchronous, but it has synchronous support. Instead of using setCallback (async), use get() (sync) to get it back synchronously. This will block your current Thread though.

    final JsonObject json = Ion.with(this, "http://api.openweathermap.org/data/2.5/weather?q=London,uk")
    .asJsonObject().
    .get();