Mehvish Ali
Mehvish Ali

Reputation: 752

Piccaso not loading Image on First Attempt android

In my application I have a fragment which loads image from remote server to set background of FrameLayout using AsynTask and in onPostExeccute() method I am trying to render Bitmap images using Picasso. But as my Fragment starts first time no image is loaded in the background of FrameLayout but as I refresh the particular fragment then I can see the Image as background.

Updated Code segment inside AsyncTask

      private class AsyncDataClass extends AsyncTask<String, Void, String> {

        @Override

        protected String doInBackground(String... params) {

            String responseBody = "";

            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
            HttpConnectionParams.setSoTimeout(httpParameters, 5000);
            HttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(params[0]);
            String jsonResult = "";
            try {

                HttpResponse response = httpClient.execute(httpPost);
                jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
                System.out.println("Returned Json object " + jsonResult.toString());
            } catch (ClientProtocolException e) {

                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonResult;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ctx);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override

        protected void onPostExecute(String result) {

            super.onPostExecute(result);
            System.out.println("Resulted Value: " + result);
            if(result.equals("") || result == null){
                Toast.makeText(ctx, "Server connection failed", Toast.LENGTH_LONG).show();

            }
            int jsonResult = returnParsedJsonObject(result);
            if(jsonResult == -1){

                    Toast.makeText(ctx, "Sorry No Places Found", Toast.LENGTH_LONG).show();


            }
            if(jsonResult == 1){
                //Toast.makeText(ctx, "", Toast.LENGTH_LONG).show();
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    // Getting JSON Array node
                    places = jsonObj.getJSONArray("result");
                    // looping through All Contacts
                    for (int i = 0; i < places.length(); i++) {
                        JSONObject place = places.getJSONObject(i);
//                        String slot = c.getString(TAG_SLOT);
//                        serverReturn.add(slot);
                        UserPlaces placeFroServer = new UserPlaces();
                        placeFroServer.setId(place.getString(TAG_PID));
                        placeFroServer.setName(place.getString(TAG_PNAME));
                        placeFroServer.setDescription(place.getString(TAG_DESC));
                        placeFroServer.setImg(place.getString(TAG_IMG));
                        placeFroServer.setLat(place.getString(TAG_LAT));
                        placeFroServer.setLng(place.getString(TAG_LNG));
                        placesList.add(placeFroServer);

                    }


                    UserPlaces myPlace =  placesList.get(counter);

                    pid=myPlace.getId();
                    lat = myPlace.getLat();
                    lng = myPlace.getLng();
                    Picasso.with(ctx).load(myPlace.getImg()).into(new Target() {
                        @Override
                        public void onPrepareLoad(Drawable arg0) {
                            // TODO Auto-generated method stub

                        }

                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
                            // TODO Auto-generated method stub
                            Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
                            pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
                            pImg.invalidate();

                        }

                        @Override
                        public void onBitmapFailed(Drawable arg0) {
                            // TODO Auto-generated method stub
                            Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
                        }
                    });

                    pname.setText(myPlace.getName());
                    pdes.setText(myPlace.getDescription());
                    rl.setVisibility(View.VISIBLE);

                    counter++;


                } catch (JSONException e) {

                    String ex = e.getMessage();
                    e.printStackTrace();
                }





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

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = br.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
            return answer;
        }
    }

Upvotes: 0

Views: 576

Answers (3)

Faisal Naseer
Faisal Naseer

Reputation: 4248

For particular problem of week reference try creating a global Target object. As demonstrated in the code below.

Code Sample:

    Target target;
    target = new Target(){
                    @Override
                    public void onPrepareLoad(Drawable arg0) {
                        // TODO Auto-generated method stub

                    }

                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom arg1) {
                        //Toast.makeText(ctx,"Loaded",Toast.LENGTH_LONG).show();
                        // TODO Auto-generated method stub
                        pImg.setBackgroundDrawable(new BitmapDrawable(ctx.getResources(), bitmap));
                        pImg.invalidate();

                    }

                    @Override
                    public void onBitmapFailed(Drawable arg0) {
                        // TODO Auto-generated method stub
                        Toast.makeText(ctx, "Failed Loading", Toast.LENGTH_SHORT).show();
                    }
                };

   Picasso.with(ctx).load(myPlace.getImg()).into(target);

Upvotes: 2

Vivek Faldu
Vivek Faldu

Reputation: 336

You can use the alternative of it Univerasal Image Loader

Upvotes: 0

muratgu
muratgu

Reputation: 7311

You should call invalidate() on pImg after setting the background.

Upvotes: 0

Related Questions