GridView CustomAdapter loads one imagebutton only - java

I have setup a custom gridView adapter, which looks like this
public class ImageAdapter extends BaseAdapter {
String[] urls = new String[10];
//....some code
class MyTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... arg0) {
//perform a get request and fill up the "urls" array by 10 values..
return null;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
new MyTask().execute(); //execute AsyncTask
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView = null;
if (convertView == null) {
gridView = new View(context);
// get layout from grid_layout.xml
gridView = inflater.inflate(R.layout.grid_layout, null);
final ImageButton grid_art = (ImageButton) gridView.findViewById(R.id.grid_art);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
imageloader = ImageLoader.getInstance();
imageloader.init(config);
imageloader.loadImage(blog_urls[position], new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
grid_art.setImageBitmap(loadedImage);
}
});
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return urls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
the adapter loads 10 image url's in an asynctask and stores it into the urls array.
I am using universal image loader to download and load images found at the urls into an imagebutton as background,
however only one imagebutton gets the background and the rest are blank.

Change your getView method like this:
public View getView(int position, View convertView, ViewGroup parent) {
new MyTask().execute(); // execute AsyncTask
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View gridView = null;
MyView myView;
if (convertView == null) {
myView= new MyView();
//gridView = new View(context);
// get layout from grid_layout.xml
convertView = inflater.inflate(R.layout.grid_layout, null);
myView.grid_art = (ImageButton) convertView.findViewById(R.id.grid_art);
convertView.setTag(myView);
} else {
myView= (MyView) convertView.getTag();
//gridView = (View) convertView;
}
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).build();
imageloader = ImageLoader.getInstance();
imageloader.init(config);
imageloader.loadImage(blog_urls[position],
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
myView.grid_art.setImageBitmap(loadedImage);
}
});
return convertView;
}
Where MyView is:
class MyView {
ImageButton grid_art;
}
Hope it helps...

Related

Listview lag when scrolling, and crash when add item

I have a custom listview with a button to add more elements
but when I add and element the app crash, but when I restart I find that the element is added, (rarely it doesn't crash)
And i
I use custom adapter
class CustomAdapter extends BaseAdapter {
ArrayList<ListItem> listItems = new ArrayList<ListItem>();
CustomAdapter(ArrayList<ListItem> list){
this.listItems = list;
}
#Override
public int getCount() {
return listItems.size();
}
#Override
public Object getItem(int position) {
return listItems.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.list_item,null);
TextView name = (TextView) view.findViewById(R.id.name);
TextView lastm = (TextView) view.findViewById(R.id.last);
TextView time = (TextView) view.findViewById(R.id.time);
CircleImageView pic= (CircleImageView) view.findViewById(R.id.pic);
name.setText(listItems.get(i).name);
lastm.setText(listItems.get(i).lastm);
time.setText(listItems.get(i).time);
Bitmap bmp = BitmapFactory.decodeByteArray(listItems.get(i).pic,0,listItems.get(i).pic.length);
pic.setImageBitmap(bmp);
return view;
}
}
and when I add an element the app crashs
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText=(EditText) mView.findViewById(R.id.name);
String name=editText.getText().toString();
boolean result=myDataBase.insertData(imageViewToByte(img),name,"no messages yet","");
if (result) {
Toast.makeText(Main2Activity.this, "Saved in DATABASE", Toast.LENGTH_SHORT).show();
viewLastData();
dialog.dismiss();
}
If your ListView lags it's because you used wrap_content for the listView's layout_height. It forces your ListView to count all the items inside and it has a huge performance impact.
So replace wrap_content by match_parent to avoid those lags.
EDIT: Use a ViewHolder pattern too in your Adapter, see this link.
Here is an example:
// ViewHolder Pattern
private static class ViewHolder {
TextView name, status;
}
#Override #NonNull
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater vi = LayoutInflater.from(getContext());
convertView = vi.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text_name);
holder.status = (TextView) convertView.findViewById(R.id.another_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Then do the other stuff with your item
// to populate your listView
// ...
return convertView
}

ListView items reordering and repeating using baseadapter

I am trying to implement a listview that displays a list of directories. and under each directory is a gridview with associated adapter (shown below) showing a list of image thumbnails (see below image). I have it working great except whenever the list item is off the screen then brought back on screen, the images are reloaded. I am using an asynctask to download the thumbnails and replace the placeholder image for each imageview so it is not acceptable that everytime an item is offscreen, all of its thumbnails are downloaded again. Does anyone have an example of this type of implementation (gridview adapter within a listview adapter) where the imageview (or images) are stored? What is the proper way to do this?
Thanks in advance for your help.
Gallery Adapter
public class GalleryAdapter extends BaseAdapter {
private Context mContext;
ArrayList<GalleryItem> GalleryList;
//MediaAdapter adapter;
public GalleryAdapter(Context c,ArrayList<GalleryItem> l) {
mContext = c;
GalleryList = l;
}
public int getCount() {
return GalleryList.size();
}
public Object getItem(int position) {
return GalleryList.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
GalleryViewHolder viewHolder = null;
if(convertView==null){
// inflate the layout
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.gallery_item, parent, false);
viewHolder = new GalleryViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.folder_settings = (ImageView) convertView.findViewById(R.id.folder_settings);
viewHolder.mediaGrid = (GridView) convertView.findViewById(R.id.imagegrid);
viewHolder.gridHolder = (LinearLayout) convertView.findViewById(R.id.gridholder);
convertView.setTag(viewHolder);
}
else{
viewHolder = (GalleryViewHolder) convertView.getTag();
}
viewHolder.title.setText(GalleryList.get(position).getTitle());
//Formatting the gridView to fit the screen dim.
ImageTools mWidth = new ImageTools(mContext);
viewHolder.mediaGrid.setColumnWidth(mWidth.imageSize());
int rows = (int) Math.ceil((GalleryList.get(position).getMedia().size() / mWidth.columnNumber)+1);
LinearLayout.LayoutParams labelLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, mWidth.imageSize()*rows);
viewHolder.gridHolder.setLayoutParams(labelLayoutParams);
viewHolder.mediaGrid.setLayoutParams(labelLayoutParams);
viewHolder.mediaGrid.setMinimumHeight(mWidth.imageSize()*rows);
//Set Adapter for image views
viewHolder.mediaGrid.setAdapter(new MediaAdapter(convertView.getContext(),GalleryList.get(position).getMedia()));
viewHolder.folder_settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Dialogs.createListDialog(mContext,"Folder Actions", R.array.gallery_action_array).show();
}
});
viewHolder.mediaGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
}
});
return convertView;
}
private class GalleryViewHolder {
private TextView title;
private ArrayList<ImageView> imageList;
private GridView mediaGrid;
private ImageView folder_settings;
private LinearLayout gridHolder;
private int position;
}
}
Media Adapter
public class MediaAdapter extends BaseAdapter {
private Context mContext;
ArrayList<MediaItem> mediaitems;
public MediaAdapter(Context c,ArrayList<MediaItem> l) {
mContext = c;
mediaitems = l;
}
public int getCount() {
return mediaitems.size();
}
public Object getItem(int position) {
return mediaitems.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setImageResource(R.drawable.loading);
imageView.setTag(R.integer.path,mediaitems.get(position).getPath().toString());
imageView.setTag(R.integer.fullsize,"false");
imageView.setTag(R.integer.parentpath,mediaitems.get(position).getParentPath().toString());
imageView.setTag(R.integer.index , String.valueOf(position));
try {
new thumbDownload(mContext).execute(imageView);
} catch (DbxException e) {
e.printStackTrace();
}
ImageTools mWidth = new ImageTools(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(mWidth.imageSize(), mWidth.imageSize()));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
//imageView.setImageBitmap(mediaitems.get(position).getBitmap());
return imageView;
}
}
Try with this..may be its silly way, but its worked for me. Just add a line of code inside your method like this for gallery adapter:
public View getView(int position, View convertView, ViewGroup parent) {
GalleryViewHolder viewHolder = null;
// Add this line.
convertView = null;
if(convertView==null){
// inflate the layout
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.gallery_item, parent, false);
viewHolder = new GalleryViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.folder_settings = (ImageView) convertView.findViewById(R.id.folder_settings);
viewHolder.mediaGrid = (GridView) convertView.findViewById(R.id.imagegrid);
viewHolder.gridHolder = (LinearLayout) convertView.findViewById(R.id.gridholder);
convertView.setTag(viewHolder);
}
else{
viewHolder = (GalleryViewHolder) convertView.getTag();
}
// rest of your code
}
You can use StickyGridHeaders to implement your UI and Android-Universal-Image-Loader for flexible asynchronous image loading.
StickyGridHeaders is an Android library that provides a GridView that shows items in sections with headers. By default the section headers stick to the top like the People app in Android 4.x but this can be turned off.
Android-Universal-Image-Loader aims to provide a reusable instrument for asynchronous image loading, caching and displaying.
I ended up Using a HashMap<String,Bitmap> to store the images once they were downloaded. I made the hashMap static in my mediaAdapter so I could add the bitmap from my asynctask when it was downloaded. Then in my media Adapter getView(), I added a if statement to check if the image had already been downloaded. If it had, I used setImageBitmap(myHash.get(key)).

my images get shuffled or changed when i scroll in list view

my images get shuffled or changed when i scroll in list view.......
Images get shuffled when i scroll down and keep on changing own its own...............
public class CustomListAdapter extends BaseAdapter {
private ArrayList<NewsItem> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<NewsItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.activity_list_search, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewsItem newsItem = (NewsItem) listData.get(position);
holder.headlineView.setText(newsItem.getHeadline());
holder.reporterNameView.setText("Model: " + newsItem.getReporterName());
holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reporterNameView;
TextView reportedDateView;
ImageView imageView;
}
}
The problem is very generic for new Android developers.
Your ImageDownloaderTask should take care of whether the downloaded image should still be posted on screen.
For example, after ImageDownloaderTask finishes one image downloading task (e.g. for index 15), it should make sure the 15th item is still displaying on screen. Since ListView is reusing all the item views, if you directly set the bit map to the original referenced view, your imageview will be shuffled.

how to write code for onitemClickListener for customized listview using BaseAdapter?

here is the code for custom listview using BaseAdapter in android its working fine:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<TaskClass> _listData;
Context _c;
public CustomListAdapter(Context context, ArrayList<TaskClass> listData) {
_listData = listData;
_c = context;
}
#Override
public int getCount() {
return _listData.size();
}
#Override
public Object getItem(int position) {
return _listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
return v;
}
}
and in activity i m binding listview with custom adapter :
listViewInstance.setAdapter(new CustomListAdapter(getApplicationContext(),taskClasslistInstance));
where "taskclasslistinstance" is my arraylist conatining data from DB its working fine
now i need to write function for listitemclick so that when user click on any listitem i can get rowid of that listitem record from Database.so after getting rowwid I can delete records from listview and from db and can edit informations
Well, we don't know about your TaskClass, but I expect you want something like this:
listViewInstance.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
TaskClass taskClass = taskClasslistInstance.get(pos);
Log.d(TAG, "Clicked on: " + taskClass)
// Do stuff with taskClass
}});
Here a small example from my project:
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LazyAdapterAlbum(getActivity(), songs);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), AlbumActivity.class);
Bundle args = new Bundle();
args.putString(AlbumActivity.ALBUM_NAME, adapter.getItem(position).getName());
i.putExtras(args);
startActivity(i);
}
});
You have to set an onClickListener on your ListView.
you can also set in getView method like below:
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform an action when this list item is clicked
}
});
return v;
}

using gridview with images in android

this is the problematic code:
public class Level1 extends Activity {
int[] logos = {
R.drawable.arutz8,
R.drawable.channel1,
R.drawable.doctor_gav,
R.drawable.foxgroup3,
R.drawable.careline,
R.drawable.golfnew,
R.drawable.haaretz,
R.drawable.hafenix,
/*R.drawable.hando,
R.drawable.bankleumi,
R.drawable.jerusalempostred,
R.drawable.laisha,
R.drawable.logo,
R.drawable.logodelta,
R.drawable.maariv,
R.drawable.pelephone,
R.drawable.ravbariah,
R.drawable.renuar,
R.drawable.reshet_tv,
R.drawable.sano,
R.drawable.shilav,
R.drawable.sport5,
R.drawable.srigamish,
R.drawable.steimatzky,
R.drawable.superpharm,
R.drawable.supersal,
R.drawable.tambur,
R.drawable.tzometsfarim,
R.drawable.walla,
R.drawable.yediot,*/
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
ListAdapter adapter = (new ArrayAdapter<Integer>(this, R.layout.level1));
GridView grid = (GridView) findViewById(R.id.gridview1);
grid.setAdapter(new ImageAdapter(this));
}
private class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
//---returns the number of images---
public int getCount() {
return logos.length;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(90, 90));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(logos[position]);
return imageView;
}
}
}
This program works perfectly as long as the size of all images is about 60px per each image. The problem in that size of image is that every image got constricted and its ugli!.
I tried to use in bigger images and for some reason only the first five images appears on the screen and when i try to load the rest images, the app crashes.
I thought that happens because of the size of the images but than i realized that all the images are in the same big size and still 5 of them were drawn on the screen.
Any ideas?
Those are the logs from logCat:
logs
and this is the result when i press on the level 1 button:
result
There is a problem in your public View getView(...) method in your ImageAdapter.
When the convertView == null, you never link the convertView to your imageView. So there will be a problem in the else-statement.
You can do this in two ways:
By defining your ImageView in code like you did, in your case this will be the best choice:
ImageView imageView = (ImageView) convertView;
if (convertView == null) {
convertView = new ImageView(context);
imageView = (ImageView) convertView;
// Set other parameters
}
// Set resource
return convertView;
By defining your layout in a xml-layout file an using a layout inflater:
Handler handler;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(yourLayoutResourceId, parent, false);
handler = new Handler();
handler.itemIV = (ImageView) convertView.findViewById(imageViewLayoutId);
convertView.setTag(handler);
} else {
handler = (Handler) convertView.getTag();
}
handler.imageView.setImageResource(...);
return convertView;
Where yourLayoutResourceId is the id of the created xml-layout file (R.layout.exmaple), and imageViewLayoutId is the id of your imaeView in the layout (R.id.exmapleIV).
As last step define an inner class Handler in your ImageAdapter:
class Handler {
ImageView imageView;
}
Good luck!
Have nice development.
Kr

Categories