Vinnig
Vinnig

Reputation: 7

How to fetch data from json in android which does not have array name?

I want to get an url from this link:

 "http://graph.facebook.com/10202459285618351/picture?type=large&redirect=false"

it gives result:

{ "data": { "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/t1.0- 1/s200x200/10342822_10202261537234765_3194866551853134720_n.jpg", "is_silhouette": false } }

I tried,

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(AccountActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        String jsonStr = sh.makeServiceCall(fbPicURL, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                fbRealURL = jsonObj.getString("url");


                    // Phone node is JSON Object
                    Toast.makeText(AccountActivity.this, fbRealURL,
                            Toast.LENGTH_LONG).show();
                    // tmp hashmap for single contact

                }
             catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        Toast.makeText(AccountActivity.this, fbRealURL,
                Toast.LENGTH_LONG).show();
    }

}

But returning null and its not crashing..

Upvotes: 0

Views: 62

Answers (1)

Milan Maharjan
Milan Maharjan

Reputation: 4236

You have to get the data object first like this:

     try {
            JSONObject jsonObj = new JSONObject(jsonStr);


            fbRealURLObj = jsonObj.getJSONObject("data");

            fbRealURL = fbRealURLObj.getString("url");

                // Phone node is JSON Object
                Toast.makeText(AccountActivity.this, fbRealURL,
                        Toast.LENGTH_LONG).show();
                // tmp hashmap for single contact

            }

Upvotes: 1

Related Questions