user1743295
user1743295

Reputation:

JSON POST request for download image from server in android

I need to download image and set it in to imageview . for parsing i use JSON POST request and for this i use base64 . I got base64 type data for the image tag in to log but the problem is that how t separate the value of that image and convert it in to string and then display it in to list view ??is there any alternative way without using base64 to display image then please suggest us.

For parsing of data i use JSON parser with HttpPost . Now how to get the value of image from response JSON format that i display above that the confusion ??

Thanks in advance ..

Upvotes: 2

Views: 3246

Answers (4)

ASHISH KUMAR Tiwary
ASHISH KUMAR Tiwary

Reputation: 578

public class SingleContactActivity extends Activity implements OnClickListener {

private static final String TAG_ImageList = "CatList";
private static final String TAG_ImageID = "ID";
private static final String TAG_ImageUrl = "Name";

private static String url_MultiImage;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
String imagepath2;
Bitmap bitmap;
ImageView image;
SessionManager session;
TextView myprofileId;

TextView pending;
TextView Categories, visibleTo;
int count = 0;
ImageButton btn;

// -----------------------
ArrayList<HashMap<String, String>> ImageList;
JSONArray JsonArray = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_single_contact);

    url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";

    new MultiImagePath().execute();

    ImageList = new ArrayList<HashMap<String, String>>();

}

private class MultiImagePath extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url_MultiImage,
                ServiceHandler.GET);

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

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

                // Getting JSON Array node
                JsonArray = jsonObj.getJSONArray(TAG_ImageList);
                if (JsonArray.length() != 0) {

                    for (int i = 0; i < JsonArray.length(); i++) {
                        JSONObject c = JsonArray.getJSONObject(i);

                        String Img_ID = c.getString(TAG_ImageID);
                        String Img_Url = c.getString(TAG_ImageUrl);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ImageID, Img_ID);
                        contact.put(TAG_ImageUrl, Img_Url);

                        // adding contact to contact list
                        ImageList.add(contact);
                    }
                }
                Log.e("JsonLength", "length is ZERO");

            } 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);

        AutoGenImgBtn();

    }

}

@SuppressWarnings("deprecation")
public void AutoGenImgBtn() {

    int count = ImageList.size();
    LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);

    ImageButton[] btn = new ImageButton[count];
    for (int i = 0; i < count; i++) {
        btn[i] = new ImageButton(this);

        btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
        btn[i].setOnClickListener(this);
        btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));

        btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
        btn[i].setAdjustViewBounds(true);

        // btn[i].setTextColor(getResources().getColor(color.white));

        llimage.addView(btn[i]);

    }

}

@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    btn = (ImageButton) v;
    String s = btn.getTag().toString();

    new ImageDownloader().execute(s);

}

private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... param) {
        // TODO Auto-generated method stub
        return downloadBitmap(param[0]);
    }

    @Override
    protected void onPreExecute() {
        Log.i("Async-Example", "onPreExecute Called");
        pDialog = new ProgressDialog(SingleContactActivity.this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(true);
        pDialog.setTitle("In progress...");
        // pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setIcon(android.R.drawable.stat_sys_download);
        pDialog.setMax(100);
        // pDialog.setTitle("Post Details");
        pDialog.show();

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        Log.i("Async-Example", "onPostExecute Called");

        if (bitmap != null) {
            btn.setImageBitmap(bitmap);

        }

        if (pDialog.isShowing())
            pDialog.dismiss();

    }

    private Bitmap downloadBitmap(String url) {
        // initilize the default HTTP client object
        final DefaultHttpClient client = new DefaultHttpClient();

        // forming a HttoGet request
        final HttpGet getRequest = new HttpGet(url);
        try {

            HttpResponse response = client.execute(getRequest);

            // check 200 OK for success
            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 {
                    // getting contents from the stream
                    inputStream = entity.getContent();

                    // decoding stream data back into image Bitmap that
                    // android understands
                    bitmap = BitmapFactory.decodeStream(inputStream);

                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            // You Could provide a more explicit error message for
            // IOException
            getRequest.abort();
            Log.e("ImageDownloader", "Something went wrong while"
                    + " retrieving bitmap from " + url + e.toString());
        }

        return null;
    }
}



  #  Add Service Handler Class#

 public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {



    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * 

 * */

public String makeServiceCall(String url, int method,List<NameValuePair> params) {

    try {
        // http client

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {               
                httpPost.setEntity(new UrlEncodedFormEntity(params));

            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

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

    return response;

}

Upvotes: 0

Mobility
Mobility

Reputation: 263

Use a Gson Parser and then parse the base64 image string to a byte array and apply on the image.

Your model classes will be as follows:

public class JsonWrapper
{
    private Root root ;
    public Root getroot()
    {
        return this.root;
    }
    public void setroot(Root root)
    {
        this.root = root;
    }
}





public class Root
{
    private Response response ;
    public Response getresponse()
    {
        return this.response;
    }
    public void setresponse(Response response)
    {
        this.response = response;
    }
}



public class Response
{
    private Message message ;
    public Message getmessage()
    {
        return this.message;
    }
    public void setmessage(Message message)
    {
        this.message = message;
    }
    private Data data ;
    public Data getdata()
    {
        return this.data;
    }
    public void setdata(Data data)
    {
        this.data = data;
    }
}

public class Message
{
    private String type ;
    public String gettype()
    {
        return this.type;
    }
    public void settype(String type)
    {
        this.type = type;
    }
    private String message ;
    public String getmessage()
    {
        return this.message;
    }
    public void setmessage(String message)
    {
        this.message = message;
    }
}

import java.util.ArrayList;


public class Data
{
    private ArrayList<Image> images ;
    public ArrayList<Image> getimages()
    {
        return this.images;
    }
    public void setimages(ArrayList<Image> images)
    {
        this.images = images;
    }
    private String last_synchronized_date ;
    public String getlast_synchronized_date()
    {
        return this.last_synchronized_date;
    }
    public void setlast_synchronized_date(String last_synchronized_date)
    {
        this.last_synchronized_date = last_synchronized_date;
    }
}

public class Image
{
    private String web_id ;
    public String getweb_id()
    {
        return this.web_id;
    }
    public void setweb_id(String web_id)
    {
        this.web_id = web_id;
    }
    private String blob_image ;
    public String getblob_image()
    {
        return this.blob_image;
    }
    public void setblob_image(String blob_image)
    {
        this.blob_image = blob_image;
    }
}

Once you have the json parse using Gson as follows:

JsonWrapper jsonWrapper = new JsonWrapper();
Gson gsonParser = new Gson();
jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());

Next you can iterate through all the images

ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();

for(Image image : images)
{
  byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

if (decodedString != null) {
                    imageViewtype.setImageBitmap(decodedByte);
                }

}

Upvotes: 0

anuruddhika
anuruddhika

Reputation: 1559

You can do like this.

Create folder in server. put images in that folder. get the URL of the image and insert in to db. then get the JSON value of that url add this method and pass that url to this method.

Bitmap bitmap;
    void loadImage(String image_location) {

        URL imageURL = null;

        try {
            imageURL = new URL(image_location);
        }

        catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();

            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
                                                                // bitmap
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {

            e.printStackTrace();
        }


       }

Upvotes: 1

Sagar Maiyad
Sagar Maiyad

Reputation: 12733

Try below code:

JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");

for(int i=0;i<imgs.length();i++){
    JSONObject Ldetails = Ldtls.getJSONObject(i);
    String img= Ldetails.getString("image");

   byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
   InputStream inputStream  = new ByteArrayInputStream(decodedString);
   Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
   imagevw.setImageBitmap(bitmap);

}

where imagevw is your ImageView.

Upvotes: 1

Related Questions