1

This project I've done with image in my drawable but now I want to get image url from JSON by using Asynctask and display it. and I make php that provide a json string like below.

I want to get path of image(url) by using AsyncTask from JSON. I want to use data from json instead of public mThumbId = {...};

 {"count":"28","data":
    [{"id":"1",
        "first_name":"man",
        "last_name":"woman",
        "username":"man",
        "password":"4f70432e636970de9929bcc6f1b72412",
        "email":"man@gmail.com",
        "url":"http://vulcan.wr.usgs.gov/Imgs/Jpg/MSH/Images/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg"},
    {"id":"2",
            "first_name":"first",
            "last_name":"Last Name",
            "username":"user",
            "password":"1a1dc91c907325c69271ddf0c944bc72",
            "email":"first@gmail.com",
            "url":"http://www.danheller.com/images/California/Marin/Scenics/bird-view-big.jpg"},
    {"id":"3",
            "first_name":"first",
            "last_name":"Last Name",
            "username":"user",
            "password":"1a1dc91c907325c69271ddf0c944bc72",
            "email":"0",
            "url":"http://www.hermes.net.au/bodhi/images/view/large/view_03.jpg"}]}

AndroidGridLayoutActivity

GridView gridView = (GridView) findViewById(R.id.grid_view);        
    gridView.setAdapter(new ImageAdapter(this));

    gridView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
            i.putExtra("id", position);
            startActivity(i);
        }
    });

ImageAdapter

public class ImageAdapter extends BaseAdapter {
private Context mContext;

// Keep all Images in array
public Integer[] mThumbIds = {
        R.drawable.pic_1, R.drawable.pic_2,
        R.drawable.pic_3, R.drawable.pic_4,
        R.drawable.pic_5, R.drawable.pic_6,
        R.drawable.pic_7, R.drawable.pic_8,
        R.drawable.pic_9, R.drawable.pic_10,
        R.drawable.pic_11, R.drawable.pic_12,
        R.drawable.pic_13, R.drawable.pic_14,
        R.drawable.pic_15
};

// Constructor
public ImageAdapter(Context c){
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

public Object getItem(int position) {
    return mThumbIds[position];
}

public long getItemId(int position) {
    return 0;
}

public View getView(int position, View convertView, ViewGroup parent) {         
    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(mThumbIds[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
    return imageView;
}

}

FullImageActivity

Intent i = getIntent();
    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);

    ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
    imageView.setImageResource(imageAdapter.mThumbIds[position]);
kongkea
  • 9,788
  • 12
  • 39
  • 49
  • I don't want to use `public mThumbId = {...};`. I want to use url from json. – kongkea Oct 08 '12 at 09:48
  • yes? and so, what have you tried? – njzk2 Oct 08 '12 at 10:00
  • http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/ this link is tutorial gridview get image from drawable but i want to get image by json above but in version 4.0.3 didn't allow get image from internet in the main thread, it allow in the background. so we must to use AsyncTask and I don't how to use AsyncTask. I want to use method that get path of image in json like `public Integer[] mThumbId = {...};` – kongkea Oct 08 '12 at 10:20
  • http://stackoverflow.com/questions/12739824/image-viewer-get-image-from-url-that-provide-image-path-as-json-string – kongkea Oct 08 '12 at 10:25
  • you don't know how to use asynktask => learn how to use asynctask http://stackoverflow.com/questions/7729133/using-asynctask-to-load-images-in-listview – njzk2 Oct 08 '12 at 11:31
  • http://androidadvance.weebly.com/display-image-from-url.html – Roadies Feb 04 '13 at 06:46

2 Answers2

0

I think that this simple link will totally answer your question:

https://github.com/novoda/ImageLoader

And my own implementation:

https://github.com/iRail/BeTrains-for-Android/blob/master/src/tof/cv/mpp/adapter/TweetItemAdapter.java

EDIT

What you really need to do:

1) Parse JSON: there are thousands of tutorials on the web, or use the awesome GSON library.

2) Once JSON is parsed, you will get an array of objects.

3) In your Adapter, you will maybe need to extend ArrayAdapter.

4) in the getView() method, analyse my 2 above links and use something like:

imageLoader.DisplayImage(tweet.profile_image_url, activity, holder.image);

Waza_Be
  • 39,407
  • 49
  • 186
  • 260
  • You asked from a way to create an AsyncTask to display images from a JSON feed in a gridView. I answered you how to create an AsyncTask to display images from a JSON feed in a ListView. Maybe you could improve your question, so I can understand what you want? – Waza_Be Oct 08 '12 at 10:23
  • http://stackoverflow.com/questions/12739824/image-viewer-get-image-from-url-that-provide-image-path-as-json-string – kongkea Oct 08 '12 at 10:24
  • On the other link, someone asked you exactly the same way than me ;-) – Waza_Be Oct 08 '12 at 10:41
  • BTW? I added 4 steps in my answer, please tell me where you have an issue – Waza_Be Oct 08 '12 at 10:44
  • you can answer the link above and i will try too – kongkea Oct 08 '12 at 10:47
  • http://www.androidhive.info/2012/02/android-gridview-layout-tutorial/ in the tutorial have `public Integer[] mThumbId = {...}` for example you don't want to use `public Integer[] mThumbId = {...}`, u want to use path of image in json above. could you correct this tutorial – kongkea Oct 08 '12 at 10:58
  • Look at my link!!! imageLoader.DisplayImage(tweet.profile_image_url, activity, holder.image); – Waza_Be Oct 08 '12 at 11:02
  • Modified ImageLoader is here: https://github.com/iRail/BeTrains-for-Android/blob/master/src/tof/cv/mpp/view/ImageLoader.java – Waza_Be Oct 08 '12 at 11:04
0

You have to first extract the urls from json in a array and then use below code to load image as bitmap dynamically using Async Task.

Bitmap bm[]=new Bitmap[3];
ImageAdapter img;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bm[0]=null;
        bm[1]=null;
        bm[2]=null;


 InputStream is= getDataFromServer();
      String asd=getResponseFromStream(is);
      try {
        JSONObject jsn=new JSONObject(asd);
        JSONArray jd=jsn.getJSONArray("data");
        for(int i=0;i<jd.length();i++)
        {
            JSONObject j_object=jd.getJSONObject(i);
            String url=j_object.getString("url");
            urls.add(url);
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


       img=new ImageAdapter(this);
        GridView gridView = (GridView) findViewById(R.id.grid_view);        
        gridView.setAdapter(img);
        new  ImageDownloader().execute();
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
                i.putExtra("id", position);
                startActivity(i);
            }
        });

    }
    ProgressDialog prg;
    private class ImageDownloader extends AsyncTask<Integer, Integer, String>
    {
        @Override
        public void onPreExecute()
        {
            prg=ProgressDialog.show(LazyLoadActivity.this, null, 
                    "Loading...");
        }

        protected void onPostExecute(String result)
        {
            prg.hide();




        }
          protected void onProgressUpdate(Integer... progress) {
              img.notifyDataSetChanged();
             }
        protected String doInBackground(Integer... a)
        {
            for(int i=0;i<3;i++)
            {
                bm[i]=downloadBitmap(urls[i]);
                this.publishProgress(i);
            }
            return "";
        }
    }
    public Integer[] mThumbIds = {
            R.drawable.ic_launcher, R.drawable.ic_launcher,
            R.drawable.ic_launcher
    };

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        // Keep all Images in array

        // Constructor
        public ImageAdapter(Context c){
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return mThumbIds[position];
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {         
            ImageView imageView = new ImageView(mContext);
            if(bm[position]==null)
            imageView.setImageResource(mThumbIds[position]);
            else
                imageView.setImageBitmap(bm[position]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
            return imageView;
        }

        }
Bitmap downloadBitmap(String url) {

        final HttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) { 
                Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); 
                return null;
            }

            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent(); 
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();  
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            // Could provide a more explicit error message for IOException or IllegalStateException
            getRequest.abort();
            Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
        } finally {
            if (client != null) {
                //client.
            }
        }
        return null;
    }
Maneesh
  • 6,098
  • 5
  • 36
  • 55
  • `String urls[] = {...}` it's static. I don't want to type it again and again. I want to query path image from json above. also thanks – kongkea Oct 08 '12 at 10:30
  • http://stackoverflow.com/questions/12739824/image-viewer-get-image-from-url-that-provide-image-path-as-json-string – kongkea Oct 08 '12 at 10:31
  • Done some changes in answer. Please check – Maneesh Oct 08 '12 at 11:13