Load images to listview dynamically - android

I'm having 4 groups of contacts(Type1,2,3,None). i want to load different images 3 for Type1,2,3, if contact belong to None then listview shouldn't contain any image.. This is my code
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
// return super.getView(position, convertView, parent);
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ContactsListActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.contacts_list_row_view, null);
}
try {
contactsData = (ContactsItem) getItem(position);
} catch (Exception e) {
}
if (null != contactsData){
final CheckBox contactsSelectedCheck = (CheckBox) v.findViewById(R.id.contact_selected_check);
TextView contactNameText = (TextView) v.findViewById(R.id.contact_name_text);
TextView contactNumberText = (TextView) v.findViewById(R.id.contact_number_text);
ImageView contactImage = (ImageView) v.findViewById(R.id.contact_image);
contactNameText.setText(contactsData.getContactName());
contactNumberText.setText(contactsData.getContactNumber());
if(contactNameText != null && contactNumberText != null){
if(contactsData.getContactProfileType() == DBConstants.TYPE_1){ contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_1));
} else if(contactsData.getContactProfileType() == DBConstants.TYPE_2){ contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_2));
} else if(contactsData.getContactProfileType() == DBConstants.TYPE_3){ contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_3));
}else{
}
}
if (selectedContactsTable.containsKey(contactsData.getContactNumber())) {
contactsSelectedCheck.setChecked(true);
} else {
contactsSelectedCheck.setChecked(false);
}
contactsSelectedCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (contactsSelectedCheck.isChecked()) {
LinearLayout r_layout = (LinearLayout) v.getParent();
TextView contactName = (TextView) r_layout.getChildAt(1);
TextView contactNumber = (TextView) r_layout.getChildAt(2);
selectedContactsTable.put(contactNumber.getText().toString(), contactName.getText().toString());
}else{
LinearLayout r_layout = (LinearLayout) v.getParent();
TextView contactNumber = (TextView) r_layout.getChildAt(2);
selectedContactsTable.remove(contactNumber.getText().toString());
}
}
});
}
return v;
}
}
Problem with this is if i assign some contacts to Type 1 corresponding images for this type loaded correctly but when i scroll the list same image will be loaded to some unassigned also, is there any problem with my code please tell me

do the class Holder that the other question suggested. And do the Holder for every single adapter you ever create.
To answer your question, try this edit:
contactImage.setVisibility(View.Visible);
if(contactsData.getContactProfileType() == DBConstants.TYPE_1){ contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_1));
} else if(contactsData.getContactProfileType() == DBConstants.TYPE_2){ contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_2));
} else if(contactsData.getContactProfileType() == DBConstants.TYPE_3){ contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_3));
}else{
contactImage.setVisibility(View.GONE);
}

Try to make a holder class for your views. Then in the if(v==null) block, you can use setTag() and use getTag() in the else block. Here's some code.
public static class ViewHolder {
TextView contactNameText;
TextView contactNumberText;
ImageView contactImage;
}
This is a holder class that contains your views. The first part of the getView() method should then look like this:
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ContactsListActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.contacts_list_row_view, null);
holder = new ViewHolder();
holder.contactNameText = (TextView) v.findViewById(R.id.contact_name_text);
holder.contactNumberText = (TextView) v.findViewById(R.id.contact_number_text);
holder.contactImage = (ImageView) v.findViewById(R.id.contact_image);
v.setTag(holder);
}
else{
holder = (ViewHolder) v.getTag();
}
try {
contactsData = (ContactsItem) getItem(position);
} catch (Exception e) {
}
if (null != contactsData){
final CheckBox contactsSelectedCheck = (CheckBox) v.findViewById(R.id.contact_selected_check);
holder.contactNameText.setText(contactsData.getContactName());
holder.contactNumberText.setText(contactsData.getContactNumber());
if(contactNameText != null && contactNumberText != null){
if(contactsData.getContactProfileType() == DBConstants.TYPE_1){ holder.contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_1));
} else if(contactsData.getContactProfileType() == DBConstants.TYPE_2){ holder.contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_2));
} else if(contactsData.getContactProfileType() == DBConstants.TYPE_3){ holder.contactImage.setImageDrawable(getResources().getDrawable(R.drawable.icon_3));
}else{
}
}

Related

ImageView of a item in the list shuffled when scrolling

I have a list,When user clicks an item in that list three buttons will be showed under that item (namely Yes,No and Maybe) so user may select any one of the buttons and that response(as 1,2,3 for yes,no,maybe) will be saved.In adapter's getView just we retrieve that response and showing imageView on all list item's row
setting image in ArrayAdapter's getView
EventUserRelationMO eventUserRelationMO1 =new EventUserRelationMO();
eventId1 = eventUserRelationMO1.getEventId();
if (eventId1 == eventIdPosition) {
long eventUserId = eventUserRelationMO1.getEventUserId();
int isAttending = eventUserRelationMO1.getIsAttending();
if (isAttending == 1) {
holder.no.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
} else if (isAttending == 2) {
holder.yes.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
} else if (isAttending == 3) {
holder.yes.setVisibility(View.GONE);
holder.no.setVisibility(View.GONE);
} else {
holder.yes.setVisibility(View.GONE);
holder.no.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
}
}
this is perfectly works but when i have more number of items in the list image is not visible for corresponding item/shuffled while scrolling
private class UserOccasions extends ArrayAdapter<EventMO> {
private ArrayList<EventMO> eventMOs;
LayoutInflater mInflater;
UserOccasions(Context context, int textViewResourceId,
ArrayList<EventMO> eventMOs) {
super(context, textViewResourceId, eventMOs);
this.eventMOs = new ArrayList<EventMO>();
this.eventMOs.addAll(eventMOs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public class ViewHolder {
TextView eventNameTxtV;
TextView eventPlaceTxtV;
TextView sendByNameTxtv;
ImageView yes;
ImageView no;
ImageView maybe;
}
#Override
public int getCount() {
return eventMOs.size();
}
/*#Override
public Object getItem(int position) {
return position;
}*/
#Override
public long getItemId(int position) {
return 0;
}
// show list values name and mobile number in contact page
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final EventMO eventMO = eventMOs.get(position);
if (null == convertView) {
convertView = mInflater.inflate(R.layout.invitation, null);
holder = new ViewHolder();
holder.eventNameTxtV = (TextView) convertView.findViewById(R.id.invitationTitle);
holder.eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitationCheckBox);
holder.sendByNameTxtv = (TextView) convertView.findViewById(R.id.sendByName);
holder.yes = (ImageView) convertView.findViewById(R.id.yes);
holder.no = (ImageView) convertView.findViewById(R.id.no);
holder.maybe = (ImageView) convertView.findViewById(R.id.maybe);
eventUserRelationMOs = eventMO.getEventUserRelationBOs();
sendUserMO = eventMO.getUserBO();
eventIdPosition = eventMO.getEventId();
for (EventUserRelationMO eventUserRelationMO1 : eventUserRelationMOs) {
eventId1 = eventUserRelationMO1.getEventId();
if (eventId1 == eventIdPosition) {
long eventUserId = eventUserRelationMO1.getEventUserId();
int isAttending = eventUserRelationMO1.getIsAttending();
if (isAttending == 1) {
holder.no.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
} else if (isAttending == 2) {
holder.yes.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
} else if (isAttending == 3) {
holder.yes.setVisibility(View.GONE);
holder.no.setVisibility(View.GONE);
} else {
holder.yes.setVisibility(View.GONE);
holder.no.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
}
}
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.yes.setTag(eventMOs.get(position));
holder.no.setTag(eventMOs.get(position));
holder.maybe.setTag(eventMOs.get(position));
holder.eventNameTxtV.setText(eventMOs.get(position).getText());
holder.eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
holder.sendByNameTxtv.setText(sendUserMO.getUserName());
View v = convertView.findViewById(R.id.invitation_single);
v.getRootView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent occasionAct = new Intent(InvitationFragment.this.getActivity(), InvitationActivity.class);
occasionAct.putExtra("eventMO", eventMO);
occasionAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(occasionAct);
}
});
return convertView;
}
this is my full adapter code any one help me to maintain corresponding imageView for each item in the list when scrolling
ListView works by recycling the views.To know more on how it works you can have a look at this (http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/).
The problem with the code is that the image is being set only once when convertView is null. When you scroll the list, the list view passes a recycled row into the getView function (this is when the convertView will not be null). In this case you are not setting the ImageView.
I have modified the code, this should work
// show list values name and mobile number in contact page
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final EventMO eventMO = eventMOs.get(position);
if (null == convertView) {
convertView = mInflater.inflate(R.layout.invitation, null);
holder = new ViewHolder();
holder.eventNameTxtV = (TextView) convertView.findViewById(R.id.invitationTitle);
holder.eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitationCheckBox);
holder.sendByNameTxtv = (TextView) convertView.findViewById(R.id.sendByName);
holder.yes = (ImageView) convertView.findViewById(R.id.yes);
holder.no = (ImageView) convertView.findViewById(R.id.no);
holder.maybe = (ImageView) convertView.findViewById(R.id.maybe);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
eventUserRelationMOs = eventMO.getEventUserRelationBOs();
sendUserMO = eventMO.getUserBO();
eventIdPosition = eventMO.getEventId();
for (EventUserRelationMO eventUserRelationMO1 : eventUserRelationMOs) {
eventId1 = eventUserRelationMO1.getEventId();
if (eventId1 == eventIdPosition) {
long eventUserId = eventUserRelationMO1.getEventUserId();
int isAttending = eventUserRelationMO1.getIsAttending();
if (isAttending == 1) {
holder.no.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
} else if (isAttending == 2) {
holder.yes.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
} else if (isAttending == 3) {
holder.yes.setVisibility(View.GONE);
holder.no.setVisibility(View.GONE);
} else {
holder.yes.setVisibility(View.GONE);
holder.no.setVisibility(View.GONE);
holder.maybe.setVisibility(View.GONE);
}
}
}
holder.yes.setTag(eventMOs.get(position));
holder.no.setTag(eventMOs.get(position));
holder.maybe.setTag(eventMOs.get(position));
holder.eventNameTxtV.setText(eventMOs.get(position).getText());
holder.eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
holder.sendByNameTxtv.setText(sendUserMO.getUserName());
View v = convertView.findViewById(R.id.invitation_single);
v.getRootView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent occasionAct = new Intent(InvitationFragment.this.getActivity(), InvitationActivity.class);
occasionAct.putExtra("eventMO", eventMO);
occasionAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(occasionAct);
}
});
return convertView;
}

How to fix repeating items when scrolling in android listview?

I have a custom adapter class which extended by ArrayAdapter. I set the adapter to a listview in my activity. In my objects list I have 8 objects. In the listview shows 5 objects when it's loading(when i'm scrolling the listview it has 3 more data to show). After I scroll the listview last 3 objects are showing same as 1st 3 objects. Here's the code what I tried.
Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
final MenuItem listItem = objects.get(position);
holder = new Holder();
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.menu_list_item, parent);
holder.textViewItemName = (TextView) convertView.findViewById(R.id.textViewItemName);
holder.textViewItemName.setText(listItem.getItemName());
holder.textViewPrice = (TextView) convertView.findViewById(R.id.textViewPrice);
holder.textViewPrice.setText("$ ".concat(String.valueOf(listItem.getItemPrice())));
holder.imageView = (ImageView) convertView.findViewById(R.id.imageViewItem);
holder.buttonPlus = (ButtonRectangle) convertView.findViewById(R.id.buttonPlus);
holder.cartQtyTextView = (TextView) convertView.findViewById(R.id.textViewCartQty);
// Check & Set
if (holder.buttonPlus != null) {
holder.buttonPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (holder.cartQtyTextView != null) {
holder.cartQtyTextView.setText("" + ++i);
}
}
});
}
holder.buttonPlus.setBackgroundColor(Color.WHITE);
holder.buttonPlus.setTextColor(Color.parseColor("#333333"));
holder.buttonMinus = (ButtonRectangle) convertView.findViewById(R.id.buttonMinus);
// Check & Set
if (holder.buttonMinus != null) {
holder.buttonMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (holder.cartQtyTextView != null) {
holder.cartQtyTextView.setText("" + --i);
}
}
});
}
holder.buttonMinus.setBackgroundColor(Color.WHITE);
holder.buttonMinus.setTextColor(Color.parseColor("#333333"));
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
return convertView;
}
Activity
listViweMenu.destroyDrawingCache();
listViweMenu.setVisibility(ListView.INVISIBLE);
listViweMenu.setVisibility(ListView.VISIBLE);
menuListAdapter.notifyDataSetChanged();
List<uk.co.bapos.android.baposwaiter.data.models.menu.MenuItem> itemsList
= MenuItemController.fetchAllCategoryItems(this, String.valueOf(new ArrayList<>(menuItemData.entrySet()).get(position).getValue()));
listDataMenu.clear();
listDataMenu.addAll(itemsList);
How may I fix this?
You are calling getTag(), setTag() and setting the data in wrong place. Try this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new Holder();
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.menu_list_item, parent);
holder.textViewItemName = (TextView) convertView.findViewById(R.id.textViewItemName);
holder.textViewPrice = (TextView) convertView.findViewById(R.id.textViewPrice);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageViewItem);
holder.buttonPlus = (ButtonRectangle) convertView.findViewById(R.id.buttonPlus);
holder.cartQtyTextView = (TextView) convertView.findViewById(R.id.textViewCartQty);
holder.buttonMinus = (ButtonRectangle) convertView.findViewById(R.id.buttonMinus);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
final MenuItem listItem = objects.get(position);
holder.textViewItemName.setText(listItem.getItemName());
holder.textViewPrice.setText("$ ".concat(String.valueOf(listItem.getItemPrice())));
// Check & Set
if (holder.buttonPlus != null) {
holder.buttonPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (holder.cartQtyTextView != null) {
holder.cartQtyTextView.setText("" + ++i);
}
}
});
}
holder.buttonPlus.setBackgroundColor(Color.WHITE);
holder.buttonPlus.setTextColor(Color.parseColor("#333333"));
// Check & Set
if (holder.buttonMinus != null) {
holder.buttonMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (holder.cartQtyTextView != null) {
holder.cartQtyTextView.setText("" + --i);
}
}
});
}
holder.buttonMinus.setBackgroundColor(Color.WHITE);
holder.buttonMinus.setTextColor(Color.parseColor("#333333"));
}
return convertView;
}
After getting all the id's of views use setTag() and if view is not null use getTag() to get all id's back. Only after that set data to the views.
In Activity :
ArrayAdapter adapter = myAdapter();//pass arraylist or data to adapter here
listview.setAdapter(adapter);
Try this.
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.menu_list_item, parent);
//initializing your view elements
convertView.setTag(holder);
}
else{
holder = (Holder) convertView.getTag();
}
// do other stuff after if-else, setting the values to view elements
You need to understand why holder is used and set as tag.
If convertView is not null means you will be reusing the view (this improves performance and saves memory)
Now what you are doing when it is not null is
holder = (Holder) convertView.getTag();
and returning sameConvertView so you get the same view
What you need to do after getting holder tag is change the view information using holder
Eg holder.textViewItemName.setText(listItem.getItemName());//Needs to get the current list item based on position.
#Override public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
final MenuItem listItem = objects.get(position);
holder = new Holder(); LayoutInflater inflater = (LayoutInflater) this.context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.menu_list_item, parent);
holder.textViewItemName = (TextView)convertView.findViewById(R.id.textViewItemName);
holder.textViewPrice = (TextView) convertView.findViewById(R.id.textViewPrice);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageViewItem);
holder.buttonPlus = (ButtonRectangle) convertView.findViewById(R.id.buttonPlus);
holder.cartQtyTextView = (TextView) convertView.findViewById(R.id.textViewCartQty);
holder.buttonMinus = (ButtonRectangle) convertView.findViewById(R.id.buttonMinus);
convertView.setTag(holder); }
else
{
holder = (Holder) convertView.getTag();
}
holder.textViewItemName.setText(listItem.getItemName());
holder.textViewPrice.setText("$ ".concat(String.valueOf(listItem.getItemPrice()))); // Check & Set if (holder.buttonPlus != null) {
holder.buttonPlus.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v)
{
int i = 0; if (holder.cartQtyTextView != null)
{
holder.cartQtyTextView.setText("" + ++i);
}
}
});
}
holder.buttonPlus.setBackgroundColor(Color.WHITE);
holder.buttonPlus.setTextColor(Color.parseColor("#333333"));
// Check & Set if (holder.buttonMinus != null)
{
holder.buttonMinus.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v)
{
int i = 0; if (holder.cartQtyTextView != null)
{
holder.cartQtyTextView.setText("" + --i);
}
} }); }
holder.buttonMinus.setBackgroundColor(Color.WHITE);
holder.buttonMinus.setTextColor(Color.parseColor("#333333"));
return convertView;
}

ListView first Item overlaid

My ListView displays in first Item something else as the rest of the ListView
The Problem is, that it replaces the first item instead of taking a own position.
Example how it has to be:
A (diferent to the others)
B
B
B
How it is:
A (B Overlaid by A)
B
B
As you can see, one B is missing because it is overlaid by A.
Here is the Code. I wrote my own CustomAdapter:
#Override
public int getCount() {
if (taskItems.size() + 1 >= 0)
return taskItems.size();
return 0;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView taskTitleTextView;
public TextView taskObjectTextView;
public TextView taskLocationTextView;
public ImageView taskImageImageView;
}
public static class ViewHolderProjects {
public TextView projectTitelTextView;
public TextView projectInfoTextView;
public TextView projectDeadline;
public ImageView projectImageImageView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolderProjects holderProjects;
if (position == 0) {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_item_projects, null);
holderProjects = new ViewHolderProjects();
holderProjects.projectTitelTextView = (TextView) vi.findViewById(R.id.projectTitle);
holderProjects.projectInfoTextView = (TextView) vi.findViewById(R.id.projectInfo);
holderProjects.projectImageImageView = (ImageView) vi.findViewById(R.id.projectImage);
holderProjects.projectDeadline = (TextView) vi.findViewById(R.id.projectdeadline);
vi.setTag(holderProjects);
} else {
holderProjects = (ViewHolderProjects) vi.getTag();
}
if (projectMap.size() <= 0) {
holderProjects.projectInfoTextView.setText("Keine Infos");
holderProjects.projectTitelTextView.setText("Kein Titel");
} else {
if (projectMap.get(position).containsKey("project_company_image")) {
if (projectMap.get(position).get("project_company_image").getBytes().length == 0) {
holderProjects.projectTitelTextView.setText(jobMap.get(position).get("job_subject"));
holderProjects.projectDeadline.setText(jobMap.get(position).get("job_deadline"));
return vi;
}
Bitmap bm = Bitmap.createBitmap(base64EncodeDecode.decodeBase64(projectMap.get(position).get("project_company_image")));
holderProjects.projectTitelTextView.setText(jobMap.get(position).get("job_subject"));
holderProjects.projectDeadline.setText(jobMap.get(position).get("job_deadline"));
holderProjects.projectImageImageView.setImageBitmap(bm);
}
}
} else {
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.list_item_tasks, null);
holder = new ViewHolder();
holder.taskTitleTextView = (TextView) vi.findViewById(R.id.taskTitle);
holder.taskObjectTextView = (TextView) vi.findViewById(R.id.taskObject);
holder.taskLocationTextView = (TextView) vi.findViewById(R.id.taskLocation);
holder.taskImageImageView = (ImageView) vi.findViewById(R.id.taskImage);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (taskItems.size() <= 0) {
holder.taskTitleTextView.setText("Kein Titel");
holder.taskObjectTextView.setText("Kein Objekt");
holder.taskLocationTextView.setText("Kein Standort");
} else {
if (taskItems.get(position).containsKey("object_image")) {
if (taskItems.get(position).get("object_image").getBytes().length == 0) {
holder.taskTitleTextView.setText(taskItems.get(position).get("task_headline"));
holder.taskObjectTextView.setText(taskItems.get(position).get("object_name"));
holder.taskLocationTextView.setText(taskItems.get(position).get("object_location"));
return vi;
}
}
Bitmap bm = Bitmap.createBitmap(base64EncodeDecode.decodeBase64(taskItems.get(position).get("object_image")));
holder.taskTitleTextView.setText(taskItems.get(position).get("task_headline"));
holder.taskObjectTextView.setText(taskItems.get(position).get("object_name"));
holder.taskLocationTextView.setText(taskItems.get(position).get("object_location"));
holder.taskImageImageView.setImageBitmap(bm);
}
}
return vi;
}
First inflate your row layout into view:
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(<R.layout.header>, myListView, false);
Now you can take each component of view and can assign the values to them.eg:
TextView tv = header.findViewById(<R.id.text>);
tv.setText("Something");
Now just pass that header to the list view.
myListView.addHeaderView(header, null, false);
To add listener to that header. Just pass a listnener to that view group:
header.setOnClickListener(<pass a new OnClickListener Instance>);
After that you put the code to add adapter into list view.
myListView.setAdapter(<your adapter instance>);
If there is condition in inflating view in getView of CustomAdapter then you must
override extra two methods..
declare a integer named "type" globally in adapter class
int type;
Override these two functions
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
if(position == 0){
return 0;
}else{
return 1;
}
return super.getItemViewType(position);
}
Make a slight change to your getView function as given in the following code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolderProjects holderProjects;
type = getItemViewType(position);
if (type == 0) {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_item_projects, null);
holderProjects = new ViewHolderProjects();
holderProjects.projectTitelTextView = (TextView) vi.findViewById(R.id.projectTitle);
holderProjects.projectInfoTextView = (TextView) vi.findViewById(R.id.projectInfo);
holderProjects.projectImageImageView = (ImageView) vi.findViewById(R.id.projectImage);
holderProjects.projectDeadline = (TextView) vi.findViewById(R.id.projectdeadline);
vi.setTag(holderProjects);
} else {
holderProjects = (ViewHolderProjects) vi.getTag();
}
if (projectMap.size() <= 0) {
holderProjects.projectInfoTextView.setText("Keine Infos");
holderProjects.projectTitelTextView.setText("Kein Titel");
} else {
if (projectMap.get(position).containsKey("project_company_image")) {
if (projectMap.get(position).get("project_company_image").getBytes().length == 0) {
holderProjects.projectTitelTextView.setText(jobMap.get(position).get("job_subject"));
holderProjects.projectDeadline.setText(jobMap.get(position).get("job_deadline"));
return vi;
}
Bitmap bm = Bitmap.createBitmap(base64EncodeDecode.decodeBase64(projectMap.get(position).get("project_company_image")));
holderProjects.projectTitelTextView.setText(jobMap.get(position).get("job_subject"));
holderProjects.projectDeadline.setText(jobMap.get(position).get("job_deadline"));
holderProjects.projectImageImageView.setImageBitmap(bm);
}
}
} else {
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.list_item_tasks, null);
holder = new ViewHolder();
holder.taskTitleTextView = (TextView) vi.findViewById(R.id.taskTitle);
holder.taskObjectTextView = (TextView) vi.findViewById(R.id.taskObject);
holder.taskLocationTextView = (TextView) vi.findViewById(R.id.taskLocation);
holder.taskImageImageView = (ImageView) vi.findViewById(R.id.taskImage);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (taskItems.size() <= 0) {
holder.taskTitleTextView.setText("Kein Titel");
holder.taskObjectTextView.setText("Kein Objekt");
holder.taskLocationTextView.setText("Kein Standort");
} else {
if (taskItems.get(position).containsKey("object_image")) {
if (taskItems.get(position).get("object_image").getBytes().length == 0) {
holder.taskTitleTextView.setText(taskItems.get(position).get("task_headline"));
holder.taskObjectTextView.setText(taskItems.get(position).get("object_name"));
holder.taskLocationTextView.setText(taskItems.get(position).get("object_location"));
return vi;
}
}
Bitmap bm = Bitmap.createBitmap(base64EncodeDecode.decodeBase64(taskItems.get(position).get("object_image")));
holder.taskTitleTextView.setText(taskItems.get(position).get("task_headline"));
holder.taskObjectTextView.setText(taskItems.get(position).get("object_name"));
holder.taskLocationTextView.setText(taskItems.get(position).get("object_location"));
holder.taskImageImageView.setImageBitmap(bm);
}
}
return vi;
}
You can set header to ListView like this
View headerView = getLayoutInflater().inflate(R.layout.header_view, null, false);
listview.addHeaderView(headerView);
Note: you have to set header view before setting the adapter

ExpandableListView ClassCastException when using two different ViewHolders for Group

I am getting a ClassCastException when using two different ViewHolders
for my Groups an in ExpandableListView.
I have a separate ViewHolder for Group in position 0. The rest of the Groups use a different one.
This error happens after I already create the views by scrolling down and scroll back up to the Group in position 0.
I know my issue is in this line:
vhPropertyInfo = (ViewHolderPropertyInfo) convertView.getTag();
When I scroll back to Group position 0, it tries to cast (ViewHolderPropertyInfo) to the convertView that is not null, but it is actually (ViewHolderGroup) type. How do I resolve this?
#Override
public View getGroupView(int groupPosition, boolean isExpandable, View convertView, ViewGroup parent) {
if (groupPosition == 0) {
ViewHolderPropertyInfo vhPropertyInfo;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_property_info, null);
vhPropertyInfo = new ViewHolderPropertyInfo();
vhPropertyInfo.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
vhPropertyInfo.mTvCountry = (TextView) convertView.findViewById(R.id.tv_country);
vhPropertyInfo.mTvCity = (TextView) convertView.findViewById(R.id.tv_city);
vhPropertyInfo.mTvDistrict = (TextView) convertView.findViewById(R.id.tv_district);
vhPropertyInfo.mTvPostalCode = (TextView) convertView.findViewById(R.id.tv_postal_code);
vhPropertyInfo.mTvStreet = (TextView) convertView.findViewById(R.id.tv_street);
vhPropertyInfo.mTvSubStreet = (TextView) convertView.findViewById(R.id.tv_sub_street);
convertView.setTag(vhPropertyInfo);
}
else {
vhPropertyInfo = (ViewHolderPropertyInfo) convertView.getTag();
}
vhPropertyInfo.mTvName.setText("House Lannister");
vhPropertyInfo.mTvCountry.setText("Westeros");
vhPropertyInfo.mTvCity.setText("Kings Landing");
vhPropertyInfo.mTvDistrict.setText("West Side");
vhPropertyInfo.mTvPostalCode.setText("12345");
vhPropertyInfo.mTvStreet.setText("123 Kings Lane");
vhPropertyInfo.mTvSubStreet.setText("Hut 23");
return convertView;
}
else {
ViewHolderGroup vhGroup;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_property_group, null);
vhGroup = new ViewHolderGroup();
vhGroup.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(vhGroup);
}
else {
vhGroup = (ViewHolderGroup) convertView.getTag();
}
// Group 0 is property info so have to subtract one position
vhGroup.mTvName.setText(getGroup(groupPosition));
return convertView;
}
}
public final class ViewHolderGroup {
public TextView mTvName;
}
public final class ViewHolderPropertyInfo {
public TextView mTvName;
public TextView mTvCountry;
public TextView mTvCity;
public TextView mTvDistrict;
public TextView mTvPostalCode;
public TextView mTvStreet;
public TextView mTvSubStreet;
}
EDIT 1: So I fixed the problem, but checking the instance of convertView.getTag() if it was the same type of ViewHolder type, but my solution doesn't seem very elegant. Anyone know a way to do this cleaner?
#Override
public View getGroupView(int groupPosition, boolean isExpandable, View convertView, ViewGroup parent) {
if (groupPosition == 0) {
ViewHolderPropertyInfo vhPropertyInfo;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_property_info, null);
vhPropertyInfo = new ViewHolderPropertyInfo();
vhPropertyInfo.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
vhPropertyInfo.mTvCountry = (TextView) convertView.findViewById(R.id.tv_country);
vhPropertyInfo.mTvCity = (TextView) convertView.findViewById(R.id.tv_city);
vhPropertyInfo.mTvDistrict = (TextView) convertView.findViewById(R.id.tv_district);
vhPropertyInfo.mTvPostalCode = (TextView) convertView.findViewById(R.id.tv_postal_code);
vhPropertyInfo.mTvStreet = (TextView) convertView.findViewById(R.id.tv_street);
vhPropertyInfo.mTvSubStreet = (TextView) convertView.findViewById(R.id.tv_sub_street);
convertView.setTag(vhPropertyInfo);
}
else {
if (convertView.getTag() instanceof ViewHolderPropertyInfo) {
vhPropertyInfo = (ViewHolderPropertyInfo) convertView.getTag();
}
else {
convertView = mInflater.inflate(R.layout.row_property_info, null);
vhPropertyInfo = new ViewHolderPropertyInfo();
vhPropertyInfo.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
vhPropertyInfo.mTvCountry = (TextView) convertView.findViewById(R.id.tv_country);
vhPropertyInfo.mTvCity = (TextView) convertView.findViewById(R.id.tv_city);
vhPropertyInfo.mTvDistrict = (TextView) convertView.findViewById(R.id.tv_district);
vhPropertyInfo.mTvPostalCode = (TextView) convertView.findViewById(R.id.tv_postal_code);
vhPropertyInfo.mTvStreet = (TextView) convertView.findViewById(R.id.tv_street);
vhPropertyInfo.mTvSubStreet = (TextView) convertView.findViewById(R.id.tv_sub_street);
convertView.setTag(vhPropertyInfo);
}
}
vhPropertyInfo.mTvName.setText("House Lannister");
vhPropertyInfo.mTvCountry.setText("Westeros");
vhPropertyInfo.mTvCity.setText("Kings Landing");
vhPropertyInfo.mTvDistrict.setText("West Side");
vhPropertyInfo.mTvPostalCode.setText("12345");
vhPropertyInfo.mTvStreet.setText("123 Kings Lane");
vhPropertyInfo.mTvSubStreet.setText("Hut 23");
return convertView;
}
else {
ViewHolderGroup vhGroup;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_property_group, null);
vhGroup = new ViewHolderGroup();
vhGroup.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(vhGroup);
}
else {
if (convertView.getTag() instanceof ViewHolderGroup) {
vhGroup = (ViewHolderGroup) convertView.getTag();
}
else {
convertView = mInflater.inflate(R.layout.row_property_group, null);
vhGroup = new ViewHolderGroup();
vhGroup.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(vhGroup);
}
}
// Group 0 is property info so have to subtract one position
vhGroup.mTvName.setText(getGroup(groupPosition));
return convertView;
}
}
I found a more elegant way to do my solution. It is to do the convertView.getTag() checking the instanceof the ViewHolder before the check if convertView == null.
#Override
public View getGroupView(int groupPosition, boolean isExpandable, View convertView, ViewGroup parent) {
if (groupPosition == 0) {
ViewHolderPropertyInfo vhPropertyInfo;
if (convertView != null && !(convertView.getTag() instanceof ViewHolderPropertyInfo)) {
convertView = null;
}
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_property_info, null);
vhPropertyInfo = new ViewHolderPropertyInfo();
vhPropertyInfo.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
vhPropertyInfo.mTvCountry = (TextView) convertView.findViewById(R.id.tv_country);
vhPropertyInfo.mTvCity = (TextView) convertView.findViewById(R.id.tv_city);
vhPropertyInfo.mTvDistrict = (TextView) convertView.findViewById(R.id.tv_district);
vhPropertyInfo.mTvPostalCode = (TextView) convertView.findViewById(R.id.tv_postal_code);
vhPropertyInfo.mTvStreet = (TextView) convertView.findViewById(R.id.tv_street);
vhPropertyInfo.mTvSubStreet = (TextView) convertView.findViewById(R.id.tv_sub_street);
convertView.setTag(vhPropertyInfo);
}
else {
vhPropertyInfo = (ViewHolderPropertyInfo) convertView.getTag();
}
vhPropertyInfo.mTvName.setText("House Lannister");
vhPropertyInfo.mTvCountry.setText("Westeros");
vhPropertyInfo.mTvCity.setText("Kings Landing");
vhPropertyInfo.mTvDistrict.setText("West Side");
vhPropertyInfo.mTvPostalCode.setText("12345");
vhPropertyInfo.mTvStreet.setText("123 Kings Lane");
vhPropertyInfo.mTvSubStreet.setText("Hut 23");
return convertView;
}
else {
ViewHolderGroup vhGroup;
if (convertView != null && !(convertView.getTag() instanceof ViewHolderGroup)) {
convertView = null;
}
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_property_group, null);
vhGroup = new ViewHolderGroup();
vhGroup.mTvName = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(vhGroup);
}
else {
vhGroup = (ViewHolderGroup) convertView.getTag();
}
// Group 0 is property info so have to subtract one position
vhGroup.mTvName.setText(getGroup(groupPosition));
return convertView;
}
}

Convert View And Multiple Types BaseAdapter

I have created an adapter that feeds a list view. It is working ok but is a little jenky so I am trying to use the Convert View to avoid inflating a view on every getView call. I changed the getview method to the following
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Suggestion suggestion = getItem(position);
int type = getItemViewType(position);
ImageView imageView;
TextView titleTv;
ImageView checkBox;
switch (type) {
case Suggestion.CONTACT_SUGGESTION_ID:
ContactSuggestion contactSuggestion = (ContactSuggestion) suggestion;
String id = contactSuggestion.getId();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.contact_history_item, parent, false);
}
imageView = (ImageView) convertView.findViewById(R.id.imageView);
PhotoRetreiver photoRetreiver = (PhotoRetreiver) imageView.getTag();
if (photoRetreiver != null) {
photoRetreiver.cancel(true);
}
if (images.containsKey(id)) {
imageView.setImageBitmap(images.get(id));
} else {
photoRetreiver = new PhotoRetreiver(context, id, imageView);
imageView.setTag(photoRetreiver);
photoRetreiver.execute();
}
titleTv = (TextView) convertView.findViewById(R.id.titleTv);
titleTv.setText(suggestion.getTitle());
checkBox = (ImageView) convertView.findViewById(R.id.favouriteIv);
checkBox.setOnClickListener(this);
checkBox.setId(position);
if (suggestion.isFavourite()) {
checkBox.setBackgroundResource(R.drawable.search_fav_active);
checkBox.setTag(true);
} else {
checkBox.setTag(false);
}
break;
case Suggestion.GOOGLE_SUGGESTION_ID:
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.google_history_item, parent, false);
}
imageView = (ImageView) convertView.findViewById(R.id.imageView);
titleTv = (TextView) convertView.findViewById(R.id.titleTv);
imageView.setImageResource(resources.getIdentifier(suggestion.getInActiveImageResource(), "drawable", "com.allryder.android"));
titleTv.setText(suggestion.getTitle());
checkBox = (ImageView) convertView.findViewById(R.id.favouriteIv);
checkBox.setOnClickListener(this);
checkBox.setId(position);
if (suggestion.isFavourite()) {
checkBox.setBackgroundResource(R.drawable.search_fav_active);
checkBox.setTag(true);
} else {
checkBox.setTag(false);
}
break;
case Suggestion.STATION_SUGGESTION_ID:
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.station_history_item, parent, false);
}
StationSuggestion stationSuggestion = (StationSuggestion) suggestion;
StationView stationView = (StationView) convertView.findViewById(R.id.stationView);
stationView.setStationTypes(stationSuggestion.getStationTypes());
titleTv = (TextView) convertView.findViewById(R.id.titleTv);
titleTv.setText(suggestion.getTitle());
checkBox = (ImageView) convertView.findViewById(R.id.favouriteIv);
checkBox.setOnClickListener(this);
checkBox.setId(position);
if (suggestion.isFavourite()) {
checkBox.setBackgroundResource(R.drawable.search_fav_active);
checkBox.setTag(true);
} else {
checkBox.setTag(false);
}
break;
case Suggestion.CURRENT_LOCATION_SUGGESTION_ID:
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.current_location_item, parent, false);
}
titleTv = (TextView) convertView.findViewById(R.id.titleTv);
titleTv.setText(suggestion.getTitle());
break;
}
TextView detailTv = (TextView) convertView.findViewById(R.id.detailTv);
detailTv.setText(suggestion.getDescription());
convertView.setTag(type);
return convertView;
}
Then overwrote the following to methods so the adapter knows which view type is should pass into the getview method
#Override
public int getViewTypeCount() {
return 4;
}
#Override
public int getItemViewType(int position) {
return getItem(position).getTypeId();
}
However I receive a a null pointer on this line
checkBox.setOnClickListener(this);
So checkbox is not instantiated.
You can see that I added a tag to the convert view this was just to check that the tag would equal the type when convert view is not null. And it always is.
Why the hell can the adapter not find checkbox?

Categories

Resources