-2

I'm trying to parse a JSON result fetched from a URL in my Android app. I have tried a few examples on the Internet, but can't get it to work. My url is: http://a.nextput.com/api/single-offer/23/89533a6f4248873b08ce52ce680f29e7/a?aff_id={aff_id}.
The JSON data looks like this after hitting the url:

{"success":true,
 "offer":
 {  
  "packageName":"com.myntra.android",
  "campKey":"284",
  "app_name":" Myntra",
  "image_url":"https:\/\/media.go2speed.org\/brand\/files\/wadogo\/142\/thumbnails_100\/unnamed-3.png",
  "desc1":"No Incent\r\nNo Free-Recharge apps traffic\r\nNO SMS\r\nNo Email\r\nNo Adult traffic\r\nNo Bot Traffic\r\nKPI - purchase% >10% of Total Installs. If not met, CPI payout will be pro-rata.\r\nNote: No social media traffic allowed. No traffic from Datalead.\r\n\r\nThe caps provided are network wide. \r\nPlease ask AM for individual Caps by Mail and Skype.\r\nexpiry date: TBA\r\nThe offer will stop converting once we hit the daily\/monthly cap\r\nCPI per install\r\nOnly use the creatives provided by us.\r\n\r\nPayout Slab:\r\n0-10 INR - Nill\r\n10-50 INR - $0.40\r\n50-100 INR - $0.62\r\n100-125 INR - $0.70\r\n125+ - $0.90",
  "desc2":null,
  "rdata":"[]",
  "cats":"0",
  "banner_url":"https:\/\/www.google.co.in\/logos\/doodles\/2016\/dmitri-mendeleevs-182nd-birthday-5692309846884352-hp.jpg",
  "click_url":"http:\/\/a.nextput.com\/apps\/install-begin\/284\/23\/37693cfc748049e45d87b8c7d8b9aacd\/89533a6f4248873b08ce52ce680f29e7\/u?aff_id={aff_id}",
  "country":"IN",
  "payout":0.12 }}

I have to parse this JSON and get the "image_url" response and open the image_url by using ImageLoader.

What's the simplest way to parse this JSON data and get the image_url and open it using ImageLoader? Please help!!!

my code for service hit and get the image_url:

public class GallecticaView extends ImageView {

public GallecticaView(Context context){
    super(context);
}

public GallecticaView(Context ctx, AttributeSet set) {
    super(ctx, set);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr) {
    super(ctx, set, defStyleAttr);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr, int defStyleRes) {
    super(ctx, set, defStyleAttr, defStyleRes);
}

private static String PREF_NAME = "gallectica_pref_adstuck";
private static SharedPreferences prefs;

private void initIV(final Context ctx) {
    new AsyncTask<Void, Void, Boolean>() {
        String developer_public_key;

        protected void onPreExecute() {
            super.onPreExecute();
            prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putString("android_id", Settings.Secure.getString(ctx.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID)).commit();

            developer_public_key = prefs.getString("developer_public_key", "23/89533a6f4248873b08ce52ce680f29e7");
        }

        protected Boolean doInBackground(Void... arg0) {
            String json = "";
            HttpURLConnection connection = null;
            InputStream is = null;

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("aff_id", prefs.getString("android_id", "")));
            params.add(new BasicNameValuePair("developer_public_key", developer_public_key));


            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://a.nextput.com/api/single-offer/" + developer_public_key + "/a");//YOUR URL  ?aff_id

                HttpResponse httpResponse = httpClient.execute(httpPost);
                json = EntityUtils.toString(httpResponse.getEntity());

                JSONObject jObj = new JSONObject(json);
                boolean isSuccess = jObj.getBoolean("success");
                System.out.println("success : " + isSuccess);

                /* JSONObject jsonObject = new JSONObject(json);
                   boolean state = jsonObject.getBoolean("success");*/

                ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)
                        .threadPriority(Thread.NORM_PRIORITY - 2)
                        .denyCacheImageMultipleSizesInMemory()
                        .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                        .diskCacheSize(50 * 1024 * 1024) // 50 Mb
                        .tasksProcessingOrder(QueueProcessingType.LIFO)
                                //.writeDebugLogs() // Remove for release app
                        .build();
                // Initialize ImageLoader with configuration.
                ImageLoader.getInstance().init(config);

                return isSuccess;
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

          //  ImageLoader.getInstance().displayImage(imageUrl);
        }
    }.execute();

}
}

How to get image_url response in it and load it in imageview using ImageLoader??

himanshu.tiwari
  • 101
  • 1
  • 12

6 Answers6

1

Use Gson library which automatically parse your json response, provided you need to have proper Model class which matches the response. Then using ImageLoader download the image from the url.

0

Assuming that the JSON response you get as result

ImageLoader imageLoader = ImageLoader.getInstance();
if(result.getBoolean("success")){
    JSONObject offer = result.getJSONObject("offer");
    String imageUrl = offer.getString("image_url");
    imageLoader.displayImage(imageUri, yourImageView);
}

Where yourImageView is the image view where you want to set the image

P.S the above way of setting the image is through universal image loader library as in https://github.com/nostra13/Android-Universal-Image-Loader

Shashank Udupa
  • 2,173
  • 1
  • 19
  • 26
0

JSONObject response = contains the response.

JSONObject offerJson = reponse.getJSONObject("offer");
String imageUrl = offerJson.getString("image_url");

now you have the image url and you can use any imageloader to display the image from this url into any ImageView.

You can use Glide, Picasso or UniversalImageLoader. These 3 are famous ones.

Nitesh Kumar
  • 5,370
  • 5
  • 37
  • 54
0

Steps:

Step 1 : First get the image url that you want to show using JSON Parsing.

Use the JsonParser class mentioned below:

public class JSONParser {

InputStream is = null;
 JSONObject jObj = null;
 String json = "";

 // constructor
 public JSONParser() {
 }

 public String getJSONFromUrl(String url) {

  // Making HTTP request
  try {

   DefaultHttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(url);
   HttpResponse httpResponse = httpClient.execute(httpPost);
   Log.e("response", "" + httpResponse);

   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, "iso-8859-1"), 8);
   StringBuilder sb = new StringBuilder();
   String line = null;
   while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
   }
   json = sb.toString();
   is.close();
  } catch (Exception e) {
   Log.e("Buffer Error", "Error converting result " + e.toString());
  }
  return json;
 }

}

Use the code below to get the imageUrl from the Json Response:

JSONObject jobject = new JSONObject("Your Json Response"); JSONObject jo = jobject.getJSONObject("offer");

String imageUrl = jo.getString("image_url");

Step 2: Now this image url can be loaded on to the Imageview using the Picasso Library. That is one of the best way to load the image from url.

Get the Picasso jar file from here

http://square.github.io/picasso/

Step 3: Use the code to load the image Url using Picasso

//Initialize ImageView ImageView imageView = (ImageView) findViewById(R.id.imageView);

//Loading image from below url into imageView

Picasso.with(this) .load("YOUR IMAGE URL HERE") .into(imageView);

New Coder
  • 873
  • 8
  • 14
  • I have written the code for this. Please suggest me the changes in that and also to get the image_url in that class also. Please – himanshu.tiwari Feb 17 '16 at 10:43
0

after your request this is the changes in your class : Please check and let me know.

 public class GallecticaView extends ImageView {

public GallecticaView(Context context){
    super(context);
}

public GallecticaView(Context ctx, AttributeSet set) {
    super(ctx, set);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr) {
    super(ctx, set, defStyleAttr);
}

public GallecticaView(Context ctx, AttributeSet set, int defStyleAttr, int defStyleRes) {
    super(ctx, set, defStyleAttr, defStyleRes);
}

private static String PREF_NAME = "gallectica_pref_adstuck";
private static SharedPreferences prefs;

private void initIV(final Context ctx) {
    new AsyncTask<Void, Void, Boolean>() {
        String developer_public_key;


        ///*** CODE ADDED BY NEW CODER ***/////
        String imageUrl; 

        protected void onPreExecute() {
            super.onPreExecute();
            prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putString("android_id", Settings.Secure.getString(ctx.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID)).commit();

            developer_public_key = prefs.getString("developer_public_key", "23/89533a6f4248873b08ce52ce680f29e7");
        }

        protected Boolean doInBackground(Void... arg0) {
            String json = "";
            HttpURLConnection connection = null;
            InputStream is = null;

            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("aff_id", prefs.getString("android_id", "")));
            params.add(new BasicNameValuePair("developer_public_key", developer_public_key));


            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://a.nextput.com/api/single-offer/" + developer_public_key + "/a");//YOUR URL  ?aff_id

                HttpResponse httpResponse = httpClient.execute(httpPost);
                json = EntityUtils.toString(httpResponse.getEntity());

                JSONObject jObj = new JSONObject(json);
                boolean isSuccess = jObj.getBoolean("success");
                System.out.println("success : " + isSuccess);

                /* JSONObject jsonObject = new JSONObject(json);
                   boolean state = jsonObject.getBoolean("success");*/


                   //// *** CODE ADDED BY NEW CODER *** ////
                   JSONObject jObject = jObj.getJSONObject("offer");
                   imageUrl =   jObject.getString("image_url");



                return isSuccess;
            } catch (Exception e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

            return false;
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if(isSuccess)
            {
                Picasso.with(this).load(imageUrl).into("Your ImageVIew");
            }

          //  ImageLoader.getInstance().displayImage(imageUrl);
        }
    }.execute();

}
}
New Coder
  • 873
  • 8
  • 14
-1

you can simply use Gson library. just add dependency in build.gradle and create a pojo file which constant all json variable and its getter and setter.

compile 'com.google.code.gson:gson:2.2.4'

List list = new ArrayList(); JSONObject jsonRootObject = new JSONObject(Stringjson);

jsonResult = jsonRootObject.getString("success");

if(jsonResult.equalsIgnoreCase("true")){

JsonObject offerObj = jsonRootObject.getJSONObject("offer");

list = new Gson().fromJson(jsonArray.toString(), new TypeToken>(){}.getType());

}

Now all data in your list..enjoy

  • The question isn't just about parsing the JSON, it's also about downloading and displaying images. – mjp66 Feb 17 '16 at 10:02