-1

I am having a doubt related to web-services and Json. Actually I have a URL http://api.icndb.com/jokes/random, which is related to some jokes website.

If you will click the above given URL you can able to see the json data. Now my problem is I am trying to do one application i.e, in my activity I have one button and text-view.

If we click the button it should fetch the joke from the website given above and it should display in text-view. Every time if i click the button it should display different joke.

Can you please help me how to fetch the data by using above given URL.

Onkar Nene
  • 1,359
  • 1
  • 17
  • 23
Jayasree
  • 21
  • 4

2 Answers2

-1

i put here code.you need to use with AsyncTask.

 public static  String getJSONFromUrl(String url) {

    // make HTTP request
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        Log.e("Log","Url1="+url);
        json = sb.toString();

    } catch (Exception e) {
        Log.e(TAG, "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e(TAG, "Error parsing data " + e.toString());
    }

    // return JSON String
    return json;
}

after fetching Result,parse it.

Vasant
  • 3,475
  • 3
  • 19
  • 33
-1

If your problem is how to retrieve the data, you should look at this solution: How to get JSON from URL in Javascript?

If you are calling the same url in the same session, it will cache the result.

You only shoud add a fake param to the url to force not to caché the request.

for example you can add getTime to the url.

var d = new Date();
var n = d.getTime();
var url = "http://api.icndb.com/jokes/random?n=" + n;

For example: http://api.icndb.com/jokes/random?n=1468578025752 http://api.icndb.com/jokes/random?n=819929720000

Community
  • 1
  • 1
Jordi Flores
  • 2,080
  • 10
  • 16