SomCollection
SomCollection

Reputation: 481

How can I convert response json string image into a displayable image

My final year project requires me to develop a mobile application which fetches a number of Json values from a server. This is my first experience in android development but sure learned something’s and enjoyed the experience.

I have managed to develop the following.

1-a json parser class which fetches the value.

2-a class which displays these values.

3-a database where I store the json response.

However I'm one step away from completing my project, I cannot display the response string image address as real images (shame on me). I need to do the following.

1- Parse the string path of the image and display the response as image.

I have spent most of my time trying to find the solution on the web, stack overflow. But no luck so far. I need to do something like this in order to display these images together with the text descriptions.

I have now reached the cross roads and my knowledge has been tested.Is what i'm trying to do here posible?.

Who can show me the way? ,to this outstanding platform.

Upvotes: 1

Views: 3540

Answers (2)

Chronos
Chronos

Reputation: 1962

you can try this ImageDownloader class from google. It´s works nice :) Is an AsynkTask that handle the download and set the bitmap to an ImageView.

ImageDownloader

Usage:

private final ImageDownloader mDownload = new ImageDownloader();
mDownload.download("URL", imageView);

Upvotes: 1

wnafee
wnafee

Reputation: 2146

if you have the image url as a string, you can load and save the image using something like this:

try {   
    Bitmap bitmap = null;
    File f = new File(filename);
    InputStream inputStream = new URL(url).openStream();
    OutputStream outputStream = new FileOutputStream(f);

    int readlen;
    byte[] buf = new byte[1024];
    while ((readlen = inputStream.read(buf)) > 0)
        outputStream.write(buf, 0, readlen);

    outputStream.close();
    inputStream.close();
    bitmap = BitmapFactory.decodeFile(filename);

    return bitmap;
} catch (Exception e) {
    return null;
}

For saving, make sure you have appropriate permissions if you're going to save to sdcard.

if you just want to load the image (without saving):

    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
   } catch (IOException e) {
       Log.e(TAG, "Error getting bitmap", e);
   }
   return bm;

Just make sure you fetch the image in a separate thread or using AsyncTask or else you'll get ANRs!

Upvotes: 1

Related Questions