Update ListView's contents by below code:
private ListView listViewBuddy;
private BuddyAdapter mBuddyAdapter;
private ArrayList<BuddyModel> buddyList = new ArrayList<BuddyModel>();
onCreate():
listViewBuddy = (ListView)findViewById(R.id.listViewBuddy);
mBuddyAdapter = new BuddyAdapter();
listViewBuddy.setAdapter(mBuddyAdapter);
onDataGet (After webservice call or from local database or otherelse):
mBuddyAdapter.setData(buddyList);
mBuddyAdapter.notifyDataSetChanged();
BaseAdapter:
private class BuddyAdapter extends BaseAdapter {
private ArrayList<BuddyModel> mArrayList = new ArrayList<BuddyModel>();
private LayoutInflater mLayoutInflater= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private ViewHolder holder;
public void setData(ArrayList<BuddyModel> list){
mArrayList = list;
}
@Override
public int getCount() {
return mArrayList.size();
}
@Override
public BuddyModel getItem(int position) {
return mArrayList.get(position);
}
@Override
public long getItemId(int pos) {
return pos;
}
private class ViewHolder {
private TextView txtBuddyName, txtBuddyBadge;
}
@SuppressLint("InflateParams")
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.row_buddy, null);
// bind views
holder.txtBuddyName = (TextView) convertView.findViewById(R.id.txtBuddyName);
holder.txtBuddyBadge = (TextView) convertView.findViewById(R.id.txtBuddyBadge);
// set tag
convertView.setTag(holder);
} else {
// get tag
holder = (ViewHolder) convertView.getTag();
}
holder.txtBuddyName.setText(mArrayList.get(position).getFriendId());
int badge = mArrayList.get(position).getCount();
if(badge!=0){
holder.txtBuddyBadge.setVisibility(View.VISIBLE);
holder.txtBuddyBadge.setText(""+badge);
}else{
holder.txtBuddyBadge.setVisibility(View.GONE);
}
return convertView;
}
}
Whenever you want to Update Listview just call below two lines code:
mBuddyAdapter.setData(Your_Updated_ArrayList);
mBuddyAdapter.notifyDataSetChanged();
Done