Android GridView With Image is Too Slow when using universalimageloader - android

I am using universalimageloader in my project to Show many images
When I try to show images it is too Slow, After commented Line Of Display Images it shows Rows as well and not Slow
the Code I tried is :
public class GridAdapterMa extends BaseAdapter {
ArrayList<JobItem> objects = new ArrayList<JobItem>();
int size = 0;
private String TAG = GridAdapterMa.class.getSimpleName();
ImageLoader imageLoader;
DisplayImageOptions options;
ImageLoaderConfiguration config;
public GridAdapterMa(ArrayList<JobItem> objects) {
size = objects.size();
this.objects.addAll(objects);
ExceptionHelpers.dLog(TAG, "Constructor");
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.thumb_square)
.showImageForEmptyUri(R.drawable.thumb_square)
.showImageOnFail(R.drawable.thumb_square)
// .cacheInMemory(false)
.cacheOnDisc(true)
.resetViewBeforeLoading(true)
// .delayBeforeLoading(100)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new SimpleBitmapDisplayer())
/*.preProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bitmap) {
int w = (int) (UIHelpers.width * 0.50);
float r = ((float) bitmap.getHeight() / (float) bitmap.getWidth());
int h = (int) (w * r);
ExceptionHelpers.dLog(TAG, "Adapter Width : " + w + " Height : " + h + " R : " + r);
ExceptionHelpers.dLog(TAG, "Adapter Width : " + bitmap.getWidth() + " Height : " + bitmap.getHeight());
return Bitmap.createScaledBitmap(bitmap, w, h, false);
}
})*/
.build();
config = new ImageLoaderConfiguration.Builder(App.context)
.defaultDisplayImageOptions(options)
.memoryCacheSize(41943040)
.discCacheSize(104857600)
.threadPoolSize(10)
.build();
}
#Override
public int getCount() {
return size;
}
#Override
public JobItem getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
try {
if(convertView==null){
LayoutInflater vi = (LayoutInflater) App.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(UIHelpers.screen_density >= 4){
convertView = vi.inflate(R.layout.grid_ma_xl, null);
}else{
convertView = vi.inflate(R.layout.grid_ma_m, null);
}
holder = new ViewHolder();
holder.img =(ImageView) convertView.findViewById(R.id.img_image_gv_ma);
holder.imgVip = (ImageView) convertView.findViewById(R.id.img_vip_gv_ma);
holder.txtTitle = (TextView) convertView.findViewById(R.id.txt_title_gv_item);
holder.txtCat = (TextView) convertView.findViewById(R.id.txt_cat_gv_item);
holder.txtDesc = (TextView) convertView.findViewById(R.id.txt_desc_gv_item);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
Typeface tf = Typeface.createFromAsset(App.context.getAssets(), "b_yekan.ttf");
Typeface tf1 = Typeface.createFromAsset(App.context.getAssets(), "b_mitra.ttf");
holder.txtTitle.setTypeface(tf1);
holder.txtCat.setTypeface(tf);
holder.txtDesc.setTypeface(tf);
holder.txtTitle.setTextSize(UIHelpers.titleFont);
holder.txtCat.setTextSize(UIHelpers.descFont);
holder.txtDesc.setTextSize(UIHelpers.descFont);
if(objects.get(position).getjVip()==1) {
holder.imgVip.setVisibility(View.VISIBLE);
} else if (objects.get(position).getjVip()==0) {
holder.imgVip.setVisibility(View.INVISIBLE);
}
String imgURL = "";
imgURL = imgURL + objects.get(position).getjImage();
// ExceptionHelpers.dLog(TAG, "imgURL : '" + imgURL + "'");
/*if(imgURL.equals("http://www.yazdjobs.com/null") ||
imgURL.equals("http://www.yazdjobs.com/") ||
imgURL.equals("http://yazdjobs.com/null") ||
imgURL.equals("http://yazdjobs.com/")){
imgURL = "http://www.yazdjobs.com/wp-content/themes/yazdjobs/images/no-image.png";
}*/
// ExceptionHelpers.dLog(TAG, "imgURL : '" + imgURL + "'");
// ExceptionHelpers.dLog(TAG, "Position : "+position+" / "+objects.size());
// Show Images
// imageLoader.init(ImageLoaderConfiguration.createDefault(App.context));
imageLoader.init(config);
ImageAware imageAware = new ImageViewAware(holder.img, false);
imageLoader.displayImage(imgURL, imageAware, options);
/*Picasso.with(App.context)
.load(imgURL)
.placeholder(R.drawable.thumb_square)
.error(R.drawable.thumb_square)
.into(holder.img);*/
holder.txtTitle.setText(objects.get(position).getjTitle());
holder.txtCat.setText(objects.get(position).getjCatName());
if(UIHelpers.screen_density >= 4){
holder.txtDesc.setText(objects.get(position).getjDescLimit());
}else{
holder.txtDesc.setText(objects.get(position).getjDesc());
}
} catch (Exception e) {
ExceptionHelpers.catchMessage(e);
ExceptionHelpers.eLog(TAG, "Error in Grid Adapter >> " + e, e);
}
return convertView;
}
public class ViewHolder {
private ImageView img;
private ImageView imgVip;
private TextView txtTitle;
private TextView txtCat;
private TextView txtDesc;
}
}
I Even Tried ImageLoaderConfiguration But Not works To Me.
How To Fix It

Related

how to load image using image path in gridview in android studio?

how do i display image using the imagepath fetched from mysql database into gridview. i tried lot but unable to do.
this is my asynctask code:
public class sampling_info extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SamplingActivity.this);
pDialog.setMessage("Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
String doc = dcname.toString();
ArrayList<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("docname", doc));
JSONObject json = jParser.makeHttpRequest(URL_SAMPLING, "POST",
namevaluepair);
return json;
}
protected void onPostExecute(JSONObject json) {
// dismiss the dialog once done
pDialog.dismiss();
if (json != null) {
try {
JSONArray jarray = json.getJSONArray("product_entered");
Log.d("jarray in sampling : ", "" + jarray.toString());
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String docname = jobj.getString("docname");
String imagep= jobj.getString("image_path");
GridItem gItem= new GridItem();
gItem.setTitle("sagar");
gItem.setImage(imagep);
mgrid.add(gItem);
Log.d("jobj : ", "" + jobj);
Log.d("jobj docname", "" + docname);
}
} catch (Exception e) {
e.printStackTrace();
}
gridAdapter = new GridViewAdapter(SamplingActivity.this, R.layout.grid_item_layout,mgrid);
gridview.setAdapter(gridAdapter);
}
}
i this asynctask am fetching imagepath from database and storing it in imagep variable and passing it to GridItem class
This is my griditem class :
public class GridItem {
private Bitmap image;
private String title,image1;
public GridItem(Bitmap image) {
this.image=image;
}
public Bitmap getImage() {
return image;
}
public Bitmap setImage(String image) { // this is where am trying to set my image but can't do.
try {
} catch (Exception e) {
}
return null;
}
And this is my adapter class :
public GridViewAdapter(Context mContext, int layoutResourceId,
ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
*
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
//ViewHolder holder;
ImageView imageView = (ImageView) row
.findViewById(R.id.grid_item_image);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
// holder = new ViewHolder();
//imageView = (ImageView) convertView;
TextView titleTextView = (TextView) row
.findViewById(R.id.grid_item_title);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
}
GridItem item = mGridData.get(position);
imageView.setImageBitmap(item.getImage());
return row;
}
I suggest you to use Universal Image Loader
First of all, include last version of jar file from 'lib' directory to your project
in Adapter :
ImageLoader imageLoader = null;
DisplayImageOptions options;
in Adapter's Contractor :
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
/*.displayer(new RoundedBitmapDisplayer((int) 27.5f))*/
.showImageOnLoading(R.drawable.thumb_square)
.showImageForEmptyUri(R.drawable.thumb_square)
.showImageOnFail(R.drawable.thumb_square)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.imageScaleType(ImageScaleType.NONE)
.bitmapConfig(Bitmap.Config.RGB_565)
/*.postProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
float r = ((float)h / (float)w);
ExceptionHelpers.dLog("POST_PROCESSOR", "width : " + w + " , height : " + h + " , R1 : " + r + " , W : " + UIHelpers.width + " , Percent W : " + UIHelpers.setPercentW(r));
return Bitmap.createScaledBitmap(bitmap, UIHelpers.width, UIHelpers.setPercentW(r), false);
}
})*/
.build();
and getView :
String imgURL = "http://www.website.com/images/image_path.png";
imageLoader.init(ImageLoaderConfiguration.createDefault(mContext));
imageLoader.displayImage(imgURL, holder.img_view, options);
First of all dont store the bitmap in modelClass, Alternatively you can add sd card path or live url of an image(http://...)
Loading the image:
-- I suggest you to use Glide library
Code sample:
Glide.with(context)
.load(url) // pass your image url
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.crossFade() //animate the image
.into(myImageView);

Fully displayed listview image is not displaying properly

its my following code.
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
//Toast.makeText(getApplicationContext(), productID[j] + "" + ProductName[j] + "" + ProductPrice[j] + "" + ProductQuantity[j] + "" + ProductModel[j] + "" + ProductImage[j] + "" + ProductManufacturer[j], Toast.LENGTH_SHORT).show();
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
getListViewSize(ListCart);
String s1 = ProductPrice.toString();
}
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
if (listItem != null) {
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
if (params != null) {
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
}
myListView.requestLayout();
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
Adapter class
Public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
listview is working properly
i just inflate cardview in listview.
when using this code image cannot displaying. only dispaly last image in list view
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
my problem is: In listview only displaying last image
check this image:
Try adding your ImageView to Holder class and use like viewholder.img.setImageBitmap(new LoadImage().execute(urll)) and change the return type to Bitmap
Use BaseAdapter instead of ArrayAdapter. Load and show image with UIL, Picasso or other image loader library.
public class ImageAdapter extends BaseAdapter {
private List<ImageBean> list;
private ArrayList<ImageBean> arraylist;
private LayoutInflater inflater;
public ImageAdapter(Context context, List<ImageBean> list) {
this.list = list;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public ImageBean getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.recycler_view_item, parent, false);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Loading image with UIL example
ImageLoader.getInstance().displayImage(getItem(position).getUrl(), holder.ivImage, ImageUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
return convertView;
}
private class ViewHolder {
public ImageView ivImage;
}
}

get item view type in adapter returning only 1 item

I have a custom adapter which will inflate two layout according to a certain condition.
GetItemViewType returning only 1 item in the position while there is two and when i present it in the list the adapter inflate one layout the other is not and i can see in my list that there is a space left for it but its blank.
here is my code
enter code here
public class ListViewAdapter extends ArrayAdapter<NewsFeed>
{
private static final int missionLayout = 0;
private static final int badgeLayout = 1;
private TreeSet mSeparatorsSet = new TreeSet();
public ListViewAdapter ()
{
super(CityNewsFeedActivity.this,R.layout.activity_activity_city_news_feed,newsfeed);
}
#Override
public int getItemViewType(int position)
{
return mSeparatorsSet.contains(position) ? missionLayout : badgeLayout;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder=null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null)
{
NewsFeed obj = newsfeed.get(position);
holder = new ViewHolder();
switch (type)
{
case missionLayout:
Log.d("fet 3ala mission layout","tahet il case");
convertView = getLayoutInflater().inflate(R.layout.city_news_single_item, parent,false);
holder.civilianImage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.heroName = (TextView) convertView.findViewById(R.id.badgename);
holder.description = (TextView) convertView.findViewById(R.id.description);
holder.timeRemaining = (TextView) convertView.findViewById(R.id.postedSince);
holder.relativeLayoutMission = (RelativeLayout) convertView.findViewById(R.id.relativeLayout);
if (obj.category.equals("mission"))
{
if (obj.accepted_rejected.equals("success"))
{
holder.relativeLayoutMission.setBackgroundResource(R.drawable.mission_successful);
Float alpha = Float.valueOf("0.9");
holder.relativeLayoutMission.setAlpha(alpha);
byte[] decodedString = Base64.decode(obj.picture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Bitmap circleBitmap = Bitmap.createBitmap(decodedByte.getWidth(), decodedByte.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(decodedByte, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(decodedByte.getWidth() / 2, decodedByte.getHeight() / 2, decodedByte.getWidth() / 2, paint);
holder.civilianImage.setImageBitmap(circleBitmap);
Drawable d = getResources().getDrawable(
R.drawable.circle_shape_for_civilian_success);
holder.civilianImage.setBackgroundDrawable(d);
String hero = obj.mission_nickname;
holder.heroName.setText(Html.fromHtml("<font color='#FAD84F'>" + hero + "</font>" + " saved " + obj.firstname + " " + obj.lastname));
holder.description.setText(obj.description);
holder.timeRemaining.setText(obj.mission_postedSince);
}
}
break;
case badgeLayout:
convertView = getLayoutInflater().inflate(R.layout.badge_single_item, null);
holder.relativeLayoutBadge = (RelativeLayout) convertView.findViewById(R.id.relativeLayout);
holder.BadgeName = (TextView) convertView.findViewById(R.id.badgename);
holder.badgeImage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.timeRemaining = (TextView) convertView.findViewById(R.id.postedSince);
if (obj.category.equals("badge"))
{
holder.relativeLayoutBadge.setBackgroundResource(R.drawable.earned_badge_post);
Float alpha = Float.valueOf("0.9");
holder.relativeLayoutBadge.setAlpha(alpha);
String hero = obj.nickname;
holder.BadgeName.setText(Html.fromHtml("<font color='#FAD84F'>" + hero + "</font>" + " earns a new badge! "));
Drawable d = getResources().getDrawable(R.drawable.circle_shape_for_badge);
holder.badgeImage.setBackgroundDrawable(d);
String imageUrl = "http://iamheroic.net/iamheroic/badge_images/" + obj.icon;
imageLoader.displayImage(imageUrl, holder.badgeImage, options);
holder.timeRemaining.setText(obj.postedSince);
}
break;
}
if (convertView != null)
{
convertView.setTag(holder);
}
}
return convertView;
}
}
When i run the app the list shows one layout of type 1 and leaves space for type 0 but its not presented.
Any help would be appreciated.
You also have to override getViewTypeCount() to tell the ListView how many item types to expect. It does this to handle recycling Views for each type.
#Override
public int getViewTypeCount() {
return 2;
}

Image in listview ordering is not correct and download again

Here is how I set up the list view and how I get the image by downloading it.
Some variable explanation :
The PostItem is the model object that contain the data for a listview item
The ImageLoader is the async task class to download the image by getting the image url from PostItem
The problem are , the ordering of the image in the listview is incorrect , for example, the image should appear in 1st is appear in both 1st , 4th, and if I scroll , the display pattern change as well.
Also, I find the image are download again if I scroll, even I have check the imageView whether has drawable
Thanks for helping.
====================================================
Here is how I generate the listview:
static class ViewHolderItem {
TextView name;
TextView date;
ImageView img;
TextView msg;
TextView count;
ImageView likeBtn;
ImageView commentBtn;
ImageView shareBtn;
}
private class MyPostAdapter extends ArrayAdapter<PostItem> {
#Override
public boolean isEnabled(int position) {
return false;
}
public MyPostAdapter(Context context, int resource, List<PostItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolderItem viewHolder;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.post_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.name = (TextView) v.findViewById(R.id.postName);
viewHolder.date = (TextView) v.findViewById(R.id.postDate);
viewHolder.img = (ImageView) v.findViewById(R.id.postImg);
viewHolder.msg = (TextView) v.findViewById(R.id.postMsg);
viewHolder.count = (TextView) v.findViewById(R.id.count);
viewHolder.likeBtn = (ImageView) v.findViewById(R.id.likeBtn);
viewHolder.commentBtn = (ImageView) v.findViewById(R.id.commentBtn);
viewHolder.shareBtn = (ImageView) v.findViewById(R.id.shareBtn);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
final PostItem post = getItem(position);
if (post != null) {
viewHolder.name.setText(post.name);
try {
c.setTime(sdf.parse(post.createDate));
} catch (ParseException e) {
e.printStackTrace();
}
relative_date = DateUtils.getRelativeDateTimeString (ctx, c.getTimeInMillis() , DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0).toString();
viewHolder.date.setText(relative_date);
viewHolder.msg.setText(post.txtMsg);
viewHolder.count.setText(post.likeCount + " " + getString(R.string.pro_like) + " " + post.commentCount + " " + getString(R.string.reply));
if (post.isLike) {
viewHolder.likeBtn.setImageResource(R.drawable.like);
} else {
viewHolder.likeBtn.setImageResource(R.drawable.before_like);
}
if (!post.imageURL.equals("null") && viewHolder.img.getDrawable() == null ) {
new ImageLoader(ctx).execute(viewHolder.img,Constant.comment_imageFolder + post.imageURL);
} else {
viewHolder.img.setImageDrawable(null);
}
viewHolder.likeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new APIManager("like", ctx, Constant.likeAPI + "/"
+ post.commentID + "/" + userID, jsonListener,
getResources().getString(R.string.update_data));
}
});
viewHolder.commentBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<PostItem> filterReplyList = new ArrayList<PostItem>();
Intent i = new Intent(ctx, ReplyActivity.class);
i.putExtra("commentID", post.commentID);
// get reply list
for (PostItem reply : replyItemList) {
if (reply.postID.equals(post.commentID)
|| reply.commentID.equals(post.commentID)) {
filterReplyList.add(reply);
}
}
i.putExtra("replyItemList", filterReplyList);
startActivityForResult(i, 0);
}
});
viewHolder.shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String data = "date: " + post.createDate + "\nmsg:" + post.txtMsg;
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
return v;
}
}
And Here is the imageloader, take the imageview, url as input and put the bitmap in the imageview
public class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
private InputStream input;
private ImageView view;
private ProgressBar loadingIcon;
private ListView myListView;
private String imageURL;
private Context ctx;
public ImageLoader(Context _ctx) {
ctx = _ctx;
}
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
// handle Chinese characters in file name
// String[] imgUrlArray = ((String) params[1]).split("/");
// String fileName = imgUrlArray[imgUrlArray.length - 1];
// String newfileName = URLEncoder.encode(fileName, "utf-8");
// imageURL = ((String) params[1]).replace(fileName, newfileName);
imageURL = ((String) params[1]);
if (params.length > 2 && (ProgressBar) params[2] != null)
loadingIcon = (ProgressBar) params[2];
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
final BitmapFactory.Options options = new BitmapFactory.Options();
BufferedInputStream bis = new BufferedInputStream(input, 4*1024);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte)current);
}
byte[] imageData = baf.toByteArray();
BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
options.inJustDecodeBounds = true;
options.inSampleSize = 2;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
if (loadingIcon != null)
loadingIcon.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
view.setImageBitmap(result);
}
}
Updated code (implement volley library):
static class ViewHolderItem {
TextView name;
TextView date;
NetworkImageView img;
TextView msg;
TextView count;
ImageView likeBtn;
ImageView commentBtn;
ImageView shareBtn;
}
private class MyPostAdapter extends ArrayAdapter<PostItem> {
#Override
public boolean isEnabled(int position) {
return false;
}
public MyPostAdapter(Context context, int resource, List<PostItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolderItem viewHolder;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.post_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.name = (TextView) v.findViewById(R.id.postName);
viewHolder.date = (TextView) v.findViewById(R.id.postDate);
viewHolder.img = (NetworkImageView) v.findViewById(R.id.postImg);
viewHolder.msg = (TextView) v.findViewById(R.id.postMsg);
viewHolder.count = (TextView) v.findViewById(R.id.count);
viewHolder.likeBtn = (ImageView) v.findViewById(R.id.likeBtn);
viewHolder.commentBtn = (ImageView) v.findViewById(R.id.commentBtn);
viewHolder.shareBtn = (ImageView) v.findViewById(R.id.shareBtn);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolderItem) convertView.getTag();
}
final PostItem post = getItem(position);
if (post != null) {
viewHolder.name.setText(post.name);
try {
c.setTime(sdf.parse(post.createDate));
} catch (ParseException e) {
e.printStackTrace();
}
relative_date = DateUtils.getRelativeDateTimeString (ctx, c.getTimeInMillis() , DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS, 0).toString();
viewHolder.date.setText(relative_date);
viewHolder.msg.setText(post.txtMsg);
viewHolder.count.setText(post.likeCount + " " + getString(R.string.pro_like) + " " + post.commentCount + " " + getString(R.string.reply));
if (post.isLike) {
viewHolder.likeBtn.setImageResource(R.drawable.like);
} else {
viewHolder.likeBtn.setImageResource(R.drawable.before_like);
}
if (!post.imageURL.equals("null")) {
viewHolder.img.setImageUrl(Constant.comment_imageFolder + post.imageURL, mImageLoader);
}
viewHolder.likeBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new APIManager("like", ctx, Constant.likeAPI + "/"
+ post.commentID + "/" + userID, jsonListener,
getResources().getString(R.string.update_data));
}
});
viewHolder.commentBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<PostItem> filterReplyList = new ArrayList<PostItem>();
Intent i = new Intent(ctx, ReplyActivity.class);
i.putExtra("commentID", post.commentID);
// get reply list
for (PostItem reply : replyItemList) {
if (reply.postID.equals(post.commentID)
|| reply.commentID.equals(post.commentID)) {
filterReplyList.add(reply);
}
}
i.putExtra("replyItemList", filterReplyList);
startActivityForResult(i, 0);
}
});
viewHolder.shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
String data = "date: " + post.createDate + "\nmsg:" + post.txtMsg;
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
return v;
}
For the task you are trying to do I would strongly recommend you to use Volley library.
Read from here
All you need to do is as below
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache());
mImageView.setImageUrl(BASE_URL + item.image_url, mImageLoader);
Where mImageView is com.android.volley.NetworkImageView instead of a regular ImageView.
Volley takes care of maintaining the cache and the ordering of the images.
if you scroll the listview you will get back recycled convertview, it is not null but it has incorrect imageview. convertView is a view thats created and recycled through scrolling the list. this view makes GC be called less and also save memory for you. it first assigned by your earliest items of list. after you scroll the list, for example item one of list disappears and you see item 15 the convertView of item one is passed again to you. in this time it is not null and it holdes the reference of last imageview, the imageview of item 1.
so this is your problem, you skipped assigning correct imageview to your viewHolder.img.
Ok, what should you do?
the best thing you can do is create in memory cache that holds your downloaded imageview by their URLs as keys of the cache. in getview you check the cache, if it has your URL of current imageview position read from it and set it to viewHolder.img else download the image from internet.
Golden rule is:
ALWAYS OVERWRITE VIEWHOLDER VALUES WITH VALUES OF YOUR ITEM AT INDEX POSITON THAT
GETVIEW PASSES TO YOU
how to create cache? look at Example LRU cache at
http://developer.android.com/training/volley/request.html
and if you want you can also use volley library instead.
if (!post.imageURL.equals("null") && viewHolder.img.getDrawable() == null ) {
new ImageLoader(ctx).execute(viewHolder.img,Constant.comment_imageFolder + post.imageURL);
}
I am guessing that the problem lies here. What happens when you get a recycled view which already has an image from the previous view it was used for? That explains why the image appears in both 1st and 4th position and the change in the display pattern when you scroll.
Get the point? Remove the viewHolder.img.getDrawable() == null and try. See if that helps.

Listview items duplicated on clicking notification

I am getting listView items duplicated if I play a song in the background and go back to the app on clicking the notification icon. While opening the app for the first time, items are not duplicated. What could be wrong? Posting below my adapter class.
Adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder = null;
final int pos = position;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (RelativeLayout) inflater.inflate(R.layout.song, parent,
false);
holder = new ViewHolder();
holder.tvTitle = (TextView) view.findViewById(R.id.tv_song_title);
holder.tvArtist = (TextView) view.findViewById(R.id.tv_song_artist);
holder.imgAlbumArt = (ImageView) view
.findViewById(R.id.img_lv_album_art);
holder.tvArtist.setText(songs.get(position).getArtist());
holder.tvTitle.setText(songs.get(position).getTitle());
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
int id = (int) songs.get(position).getId();
if (bitmaps == null) {
Bitmap bm = MainActivity.getCachedArtwork(mContext,
id, MainActivity.getDefaultArtwork(mContext));
holder.imgAlbumArt.setImageBitmap(bm);
bitmaps.put(id, bm);
Log.d("inside null", "key=" + id + "bm=" + bm + "pos" + position);
} else if (bitmaps.containsKey(id)) {
Bitmap bm = bitmaps.get(id);
holder.imgAlbumArt.setImageBitmap(bm);
bitmaps.put(id, bm);
Log.d("inside contains key", "key=" + id + "bm=" + bm + "pos"
+ position);
} else {
Bitmap bm = MainActivity.getCachedArtwork(mContext,
id, MainActivity.getDefaultArtwork(mContext));
holder.imgAlbumArt.setImageBitmap(bm);
bitmaps.put(id, bm);
Log.d("inside else", "key=" + id + "bm=" + bm + "pos" + position);
}
return view;
}
MainActivity:
public static Bitmap getCachedArtwork(Context context, int artIndex,
Bitmap defaultArtwork) {
Bitmap d = null;
synchronized (sArtCache) {
d = sArtCache.get(artIndex);
}
if (d == null) {
d = defaultArtwork;
final Bitmap icon = defaultArtwork;
int w = icon.getWidth();
int h = icon.getHeight();
Bitmap b = getArtworkQuick(context, artIndex, w, h);
if (b != null) {
d = b;// new FastBitmapDrawable(b);
synchronized (sArtCache) {
// the cache may have changed since we checked
Bitmap value = sArtCache.get(artIndex);
if (value == null) {
sArtCache.put(artIndex, d);
} else {
d = value;
}
}
}
}
return d;
}
// Get album art for specified album. This method will not try to
// fall back to getting artwork directly from the file, nor will
// it attempt to repair the database.
private static Bitmap getArtworkQuick(Context context, int album_id, int w, int h) {
// NOTE: There is in fact a 1 pixel frame in the ImageView used to
// display this drawable. Take it into account now, so we don't have to
// scale later.
w -= 2;
h -= 2;
ContentResolver res = context.getContentResolver();
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
if (uri != null) {
ParcelFileDescriptor fd = null;
try {
fd = res.openFileDescriptor(uri, "r");
int sampleSize = 1;
// Compute the closest power-of-two scale factor
// and pass that to sBitmapOptionsCache.inSampleSize, which will
// result in faster decoding and better quality
sBitmapOptionsCache.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(
fd.getFileDescriptor(), null, sBitmapOptionsCache);
int nextWidth = sBitmapOptionsCache.outWidth >> 1;
int nextHeight = sBitmapOptionsCache.outHeight >> 1;
while (nextWidth>w && nextHeight>h) {
sampleSize <<= 1;
nextWidth >>= 1;
nextHeight >>= 1;
}
sBitmapOptionsCache.inSampleSize = sampleSize;
sBitmapOptionsCache.inJustDecodeBounds = false;
Bitmap b = BitmapFactory.decodeFileDescriptor(
fd.getFileDescriptor(), null, sBitmapOptionsCache);
if (b != null) {
// finally rescale to exactly the size we need
if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
b.recycle();
b = tmp;
}
}
return b;
} catch (FileNotFoundException e) {
} finally {
try {
if (fd != null)
fd.close();
} catch (IOException e) {
}
}
}
return null;
}

Categories

Resources