joshcawthorne
joshcawthorne

Reputation: 48

Pulling JSON data from URL in Android 2017

Before I get started, could I just point out I've spent the last 5 hours going in circles here. I've tried what seems like every StackOverflow method out there to pull what seems like a simple int from an API. This seems like it should be way easier, but isn't.

What I'm trying to achieve is pull the JSON info from this URL:

http://api.apixu.com/v1/current.json?key=ENTERKEYHERE&q=leeds

And then gather the category "temp_c", which should be something along the lines of "7.0". Below is an example of how a call looks:

{
  "location": {
    "name": "Leeds",
    "region": "West Yorkshire",
    "country": "United Kingdom",
    "lat": 53.81,
    "lon": -1.54,
    "tz_id": "Europe/London",
    "localtime_epoch": 1509670055,
    "localtime": "2017-11-03 0:47"
  },
  "current": {
    "last_updated_epoch": 1509669008,
    "last_updated": "2017-11-03 00:30",
    "temp_c": 7,
    "temp_f": 44.6,
    "is_day": 0,
    "condition": {
      "text": "Partly cloudy",
      "icon": "//cdn.apixu.com/weather/64x64/night/116.png",
      "code": 1003
    },
    "wind_mph": 4.3,
    "wind_kph": 6.8,
    "wind_degree": 150,
    "wind_dir": "SSE",
    "pressure_mb": 1015,
    "pressure_in": 30.4,
    "precip_mm": 0,
    "precip_in": 0,
    "humidity": 93,
    "cloud": 75,
    "feelslike_c": 5.8,
    "feelslike_f": 42.4,
    "vis_km": 10,
    "vis_miles": 6
  }
}

I've successfully gotten the data to pull into an app during random points in the night, however have been unable to pull the specific piece of data at all. Currently, my app won't pull it at all and I'm not sure what I did before.

I'm truly sorry if this is a question deemed "duplicate", but I can assure you that for someone trying to learn the language, none of the answers fully explain how to do this using the newer API's (Some of the answers seem to no longer work in API 23+)

I'm not looking for a detailed app with loads of methods, just a simple way of pulling the JSON data and selecting a specific category. I'd be extremely grateful if you could explain how to do this as I plan on adapting the code in the future for other sources. Thank you!

Upvotes: 1

Views: 177

Answers (2)

Xenolion
Xenolion

Reputation: 12717

First step take your whole Json as a String lets say String json_string and here is what you have to do (Read the comments in code for further information):

String json_string="your json string here as a normal String json object";

    try {
        JSONObject jsonObjectRoot=new JSONObject(json_string);
        JSONObject locationObject=jsonObjectRoot.getJSONObject("location");

        String name=locationObject.getString("name"); //This will return leeds
        String region=locationObject.getString("region"); //This will return West YorkShire!
    }catch (JSONException json_except){
        //You have an exception so check if your items really exist with those names!
        json_except.printStackTrace();
    }

So from the above example using your own data you need to know is:

  • All Json code should be in a try block and catch Json exception.
  • To get a json object from a string just a constructor itself like new JSONObject(string);
  • To get any inner json object (json object within json object) we use the method outer_object.getJSONObject("string_name_of_inner_object");and continue deeper until you get your object.
  • To get a string within an object we use String string=json_object.getString("the_string_name_as_it_appears_in_the_object");
  • To get a Json Array inside an object you use JSONArray jsonArray=your_json_object.getJSONArray("array_name_as_it_appears_in_json");

I hope this will help you!

Upvotes: 0

Tomhawk
Tomhawk

Reputation: 188

You should use an AsyncTask or AsyncTaskLoader so the UI-Thread doesn't lag during loading. Search for this term or use the UI thread, but then it will lag during the load. Eitherways, call this function, with url being your url:

public static String getResponse(URL url) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = urlConnection.getInputStream();
        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");
        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        urlConnection.disconnect();
    }

The url can be gotten by calling

url = new URL(yourAddressAsAString)

The upper functoin should return a string. Convert it into a JSON Object

            JSONObject obj = null;
            try {
                obj = new JSONObject(yourString);
            } catch (Throwable t) {                }

Then call

String tempc = String.valueOf(obj.getJSONObject("current").getJSONObject("temp_c"))

To get the Object in question. Good luck!

Upvotes: 1

Related Questions