android ListView adapter with three different xml items - android

I am trying to create a listview with three different item types I have a code that works with two XML files
Here is the adapter code:
private class MyCustomAdapter extends ArrayAdapter<String> {
String hello;
private String place;
int image;
private String temp;
private String humidity;
private String windspeed;
private String condition;
private int imageTop;
private String time;
private static final int TYPE_WEATHER = 0;
private static final int TYPE_TIME = 1;
private static final int TYPE_TOP = 2;
private static final int TYPE_MAX_COUNT = 3 + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context, int resource) {
super(context, resource);
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addWeather(final String place,final int image , final String temp,final String humidity,final String windspeed,final String condition) {
mData.add(place);
this.place = place;
this.image = image;
this.temp = temp;
this.humidity = humidity;
this.windspeed = windspeed;
this.condition = condition;
notifyDataSetChanged();
}
public void addFavapp(final String helloworld){
mData.add(place);
this.hello = helloworld;
notifyDataSetChanged();
}
public void addItem(final String item) {
this.time = item;
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_WEATHER : TYPE_TIME;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_WEATHER:
convertView = mInflater.inflate(R.layout.weather_item, null);
//Handling xml file weather_item
break;
case TYPE_TIME:
convertView = mInflater.inflate(R.layout.time_card_item, null);
holder.textView = (TextView)convertView.findViewById(R.id.two);
holder.textView.setText(time);
break;
case TYPE_TOP:
convertView = mInflater.inflate(R.layout.top_card_item, null);
//Handling xml file top_card_item
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
public ImageView image;
public TextView txtTemp;
public ImageView imageView;
public TextView txthumidity;
public TextView txtWind;
public TextView txtCond;
}
I tried creating a method called "addFavapp" to add my third XML file but I couldn't get it to work.
Help please.

Got it fixed by replacing
return mSeparatorsSet.contains(position) ? TYPE_WEATHER : TYPE_TIME;
Inside the getItemViewType
To
return position;

Related

How to check if list view items are checked or not on button click

I am using a custom List adapter for my list view
layout
public class VoterListAdapter extends ArrayAdapter<Voter> implements Filterable {
private static final String TAG = "VoterListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private static class ViewHolder {
TextView vid;
TextView name;
TextView mNum;
TextView wNum;
TextView lmNum;
TextView rNum;
CheckBox vote;
}
public VoterListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Voter> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String vid = getItem(position).getVid();
String name = getItem(position).getName();
String mNum = getItem(position).getmNum();
String wNum = getItem(position).getwNum();
String lmNum = getItem(position).getLmNum();
String rNum = getItem(position).getrNum();
Voter voter = new Voter(vid,name,mNum,wNum,lmNum,rNum);
final View result;
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name_text_view);
holder.mNum = (TextView) convertView.findViewById(R.id.mNum_text_view);
holder.wNum = (TextView) convertView.findViewById(R.id.wNum_text_view);
holder.lmNum = (TextView) convertView.findViewById(R.id.lmNum_text_view);
holder.rNum = (TextView) convertView.findViewById(R.id.rNum_text_view);
holder.vote = (CheckBox) convertView.findViewById(R.id.vote_check_box);
result = convertView;
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext,
(position > lastPosition) ? R.anim.loading_down_anim : R.anim.loading_up_anim);
result.startAnimation(animation);
lastPosition = position;
holder.name.setText(voter.getName());
holder.mNum.setText(voter.getmNum());
holder.wNum.setText(voter.getwNum());
holder.lmNum.setText(voter.getLmNum());
holder.rNum.setText(voter.getrNum());
return convertView;
}
}
My Voter class looks like this
public class Voter {
private String vid;
private String name;
private String mNum;
private String wNum;
private String lmNum;
private String rNum;
private CheckBox vote;
public Voter(String vid, String name, String mNum, String wNum, String lmNum, String rNum ) {
this.vid = vid;
this.name = name;
this.mNum = mNum;
this.wNum = wNum;
this.lmNum = lmNum;
this.rNum = rNum;
}
public CheckBox getVote() {
return vote;
}
public void setVote(CheckBox vote) {
this.vote = vote;
}
public String getVid() {
return vid;
}
public void setVid(String vid) {
this.vid = vid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getmNum() {
return mNum;
}
public void setmNum(String mNum) {
this.mNum = mNum;
}
public String getwNum() {
return wNum;
}
public void setwNum(String wNum) {
this.wNum = wNum;
}
public String getLmNum() {
return lmNum;
}
public void setLmNum(String lmNum) {
this.lmNum = lmNum;
}
public String getrNum() {
return rNum;
}
public void setrNum(String rNum) {
this.rNum = rNum;
}
}
This is how i set my adapter(may not be relevant)
adapter = new VoterListAdapter(getActivity(), R.layout.adapter_view_layout, voterlist);
datalistview.setAdapter(adapter);
I have a separate button which should check all items in the custom list view and if they are checked, give me the Voter object.I tried using onItemClickListener() but I am only able to get it work on individual object. I want it to check all items at once when the button is clicked

Display image Id instead of image in Android

I have a expandable recycler view which have some parent and some child items as like this.
I'm trying to add a image with every file name using like this code:
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, obj1.optString("category").trim()+" "+R.drawable.download48));
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, obj1.optString("filename").trim()));
But it prints the image id(red circled area) instead of actual image. How to print here actual image?
Here is my adapter code:
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
float dp = context.getResources().getDisplayMetrics().density;
int subItemPaddingLeft = (int) (18 * dp);
int subItemPaddingTopAndBottom = (int) (5 * dp);
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (type) {
case HEADER:
view = inflater.inflate(R.layout.list_header, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
view = inflater.inflate(R.layout.listchild, parent, false);
ListChildViewHolder child = new ListChildViewHolder(view);
return child;
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
break;
}
}
#Override
public int getItemViewType(int position) {
return data.get(position).type;
}
#Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
}
}
private static class ListChildViewHolder extends RecyclerView.ViewHolder {
public TextView header_title1;
public ImageView btn_expand_toggle1;
public Item refferalItem1;
public ListChildViewHolder(View itemView) {
super(itemView);
header_title1 = (TextView) itemView.findViewById(R.id.header_title1);
btn_expand_toggle1 = (ImageView) itemView.findViewById(R.id.btn_expand_toggle1);
}
}
public static class Item {
public int type;
public String text;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Your onBindViewHolder() method's case CHILD should look something like this
case CHILD:
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
itemController1.btn_expand_toggle1.setImageResource(item.resId);
break;
And your class Item should be something like this:
public static class Item {
public int type;
public String text;
private int resId;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text, #DrawableRes int resId) {
this.type = type;
this.text = text;
this.resId = resId;
}
}
And while initializing it should be
data.add(new ExpandableListAdapter.Item(ExpandableListAdapter.CHILD, obj1.optString("category").trim(), R.drawable.download48));
Add this line
btn_expand_toggle1.setImageDrawable(getResources().getDrawab‌​le(R.drawable.ic_lau‌​ncher));
after
final ListChildViewHolder itemController1 = (ListChildViewHolder) holder;
itemController1.refferalItem1 = item;
itemController1.header_title1.setText(item.text);
It will work

Using two different listview row types

I am trying to make a listview that contains soccer(football) teams fixtures but I have failed to alternate between the title(contains the date) and the matches under that date
This is mycode
public class FixturesCursorAdapter extends CursorAdapter {
private static final String TAG = "CURSORLOADER";
private final int VIEW_TYPE_TITLE = 0;
private final int VIEW_TYPE_BODY = 1;
private final int VIEW_TYPE_COUNT = 2;
private String itemname;
private int n = 0;
private ImageView imageView;
public static class ViewHolder {
public final TextView homeTeam;
public final TextView awayTeam;
public final TextView score;
public final TextView date;
public final ImageView homeImage;
public final ImageView awayImage;
public ViewHolder(View view) {
homeTeam = (TextView) view.findViewById(R.id.homeTeam);
awayTeam = (TextView) view.findViewById(R.id.awayTeam);
score = (TextView) view.findViewById(R.id.score);
date = (TextView) view.findViewById(R.id.date);
homeImage = (ImageView) view.findViewById(R.id.homeTeamImage);
awayImage = (ImageView) view.findViewById(R.id.awayImageTeam);
}
}
public FixturesCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getItemViewType(int position) {
return (position == 0)? VIEW_TYPE_TITLE : VIEW_TYPE_BODY;
}
#Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
if (viewType == VIEW_TYPE_TITLE){
layoutId = R.layout.fixtures_row_title;
}
else if (viewType == VIEW_TYPE_BODY){
layoutId = R.layout.fixtures_table_row;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor){
String homeTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_HOME_TEAM_NAME));
String awayTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_AWAY_TEAM_NAME));
String goalsHomeTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_GOALS_HOME_TEAM));
String goalsAwayTeam = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_GOALS_AWAY_TEAM));
// String date = cursor.getString(cursor.getColumnIndex(SoccerContract.FixturesTable.TAG_DATE));
Log.d("CURSOR_bindview", homeTeam);
Log.d("CURSOR_bindview", awayTeam);
ViewHolder viewHolder = (ViewHolder) view.getTag();
try {
viewHolder.homeTeam.setText(homeTeam);
viewHolder.awayTeam.setText(awayTeam);
viewHolder.score.setText(goalsHomeTeam + " - " + goalsAwayTeam);
// viewHolder.date.setText(Utility.timeTruncate(date));
Log.d("PicassoLoader", "initiating" + n);
for (n = 0; n < 2; n++) {
Log.d("PicassoLoader", "started" + n);
if (n == 0) {
itemname = homeTeam;
imageView = viewHolder.homeImage;
} else {
itemname = awayTeam;
imageView = viewHolder.awayImage;
}
if (imageView != null && itemname != null) {
Utility.picassoLoader(context, 0, imageView,itemname);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The title appears only at the top. So how can I manually switch between the title(VIEW_TYPE_TITLE) and body(VIEW_TYPE_BODY)
You shouldn't be using newView() to specify the view for each item. Use getView() instead.
See the answer to this question for details on what getView() and newView() and when to use each.

How to make BaseAdapter work

I'm trying to make category listview . I want use my code easy to understand and using
I have a MainActivity class
public class MainActivity extends Activity{
private MyCustomAdapter mAdapter;
ListView lst;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lst = (ListView)findViewById(R.id.lstView);
mAdapter = new MyCustomAdapter(this);
for (int i = 1; i < 50; i++) {
mAdapter.addItem("Sameer Blog " + i);
if (i % 4 == 0) {
mAdapter.addSeparatorItem("Ahmad " + i);
}
}
lst.setAdapter(mAdapter);
}
}
and a MyCustomAdapter class like this
public class MyCustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private Context context;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context c) {
this.context = c;
mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
// save separator position
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public int getItemViewType(int position) {
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public int getCount() {
return mData.size();
}
public String getItem(int position) {
return mData.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView txtView = null;
int type = getItemViewType(position);
if (convertView == null) {
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.list_item, null);
txtView = (TextView)convertView.findViewById(R.id.txtItem);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.list_header, null);
txtView = (TextView)convertView.findViewById(R.id.txtHeader);
break;
}
}
txtView.setText(mData.get(position));
return convertView;
}
}
But I always get NullPointerException in logcat . Somebody can hep me ????
May be it is due to
notifyDataSetChanged();
you call in addItem and addSeparatorItem without setting adapter in listview.
Try changing your:
public MyCustomAdapter(Context c) {
this.context = c;
mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
to:
public MyCustomAdapter(Context c) {
this.context = c;
mInflater =LayoutInflater.from(getContext());
}

ListFragment error

I have a list in a "listview" to scroll the list using this mess,
grouping and the list has a header with icons.
public class MyCustomAdapter extends BaseAdapter {
private static final String ASSETS_DIR = "images/";
private static final int TYPE_HEAD = -1;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private Context ctx;
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
private TreeSet<Integer> mSeparatorsSet = new TreeSet<Integer>();
public MyCustomAdapter(Context context) {
this.ctx = context;
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSeparatorItem(final String item) {
mData.add(item);
mSeparatorsSet.add(mData.size() - 1);
notifyDataSetChanged();
}
public void addHeadItem(){
mData.add("");
mSeparatorsSet.add(0);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
//return equipos.size();
}
#Override
public String getItem(int position) {
return mData.get(position) ;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemViewType(int position) {
if (position==0)
return TYPE_HEAD;
return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
System.out.println("getView " + position + " " + convertView
+ " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.list_item, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
holder.textView3 = (TextView) convertView.findViewById(R.id.textView3);
holder.imageView1 = (ImageView) convertView.findViewById(R.id.imageView1);
String[] datos = mData.get(position).split("-");
holder.textView1.setText(String.format(" %s - %s", datos[0],datos[1]));
holder.textView2.setText(datos[2]);
holder.textView3.setText(datos[3]);
String sel_bandera = datos[4].trim() ;
String imgFilePath = "";
if (sel_bandera.equals("verde")){
imgFilePath = ASSETS_DIR + "circle_green.png" ;
}else if (sel_bandera.equals("amarilla")){
imgFilePath = ASSETS_DIR + "circle_yellow.png";
}else {
imgFilePath = ASSETS_DIR + "circle_red.png";
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(this.ctx.getResources().getAssets().open(imgFilePath));
holder.imageView1.setImageBitmap(bitmap);
//bandera.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.list_group, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textSeparator);
holder.textView1.setText(mData.get(position));
break;
case TYPE_HEAD:
convertView = mInflater.inflate(R.layout.list_head, null);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
public static class ViewHolder {
public TextView textView1;
public TextView textView2;
public TextView textView3;
public ImageView imageView1;
public TextView getTextView1() {
return textView1;
}
public void setTextView1(TextView textView1) {
this.textView1 = textView1;
}
public TextView getTextView2() {
return textView2;
}
public void setTextView2(TextView textView2) {
this.textView2 = textView2;
}
public TextView getTextView3() {
return textView3;
}
public void setTextView3(TextView textView3) {
this.textView3 = textView3;
}
public ImageView getImageView1() {
return imageView1;
}
public void setImageView1(ImageView imageView1) {
this.imageView1 = imageView1;
}
}
}
public class EquiposActivity extends ListFragment implements OnTouchListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mAdapter = new MyCustomAdapter(getActivity());
if (lista.length > 0) {
String[] datos = lista[0].split("-");
cabecera_grupo = datos[4];
}
mAdapter.addHeadItem();
for (int i = 0; i < lista.length; i++) {
String[] datos = lista[i].split("-");
String grupo = datos[4];
if (i == 0) {
mAdapter.addSeparatorItem(grupo.replace("_", " "));
}
if (!grupo.equals(cabecera_grupo)) {
mAdapter.addSeparatorItem(grupo.replace("_", " "));
cabecera_grupo = grupo;
}
mAdapter.addItem(String.format("%s - %s - %s - %s - %s",
datos[0], datos[1], datos[2], datos[3], datos[5]));
}
setListAdapter(mAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
I suggest you to rewrite your getView() method, because I think that you are wrongly using ViewHolder pattern. Read this: http://www.jmanzano.es/blog/?p=166
Or just get rid of ViewHolder and code getView() without it.

Categories

Resources