在GridView中向下滚动时再次向上滚动图像时再次加载

时间:2015-12-02 05:51:22

标签: android gridview

在Gridview中向下滚动时,再次向上滚动图像时再次加载。我使用Picasso库来下载图像。

这里是我的代码: -

        public class ProductsAdapterGridView extends ArrayAdapter<Products> {

        ArrayList<Products> productsList;
        LayoutInflater vi;
        int Resource;
        ViewHolder holder;
        UserSessionManager session;
        Boolean isInternetPresent = false;
        ConnectionDetector cd;
        AlertDialogManager alert = new AlertDialogManager();
        String product_id_grid;
        String val;

        List<String> wishArray = new ArrayList<>();
        private String file = "wishlistdata";
        String data;



        public ProductsAdapterGridView(Context context, int resource, ArrayList<Products> object) {
            super(context, resource, object);
            vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            productsList = object;
            Resource = resource;
            session = new UserSessionManager(getContext());
            cd = new ConnectionDetector(getContext());
            //   this.context = context;

        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                holder = new ViewHolder();
                v = vi.inflate(Resource, null);

                holder.image_product=(ImageView)v.findViewById(R.id.image_grid_view);
                holder.product_id = (TextView)v.findViewById(R.id.product_id_grid_view);
                holder.product_name = (TextView)v.findViewById(R.id.product_name_grid_view);
                holder.product_price = (TextView)v.findViewById(R.id.products_price_grid_view);
                holder.product_discount = (TextView)v.findViewById(R.id.product_discount_grid_view);
                holder.product_special = (TextView)v.findViewById(R.id.product_special_grid_view);
                holder.ratingBar = (RatingBar)v.findViewById(R.id.ratingBar_grid_view);
                holder.products_off_grid_view = (TextView)v.findViewById(R.id.products_off_grid_view);
                holder.imageViewHeart = (ImageView)v.findViewById(R.id.heart);

                v.setTag(holder);
            }
            else{
                holder = (ViewHolder)v.getTag();
            }
            holder.image_product.setImageResource(R.drawable.ic);



           Picasso.with(getContext()).load(productsList.get(position).getThumb()).into(holder.image_product);

            Picasso.with(getContext()).load(productsList.get(position).getHeart()).into(holder.imageViewHeart);



           // new DownloadImageTask(holder.image_product).execute(productsList.get(position).getThumb());

            //ProductsCategory.wishlistCheckModules
            holder.product_id.setText(productsList.get(position).getId());


            //Toast.makeText(getContext(), holder.product_id.getText().toString(),Toast.LENGTH_LONG).show();
            holder.product_name.setText(productsList.get(position).getName());
            if(!productsList.get(position).getSpecial().equals("0")){

                holder.product_price.setText(getContext().getResources().getString(R.string.price) + "" + productsList.get(position).getPirce());
                //   holder.product_price.setTextColor(Color.parseColor("#000000"));
                //   holder.product_price.setTextSize(12.0f);

                holder.product_special.setText(getContext().getResources().getString(R.string.price)+""+productsList.get(position).getSpecial());

                holder.product_price.setPaintFlags(holder.product_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.product_price.setTextSize(10.0f);
                holder.product_price.setTypeface(null, Typeface.NORMAL);
                holder.product_price.setTextColor(Color.parseColor("#999999"));

                float num1 = 100-((Float.parseFloat(productsList.get(position).getSpecial())/Float.parseFloat(productsList.get(position).getPirce()))*100);
                holder.products_off_grid_view.setText(Math.round(num1) + getContext().getResources().getString(R.string.off));
                holder.products_off_grid_view.setTypeface(null, Typeface.BOLD);
                //  holder.products_off_grid_view.setTextSize(12.0f);

                holder.product_discount.setVisibility(View.GONE);
                holder.product_special.setVisibility(View.VISIBLE);
                holder.products_off_grid_view.setVisibility(View.VISIBLE);
            }
            else if(!productsList.get(position).getDiscountprice().equals("0")){


                holder.product_price.setText(getContext().getResources().getString(R.string.price) + "" + productsList.get(position).getPirce());

                holder.product_discount.setText(getContext().getResources().getString(R.string.price) + "" + productsList.get(position).getDiscountprice());
                holder.product_price.setPaintFlags(holder.product_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                holder.product_price.setTextSize(10.0f);
                holder.product_price.setTypeface(null, Typeface.NORMAL);
                holder.product_price.setTextColor(Color.parseColor("#999999"));


                float num1 = 100-((Float.parseFloat(productsList.get(position).getDiscountprice())/Float.parseFloat(productsList.get(position).getPirce()))*100);
                holder.products_off_grid_view.setText(Math.round(num1) + getContext().getResources().getString(R.string.off));
                holder.products_off_grid_view.setTypeface(null, Typeface.BOLD);

                holder.product_special.setVisibility(View.GONE);
                holder.product_discount.setVisibility(View.VISIBLE);
                holder.products_off_grid_view.setVisibility(View.VISIBLE);
            }
            else {
                holder.product_price.setText(getContext().getResources().getString(R.string.price)+""+productsList.get(position).getPirce());
                holder.product_price.setPaintFlags(0);
                holder.product_price.setPaintFlags(holder.product_price.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
                holder.product_price.setTextColor(Color.parseColor("#000000"));
                holder.product_price.setTypeface(null, Typeface.BOLD);
                holder.product_price.setTextSize(15.0f);

                holder.products_off_grid_view.setVisibility(View.INVISIBLE);
                holder.product_discount.setVisibility(View.GONE);
                holder.product_special.setVisibility(View.GONE);
            }

            holder.ratingBar.setNumStars(Integer.parseInt(productsList.get(position).getRating()));
            holder.ratingBar.setVisibility(View.GONE);
            holder.imageViewHeart.setId(position);
            holder.imageViewHeart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(session.checkLoginWishlist()){

                        product_id_grid = productsList.get(v.getId()).getId();

                        isInternetPresent = cd.isConnectingToInternet();

                        if(isInternetPresent){
                            new WishListProducts().execute("http://www.shoppingmazza.com/?route=feed/web_api/wishlistadd&key=test123$");
                        }
                        else {
                            alert.showAlertDialog(getContext(), "No Internet Connection",
                                    "You don't have internet connection.", false);
                        }
                    }
                    else {
                        Toast.makeText(getContext(),"You have to login first",Toast.LENGTH_LONG).show();
                    }
                }
            });
            return v;
        }

        public class WishListProducts extends AsyncTask<String,Void,Void>{
            Boolean result = true;

            HashMap<String,String> cidValue = session.getUserDetails();
            String val;
            Boolean run = true;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                Boolean run;
                for(Map.Entry<String, String> entry : cidValue.entrySet()) {
                    String key = entry.getKey().toString();;
                    String  value = entry.getValue();
                    val = value;
                    Log.d("value is",val);
                    // Toast.makeText(ProductsDetails.this,"call pre",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            protected Void doInBackground(String... params) {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(params[0]);

                    List<NameValuePair> nameValuePairs = new ArrayList<>(2);
                    nameValuePairs.add(new BasicNameValuePair("product_id",product_id_grid));
                    nameValuePairs.add(new BasicNameValuePair("cid", val));

                    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = client.execute(post);
                    int status = response.getStatusLine().getStatusCode();
                    if(status==200){
                        HttpEntity entity = response.getEntity();
                        String data = EntityUtils.toString(entity);

                        JSONObject jsonObject = new JSONObject(data);

                        String msg = jsonObject.getString("msg");

                        Log.d("mamu",msg);

                        if(msg.equals("success")){
                            run = true;
                        }
                        else {
                            run = false;
                        }
                    }

                }catch (IOException | JSONException e){
                    result = false;
                    Log.e("Error",e.getMessage());
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                //super.onPostExecute(aVoid);
                if(result){
                    if(run){
                        Toast.makeText(getContext(), "Products Sucessfully Added", Toast.LENGTH_LONG).show();

                    /*    Picasso.with(getContext()).load("http://shoppingmazza.com/image/data/heart13.png").into(holder.imageViewHeart);
                        new InsertWishlistDetail().execute("http://shoppingmazza.com/?route=feed/web_api/insertappdata&key=test123$");*/

                    }
                    else {

                        new RemoveWishListProducts().execute("http://www.shoppingmazza.com/?route=feed/web_api/wishlistremove&key=test123$");

                    }
                } else{
                    Toast.makeText(getContext(),"Somthing is bad happen",Toast.LENGTH_LONG).show();
                }
            }
        }
        public class InsertWishlistDetail extends AsyncTask<String,Void,Void>{
            Boolean result = true,run;
            String android_id;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                android_id = Settings.Secure.getString(getContext().getContentResolver(),
                        Settings.Secure.ANDROID_ID);
            }

            @Override
            protected Void doInBackground(String... params) {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(params[0]);

                    List<NameValuePair> nameValuePairs = new ArrayList<>(2);
                    nameValuePairs.add(new BasicNameValuePair("deviceid", android_id));
                    nameValuePairs.add(new BasicNameValuePair("pid",product_id_grid));


                    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = client.execute(post);
                    if(response.getStatusLine().getStatusCode()==200){

                        HttpEntity entity = response.getEntity();
                        String data = EntityUtils.toString(entity);

                        JSONObject jsonObject = new JSONObject(data);

                        if(jsonObject.getString("msg").equals("success")){
                            run = true;
                        }
                        else {
                            run = false;
                        }

                    }

                }catch (IOException | JSONException e){
                    result = false;
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
               // super.onPostExecute(aVoid);
                if(result){
                    if(run){

                    }
                }
            }
        }
        public class RemoveWishListProducts extends AsyncTask<String,Void,Void>{
            Boolean result;
            HashMap<String,String> cidValue = session.getUserDetails();
            String val;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                for(Map.Entry<String, String> entry : cidValue.entrySet()) {
                    String key = entry.getKey().toString();;
                    String  value = entry.getValue();
                    val = value;
                    Log.d("value is",val);
                    // Toast.makeText(ProductsDetails.this,"call pre",Toast.LENGTH_LONG).show();
                }
            }
            @Override
            protected Void doInBackground(String... params) {
                try{
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(params[0]);

                    List<NameValuePair> nameValuePairs = new ArrayList<>(2);
                    nameValuePairs.add(new BasicNameValuePair("product_id",product_id_grid));
                    nameValuePairs.add(new BasicNameValuePair("cid",val));
                    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = client.execute(post);
                    int status = response.getStatusLine().getStatusCode();
                    if(status==200) {
                        HttpEntity entity = response.getEntity();
                        String data = EntityUtils.toString(entity);

                        JSONObject jsonObject = new JSONObject(data);

                        if(jsonObject.getString("msg").equals("error")){
                            result = false;
                        }else {
                            result = true;
                        }
                    }
                }catch (IOException |JSONException e){
                    // Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                if(result){
                   // reload();
                    Toast.makeText(getContext(),"Item is sucessfully Removed",Toast.LENGTH_LONG).show();

                    Picasso.with(getContext()).load("http://shoppingmazza.com/image/data/heart296.png").into(holder.imageViewHeart);

                    new WishlistRemove().execute("http://shoppingmazza.com/?route=feed/web_api/deleteappdata&key=test123$");
                  //  holder.imageViewHeart.setImageResource(R.drawable.wishlistcat);
                }else {
                    Toast.makeText(getContext(),"Somthing is bad happened",Toast.LENGTH_LONG).show();
                }
            }
        }

        public class WishlistRemove extends AsyncTask<String,Void,Void>{
            Boolean result = true;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(String... params) {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(params[0]);

                    List<NameValuePair> nameValuePairs = new ArrayList<>(1);
                    nameValuePairs.add(new BasicNameValuePair("id", product_id_grid));

                    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = client.execute(post);
                    if(response.getStatusLine().getStatusCode()==200){

                        HttpEntity entity = response.getEntity();
                        String data = EntityUtils.toString(entity);

                        JSONObject jsonObject = new JSONObject(data);

                        Log.d("jo",jsonObject+"");
                    }

                }catch (IOException | JSONException e){
                    result = false;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
               // super.onPostExecute(aVoid);
                if(result){

                }
            }
        }

        static class ViewHolder{
            public ImageView image_product;
            public TextView  product_id;
            public TextView  product_name;
            public TextView  product_price;
            public TextView  product_discount;
            public TextView  product_special;
            public RatingBar ratingBar;
            public TextView  products_off_grid_view;
            public ImageView imageViewHeart;
        }

    }

我是android开发的新手。任何人都可以帮我解决我的问题。提前谢谢!

1 个答案:

答案 0 :(得分:2)

通常,当图像大小超过高速缓存大小时,这会发生在Picasso上,即如果加载图像而不调整大小以降低分辨率以减小其在内存中的大小。 Picasso有一个内部LruCache,具有固定的最大大小,因此当加载多个“巨大”图像时,先前的图像将从内存中丢弃,以便不超过缓存大小限制。

解决这个问题的方法是

  • 增加Picasso的Lrucache大小。

  • 在加载图像之前将图像调整为较低分辨率。

修改

更改毕加索缓存大小。记住你必须将这段代码放在你的应用程序类中,并确保这个实例化是一个单例。你需要在其他地方使用这个毕加索课程。我会建议更改缓存大小。而是尝试第二种方法

int maxSize = MAX_CACHE_SIZE;
Picasso picasso = new Picasso.Builder(context)
                        .memoryCache(new LruCache(maxSize)).build();

调整图片大小

Picasso
    .with(context)
    .load(UsageExampleListViewAdapter.eatFoodyImages[0])
    .resize(600, 200) // resizes the image to these dimensions (in pixel). does not respect aspect ratio
    .into(imageViewResize);