I am trying to create a listview item with an imageview to the right of a textview.. lets say if the text was 3 lines i want the text of the first 2 lines to begin after the image view with some padding.. and the third line to be at the bottom of the image with no padding..
I used this code in my list adapter to do this..
TextView commenterName = (TextView) row
.findViewById(R.id.commenter_name);
commentText = (TextView) row.findViewById(R.id.tv);
ImageView commenterPhoto = (ImageView) row
.findViewById(R.id.commenterPhoto);
Display display = ((WindowManager) row.getContext()
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
FlowTextHelper.tryFlowText(commentsArray.get(pos).getComment(),
commenterPhoto, commentText, display, 0);
commenterName.setText(commentsArray.get(pos).getCommenter());
commentText.setTextColor(context.getResources().getColor(R.color.Black));
commentText.setGravity(Gravity.RIGHT);
this working fine.. but when scrolling the list view the text loses its padding and get over the image and out of the screen..
UPDATE:
This was the part causing the problem.. i put the else condition to set the default photo but the problem still exist..
String path = url.substring(url.lastIndexOf("/") + 1, url.length());
sd = new File(Environment.getExternalStorageDirectory()
+ Constants.user_images_path + path);
if (sd.exists()) {
Bitmap thumbnail = null;
try {
//File filePath = context.getFileStreamPath(url);
FileInputStream fi = new FileInputStream(sd);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
thumbnail = BitmapFactory.decodeStream(fi, null, options);
if(thumbnail != null)
holder.commenterPhoto.setImageBitmap(thumbnail);
else
holder.commenterPhoto.setBackgroundResource(R.drawable.commenter_default);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}
I don't know why this is happening.. Can you help me please?
OK.. I solved the problem by setting my imageView background in the condition of convertview in my getView() method before setting the tag of my holder.. just like this:
View row = convertView;
if (row == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = infalInflater.inflate(resource, null);
holder = new ViewHolder();
holder.commentText = (TextView) row.findViewById (R.id.tv);
holder.commenterPhoto = (ImageView) row.findViewById (R.id.commenterPhoto);
holder.commenterName = (TextView) row.findViewById (R.id.commenter_name);
holder.date = (TextView) row.findViewById (R.id.date);
holder.show = (ImageButton) row.findViewById(R.id.show);
String path = url.substring(url.lastIndexOf("/") + 1, url.length());
sd = new File(Environment.getExternalStorageDirectory()
+ Constants.user_images_path + path);
Bitmap thumbnail = null;
if (sd.exists()) {
try {
//File filePath = context.getFileStreamPath(url);
FileInputStream fi = new FileInputStream(sd);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
thumbnail = BitmapFactory.decodeStream(fi, null, options);
if(thumbnail != null)
holder.commenterPhoto.setImageBitmap(thumbnail);
else
holder.commenterPhoto.setBackgroundResource(R.drawable.commenter_default);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}else{
Toast.makeText(context, "No Image Found", Toast.LENGTH_LONG).show();
}
row.setTag(holder);
}
else{
holder = (ViewHolder) row.getTag();
}
Be careful with if...else blocks inside the getView() method in the adapter. If you set the background color in red of a LinearLayout inside an if statement you should put the "original" color in the else statement. This is caused by the ListView recycling views. You can see it better explained here
Try to add an "else" in the if(sd.exist()) block. I have supposed that this code is in getView().
Related
i have a grid view with 6 cells loading in adapter. when i click each cell,i am going to add image either from taking photos or choosing images from gallery.after selecting images, the grid view is showing empty only. though i set image in one cell,when go for another cell,the previous selection is gone. how to make it done?.. plea help me. if i am anything wrong , please guide me.
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.fpc_document_view, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
imageView = (ImageView) grid.findViewById(R.id.grid_image);
if (fileList.size() == 0) {
textView.setText(DOCUMENT_NAME_LIST[position].toString());
for (int i = 0; i <= 6; i++) {
imageView.setImageResource(R.mipmap.ic_add_document);
}
} else {
Bitmap bitmapResized = null;
for (int i = 0; i < fileList.size(); i++) {
if (!fileList.get(i).equals("")) {
System.out.println("fileList here ,,,," + fileList.get(i).toString());
Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ic_add_document);
bitmapResized = ((BitmapDrawable) drawable).getBitmap();
} else {
Uri selectedImageUri = Uri.fromFile(fileList.get(i));
bitmapResized = ImageRelatedStuff.convertURIToBitmap(selectedImageUri, mContext);
if (bitmapResized != null) {
Bitmap bitmapTemp = bitmapResized;
bitmapResized = null;
bitmapResized = ImageRelatedStuff.getResizedBitmap(bitmapTemp, 500, 500, 0);
}
}
imageView.setImageBitmap(ImageRelatedStuff.getRoundedCornerBitmap(bitmapResized, 15));
}
}
} else {
grid = convertView;
imageView = (ImageView) grid.findViewById(R.id.grid_image);
}
Change your code like this:
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.fpc_document_view, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
imageView = (ImageView) grid.findViewById(R.id.grid_image);
} else {
grid = convertView;
imageView = (ImageView) grid.findViewById(R.id.grid_image);
}
if (fileList.size() == 0) {
textView.setText(DOCUMENT_NAME_LIST[position].toString());
for (int i = 0; i <= 6; i++) {
imageView.setImageResource(R.mipmap.ic_add_document);
}
} else {
Bitmap bitmapResized = null;
for (int i = 0; i < fileList.size(); i++) {
if (!fileList.get(i).equals("")) {
System.out.println("fileList here ,,,," + fileList.get(i).toString());
Drawable drawable = mContext.getResources().getDrawable(R.mipmap.ic_add_document);
bitmapResized = ((BitmapDrawable) drawable).getBitmap();
} else {
Uri selectedImageUri = Uri.fromFile(fileList.get(i));
bitmapResized = ImageRelatedStuff.convertURIToBitmap(selectedImageUri, mContext);
if (bitmapResized != null) {
Bitmap bitmapTemp = bitmapResized;
bitmapResized = null;
bitmapResized = ImageRelatedStuff.getResizedBitmap(bitmapTemp, 500, 500, 0);
}
}
imageView.setImageBitmap(ImageRelatedStuff.getRoundedCornerBitmap(bitmapResized, 15));
}
}
Problem is when your convertView is not equals null you are not setting anything image on imageView. That is why on 2nd cell where convertView is null you are getting image while on previous cell which is not null you are getting nothing.
public class MyAdapter extends BaseAdapter{
private final int GRID_COUNT = 6;
// you need an array save bitmap with position
Bitmap[] bitmapArray;
public MyAdapter(){
bitmapArray = new Bitmap[GRID_COUNT];
}
#Override
public int getCount() {
return 6;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
// inflater your layout
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_image);
// get the bitmap in array by position
Bitmap bitmap = bitmapArray[position];
// when bitmap is null ,show default picture
if (bitmap == null){
imageView.setBackgroundResource(R.drawable.ic_default);
}else{
imageView.setImageBitmap(bitmap);
}
return convertView;
}
// activity or fragment use this method call adapter refresh
public void setBitmap(int position, Bitmap bitmap){
bitmapArray[position] = bitmap;
notifyDataSetChanged();
}
}
update my answer, hope help you
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.
I have a gridViewAdapter class that creates a view when there is none and I set an Id to it. Here is the getView() section of that class:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
view.setId(R.id.iconImageView_id);
}
if(checked == true){
isSdReadable();
Log.i("GridViewAdapter", "checkbox is checked");
} else {
Log.i("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
I have a ids.xml in the values section of my resources here:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="iconImageView_id"/>
</resources>
Then I am trying to get the imageView in another class here:
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = new FileOutputStream(file);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "The icon for use in gridView is saved");
out.close();
// Load back the image file to confirms it works
Bitmap bitmap = BitmapFactory.decodeFile( file.getAbsolutePath() );
ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id);
imageView1.setImageBitmap( bitmap );
Log.i("AppInfoAdapter", "The icon image has been set into the gridView");
}
But I get a NPE on this line:
imageView1.setImageBitmap( bitmap );
telling me that the imageView is returning null
Why is this? How can I fix this?
ADDED:
I am getting the imageView in another adapter class here:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
tvAppName.setText(entry.activityInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.activityInfo.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
final int DEST_IMAGE_WIDTH = 100;
final int DEST_IMAGE_HEIGHT = 100;
ApplicationInfo appInfo = mContext.getApplicationInfo();
Drawable appIcon = pm.getApplicationIcon(appInfo);
Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888);
// Creates a new canvas based on the image specification
// created just above.
Canvas canvas = new Canvas(appBmp);
// (optional) Fills the entire canvas
canvas.drawColor(Color.WHITE);
// You need to set bounds otherwise a 0,0 sized image would be drawn.
appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
appIcon.draw(canvas);
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = new FileOutputStream(file);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "The icon for use in gridView is saved");
out.close();
// Load back the image file to confirms it works
Bitmap bitmap = BitmapFactory.decodeFile( file.getAbsolutePath() );
ImageView imageView1 = (ImageView)v.findViewById(R.id.iconImageView_id);
imageView1.setImageBitmap( bitmap );
Log.i("AppInfoAdapter", "The icon image has been set into the gridView");
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
I am trying to make it so the the last row and first row of my listview will have rounded edges. Right now I am just trying to get the first row to have rounded edges. I able to accomplish this but a few random rows usually the 5-7 and 15 or 16th rows will be set to the rounded edges background too and I can't figure out why.
Here is the part of my adapter code where I try to set the rounded edges drawable:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.title);
holder.desc = (TextView) vi.findViewById(R.id.details);
holder.date = (TextView) vi.findViewById(R.id.date);
holder.price = (TextView) vi.findViewById(R.id.price);
holder.location = (TextView) vi.findViewById(R.id.location);
holder.newImage = (ImageView) vi.findViewById(R.id.savedNewItemsRibbon);
holder.rellay = (RelativeLayout) vi.findViewById(R.id.widget30);
//holder.image = (ImageView) vi.findViewById(R.id.thumb);
vi.setTag(holder);
}else{
holder = (ViewHolder) vi.getTag();
}
if(position == 0 && firstRow){
holder.rellay.setBackgroundResource(R.drawable.roundededges);
firstRow = false;
}else{
//vi.setBackgroundColor(Color.WHITE);
}
Log.d("MySQL", "COunt:"+position);
holder.price.setText(data.get(position).getPrice());
holder.location.setText(data.get(position).getUrl());
datasource = new PostDataSource(activity);
datasource.open();
if(datasource.checkIfNew(data.get(position).getTitle())){
holder.newImage.setVisibility(View.VISIBLE);
//vi.setBackgroundColor(Color.YELLOW);
}else{
holder.title.setTextColor(Color.BLACK);
}
holder.title.setText(data.get(position).getTitle());
holder.desc.setText(data.get(position).getDescription());
holder.date.setText(data.get(position).getPubDate());
holder.location.setText(data.get(position).getCity());
//holder.title.setText(data.get(0).getTitle());
//imageLoader.DisplayImage((data.get(position).getThumbnail()), activity,holder.image, 72, 72);
URL url = null;
try {
url = new URL((data.get(position).getThumbnail()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
/*
try {
//content = (InputStream)url.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(content , "src");
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
holder.image.setImageBitmap(Bitmap.createScaledBitmap(mIcon1, 72, 72, false));
*/
positionCount++;
return vi;
}
I've tried just using position==0 to set it to no avail. Any ideas?
This is most likely because the framework is passing a non-null convertView into your getView method, which happens to come from your first row.
The easiest fix is to unset the background resource for every row but the first:
if (position == 0){
holder.rellay.setBackgroundResource(R.drawable.roundededges);
} else {
holder.rellay.setBackgroundResource(0);
}
I'm using the following code to make a custom listview. I have to show image dynamically, so all the images are added to this in Linearlayout. The problem is that these dynamic images add multiple times. Below is the code of my getView().
LinearLayout fbpiclayout = null;
if (convertView == null)
vi = inflater.inflate(R.layout.popular_event_list, null);
fbpiclayout = (LinearLayout) vi
.findViewById(R.id.fbpic_layout);
ArrayList<String> list= mDbManager
.getAllValuesComingSoonFriendList(facebookEventList
.get(position).getEventId());
int height = 0;
for(int i=0;i<list.size();i++)
{
if(i<3)
{
String friendPics = "http://graph.facebook.com/"
+ list.get(i)
+ "/picture?type=large";
Log.d("Friends","list no "+i+" "+mDbManager
.getFacebookFriendName(list.get(i)));
ImageView fbFriendimage = new ImageView(getActivity());
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
vp.setMargins(3, 0, 3, 3);
fbFriendimage.setLayoutParams(vp);
fbFriendimage.setAdjustViewBounds(true);
fbFriendimage.getLayoutParams().height = height;
fbFriendimage.getLayoutParams().width = width_iv;
fbFriendimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
// image.setImageBitmap(bm);
imageLoader.DisplayImage(friendPics, fbFriendimage);
fbpiclayout.addView(fbFriendimage, vp);
}
}
Kindly suggest me on that issue.
Thanks in Advance.
Try the following code:
LinearLayout fbpiclayout = null;
if (convertView == null)
vi = inflater.inflate(R.layout.popular_event_list, null);
fbpiclayout = (LinearLayout) vi
.findViewById(R.id.fbpic_layout);
//if the convertView was not null it would have the child view you added the
// last time liner layout was used. So remove the added child view.
fbpiclayout.removeAllViews();
ArrayList<String> list= mDbManager
.getAllValuesComingSoonFriendList(facebookEventList
.get(position).getEventId());
int height = 0;
for(int i=0;i<list.size();i++)
{
if(i<3)
{
String friendPics = "http://graph.facebook.com/"
+ list.get(i)
+ "/picture?type=large";
Log.d("Friends","list no "+i+" "+mDbManager
.getFacebookFriendName(list.get(i)));
ImageView fbFriendimage = new ImageView(getActivity());
LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
vp.setMargins(3, 0, 3, 3);
fbFriendimage.setLayoutParams(vp);
fbFriendimage.setAdjustViewBounds(true);
fbFriendimage.getLayoutParams().height = height;
fbFriendimage.getLayoutParams().width = width_iv;
fbFriendimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
// image.setImageBitmap(bm);
imageLoader.DisplayImage(friendPics, fbFriendimage);
fbpiclayout.addView(fbFriendimage, vp);
}
}
EDIT1: Try to use smart image view http://loopj.com/android-smart-image-view/ to improve performance....
don't use that loop. Put that list's size in getCount(). It will work properly