Reputation:
When scroll down in Gridview and again when scroll up image are loaded again and again. I use Picasso library to download images.
here my code:-
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;
}
}
I am new in android developing.Anyone can help me to solve my problem.Thanks in advance!
Upvotes: 0
Views: 414
Reputation: 8277
Usually this happens on Picasso when the image sizes exceed the cache size, i.e if you load images without resizing to lower resolution to reduce their size in memory. Picasso has an internal LruCache, with a fixed max size, so when multiple "huge" images are loaded the previous images are discarded from memory in order to not go over the cache size limit.
The methods to go around this are
Increase Picasso's Lrucache size.
Resize image to lower resolution before loading them.
Edit
Change picasso cache size. Remeber you have to put this code in your application class, and ensure that this instantiation is a singleton. And you need to use this Picasso class everywhere else. I would NOT recommend changing cache size. Instead try the second method method
int maxSize = MAX_CACHE_SIZE;
Picasso picasso = new Picasso.Builder(context)
.memoryCache(new LruCache(maxSize)).build();
Resize image size
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);
Upvotes: 2