I have set the custom BaseAdapter in Activity as :
llNoContactMessage = (LinearLayout) findViewById(R.id.llNoContacts);
listAdapter = new ContactsListAdapter(this, contactsList);
lvContactList = (ListView) findViewById(R.id.lvContactList);
lvContactList.setAdapter(listAdapter);
lvContactList.setOnItemClickListener(null);
And there is my Adapter class:
public class ContactsListAdapter extends BaseAdapter {
private List<ContactsInfo> contactList;
private Context context;
public ContactsListAdapter(Context context, List<ContactsInfo> contactsList) {
this.context = context;
this.contactList = contactsList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
final ContactsInfo contactsInfo = contactList.get(position);
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_contacts_item, parent, false);
ViewHolder vh = new ViewHolder();
vh.tvContactName = (TextView) view.findViewById(R.id.tvContactName);
vh.tvContactNumber = (TextView) view.findViewById(R.id.tvContactNumber);
vh.llRemoveContact = (LinearLayout) view.findViewById(R.id.llRemoveContact);
view.setTag(vh);
}
final ViewHolder holder = (ViewHolder) view.getTag();
holder.tvContactName.setText(contactsInfo.getContactName());
holder.tvContactNumber.setText(contactsInfo.getContactNumber());
holder.llRemoveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UIUtils.showRemoveContactAlert(context, contactsInfo);
if(UIUtils.contactRemoved) {
contactList.remove(contactsInfo);
setList(getContacts());
notifyDataSetChanged();
}
}
});
return view;
}
static class ViewHolder {
TextView tvContactNumber;
TextView tvContactName;
LinearLayout llRemoveContact;
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public ContactsInfo getItem(int index) {
return contactList.get(index);
}
#Override
public long getItemId(int position) {
return getItem(position).get_id();
}
public void setList(List<ContactsInfo> list) {
contactList.clear();
contactList.addAll(list);
}
private List<ContactsInfo> getContacts() {
CrisisCallingDatabase crisisCallDB = new CrisisCallingDatabase(context);
return crisisCallDB.getContactsList();
}
}
The method to delete data from database is:
public static void showRemoveContactAlert(final Context context, final ContactsInfo contact) {
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setMessage("Remove Contact");
b.setCancelable(true);
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CrisisCallingDatabase ccd = new CrisisCallingDatabase(context);
if(ccd.deletContact(contact.get_id())){
Toast.makeText(context, contact.getContactName() + " removed successfully.", Toast.LENGTH_SHORT).show();
contactRemoved = true;
} else {
Toast.makeText(context, "Remove contact failed.", Toast.LENGTH_SHORT).show();
contactRemoved = false;
}
CrisisCallingDatabase.closeDBConnections();
}
});
b.setNegativeButton("No", null);
b.show();
}
But the view of the list is not removing the item from the list. However after clicking the any UI component on the list again is reloading the list i.e. the deleted item is removed. I don't know where I did mistake. Any help will be appreciated.
Move your notifyDataSetChanged() call to the end of your setList method.
Finally solved the issue, I just moved the confirmation alert code inside the On Click event like below :
holder.llRemoveContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder b = new AlertDialog.Builder(context);
b.setMessage("Remove Contact");
b.setCancelable(true);
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(succefulRemoval)){
contactList.remove(contactsInfo);
setList();
Toast.makeText(context, contactsInfo.getContactName() + " removed successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Remove contact failed.", Toast.LENGTH_SHORT).show();
}
}
});
b.setNegativeButton("No", null);
b.show();
}
});
}
});
Maybe you got answer already, but just for an extra
public void setList(List<ContactsInfo> list) {
contactList.clear();
contactList.addAll(list);
contactList.notifyDataSetChanged();
}
Related
Hello i am new to android and working on a demo of Custom ListView,I have made an adapter ,a ListItem custom and binding to my Listview,All things working perfectly but i want to remove item when i delete it from the list
Adapter
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(true);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
notifyDataSetChanged();
return view;
}
}
fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
total = 0;
mPullToRefreshLayout = (PullToRefreshLayout) getActivity().findViewById(R.id.ptr_layout);
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(this).setup(mPullToRefreshLayout);
mProgressBarLoading = (ProgressBar) getActivity().findViewById(R.id.progressBarLoading);
mTextViewNoItems = (TextView) getActivity().findViewById(R.id.textViewNoItems);
mTimelineAdapter = new TimelineAdapter(getActivity());
mListViewTimeline = (ListView) getActivity().findViewById(R.id.listViewTimeline);
mListViewTimeline.setEmptyView(mProgressBarLoading);
mListViewTimeline.setAdapter(mTimelineAdapter);
mTimelineAdapter.notifyDataSetChanged();
mListViewTimeline.setOnScrollListener(this);
// mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setVerticalScrollBarEnabled(false);
Activity activity = getActivity();
if(activity != null) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
getLoaderManager().initLoader(0, null, TimelineFragment.this);
//Do something after 100ms
}
}, 1000);
mTextViewNoItems.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, TimelineFragment.this);
Log.d("CLICK", "REFRESH");
}
});
}
}
#Override
public Loader<List<Post>> onCreateLoader(int id, Bundle args) {
mTimelineLoader = new TimelineLoader(getActivity(), mListViewTimeline);
setHasOptionsMenu(true);
return mTimelineLoader;
}
#Override
public void onLoadFinished(Loader<List<Post>> arg0, List<Post> data) {
mTimelineAdapter.setData(data);
mTimelineAdapter.notifyDataSetChanged();
mPullToRefreshLayout.setRefreshComplete();
mTextViewNoItems.setVisibility(View.VISIBLE);
mProgressBarLoading.setVisibility(View.INVISIBLE);
mListViewTimeline.setEmptyView(mTextViewNoItems);
if (data.isEmpty()) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, TimelineFragment.this);
}
}
#Override
public void onLoaderReset(Loader<List<Post>> arg0) {
mTimelineAdapter.setData(null);
setHasOptionsMenu(true);
}
ListItem
if (which == 2) {
if (mPost.postUser.userID == sharedConnect.mCurrentUser.userID) {
// Log.e("Remove Post", "Success");
//Added by jigar..
tfragment = new TimelineFragment();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setMessage("Are you sure?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//open = false;
final AsyncTask<Void, Void, Boolean> deleted = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
Connect sharedConnect = Connect.getInstance(getContext());
sharedConnect.deletePost(mPost.postID);
return true;
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getContext(), "Deleted",
Toast.LENGTH_SHORT).show();
tfragment = new TimelineFragment();
tfragment.mTimelineAdapter.notifyDataSetChanged();
}
}.execute();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
// open = false;
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
//end
}
implement onResume() method and load the adapter in onResume() method and notify data set changed
First use the adapter.notifiDataSetChanged() carefully. It should be used when you are adding or removing a row from the list.
In order to delete an item from the list, set onItemclicklistener on your ListView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
from this you will get the position of clicked item that you want to remove.
Now define a method in your adapter
public void deleteRowFromUi(int position) {
dataList.remove(position);
notifyDataSetChanged();
}
And call this method from the activity using instance of the adapter in the activity
Adapter Class:
public List<TSPDataModel> employeeData;
private Context mContext;
private LayoutInflater mInflater;
RadioGroup radiogroupbutton;
String[] data = {"Document not clear","Adress is not Visibile","Photo is not pasted","Signature is not Avilable"};
String value;
public TSPListDocumentadapter(Context context, int textViewResourceId,
List<TSPDataModel> objects)
{
this.employeeData = objects;
this.mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.tspdocumentlistitem, null);
holder.relatvie1=(RelativeLayout)convertView.findViewById(R.id.relatvie1);
holder.txtName = (TextView) convertView.findViewById(R.id.textView1);
holder.accecpt = (ImageView) convertView.findViewById(R.id.imageButton);
holder.reject = (ImageView) convertView.findViewById(R.id.imageButton2);
holder.statustextview = (TextView) convertView.findViewById(R.id.statustextview);
holder.poaedittext=(TextView) convertView.findViewById(R.id.poieditext);
holder.poaedittext=(TextView)convertView.findViewById(R.id.poaedittext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(employeeData.get(position).getName());
holder.poaedittext.setText(employeeData.get(position).getPoa());
holder.accecpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.statustextview.setText("Accepted");
employeeData.get(position).setSelected(true);
employeeData.get(position).getOrderId();
holder.relatvie1.setBackgroundResource(R.color.acceptedcolor);
}
});
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog();
holder.statustextview.setText("Rejected");
employeeData.get(position).setSelected(false);
employeeData.get(position).setReasone(value);
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
return convertView;
}
static class ViewHolder {
TextView txtName;
ImageView reject;
ImageView accecpt;
TextView statustextview;
TextView poiedittext;
TextView poaedittext;
RelativeLayout relatvie1;
}
public int getCount() {
return employeeData.size();
}
public TSPDataModel getItem(int position) {
return employeeData.get(position);
}
public long getItemId(int position) {
return 0;
}
public void showdilog() {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
This Button click in my actvity class :
#Override
public void onClick(View view) {
if (view.getId() == R.id.button1) {
try {
List<TSPDataModel> empData = adapter.employeeData;
System.out.println("Total Size :" + empData.size());
for (TSPDataModel employeeModel : empData) {
if (employeeModel.isSelected()) {
Toast.makeText(TSPDocumentListActvity.this, employeeModel.getName(), Toast.LENGTH_LONG).show();
} else {
String Reasonse= employeeModel.getresonse() ;
Toast.makeText(TSPDocumentListActvity.this, "false" + employeeModel.getName(), Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
First i Print data in Listview then each list view item there is accept and reject Button is there when we click on accept then no alert will asked only reject button reason will ask which is come on listitem on popup i want to get that selected reason on Button click in actvity but i always get null value please help me where i am doing wrong
change your reject button and showDialog code to
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog(position);
holder.statustextview.setText("Rejected");
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
and showDualog to
public void showdilog(int list_position) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
employeeData.get(list_position).setSelected(false);
employeeData.get(list_position).setReasone(value);
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
I have made a custom ListView and adapter for that, I have made a custom relative layout class for delete feature. Now I want to update my ListView once any of item is deleted. I have used notifydatasetChanged() method, But its not working. Please help me. My adapter is as below
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(false);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
return view;
}
}
CustomListItem
if (mPost.postUser.userID == sharedConnect.mCurrentUser.userID) {
// Log.e("Remove Post", "Success");
//Added by jigar..
tfragment = new TimelineFragment();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setMessage("Are you sure?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//open = false;
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
Connect sharedConnect = Connect.getInstance(getContext());
sharedConnect.deletePost(mPost.postID);
return true;
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getContext(), "Deleted",
Toast.LENGTH_SHORT).show();
}
}.execute();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
// open = false;
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
//end
public class SoloPlayActivity extends BaseActivity implements View.OnClickListener{
private ListView case_list;
private RelativeLayout add_case;
private TextView num_case_textview;
private Button start_button;
ArrayList<ItemSoloplayCase> caseArrayList;
AdapterSoloplay adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_solo_play);
initView();
//처음에는 경우의 수가 아무것도 없음
num_case_textview.setText("0");
caseArrayList = new ArrayList<ItemSoloplayCase>();
adapter = new AdapterSoloplay(this, caseArrayList, num_case_textview);
case_list.setAdapter(adapter);
}
private void initView(){
add_case = (RelativeLayout)findViewById(R.id.add_case);
add_case.setOnClickListener(this);
num_case_textview = (TextView)findViewById(R.id.num_case);
start_button = (Button)findViewById(R.id.game_start);
start_button.setOnClickListener(this);
case_list = (ListView)findViewById(R.id.case_list);
//리스트뷰에서 포커스를 잃지 않도록 한다.
case_list.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
}
#Override
protected String getActionbarTitle() {
return getString(R.string.solo_play_name);
}
//뒤로가기가 눌렸을때 추가한 경우의 수가 있을경우에만 다이얼로그 띄우고 경우의수가 비었다면 그냥 종료
#Override
public void onBackPressed() {
if (!caseArrayList.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("입력한 경우의 수는 모두 사라집니다. 정말로 닫겠습니까?")
.setCancelable(false)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SoloPlayActivity.this.finish();
}
})
.setNegativeButton("취소", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
else
SoloPlayActivity.this.finish();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.game_start:
Toast.makeText(getApplicationContext(), "게임시작 버튼 누름", Toast.LENGTH_SHORT);
break;
case R.id.add_case:
//경우의수 추가
ItemSoloplayCase additem = new ItemSoloplayCase();
caseArrayList.add(additem);
num_case_textview.setText(Integer.toString(caseArrayList.size()));
adapter.notifyDataSetChanged();
break;
}
}}
activity file.
Adapter file.
public class AdapterSoloplay extends BaseAdapter {
private Context context;
private ArrayList<ItemSoloplayCase> caselist;
private TextView num_case;
//순서 갱신 오류, 해당 지운 에디트가 지워지지 않음
public AdapterSoloplay(Context context, ArrayList<ItemSoloplayCase> caselist, TextView num_case) {
this.context = context;
this.caselist = caselist;
this.num_case = num_case;
}
#Override
public int getCount() {
return caselist.size();
}
#Override
public Object getItem(int position) {
return caselist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Viewholder holder;
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_case_input, parent, false);
holder = new Viewholder();
holder.order = (TextView) convertView.findViewById(R.id.order_num);
holder.editText = (EditText)convertView.findViewById(R.id.input_case);
holder.button_clear = (ImageButton)convertView.findViewById(R.id.remove_case);
//순서는 현재 크기만큼
holder.order.setText(Integer.toString(getCount()));
convertView.setTag(holder);
}
else
holder = (Viewholder)convertView.getTag();
//클리어를 눌럿을때 제거하고 순서를 재정렬하고 갱신시킨다
holder.button_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ItemSoloplayCase item = (ItemSoloplayCase)getItem(position);
item = null;
caselist.remove(position);
notifyDataSetChanged();
num_case.setText(Integer.toString(caselist.size()));
}
});
return convertView;
}
class Viewholder {
private EditText editText;
private TextView order;
private ImageButton button_clear;
}
}
i want to make dynamically add or remove edit text in list view. '
like image.
enter image description here
if i want remove second list(in this image, b) but it removed last data(in this image, d). and i click add button it makes last data..(in this image, makes edit text value d).
above is my code. help.
please help me.
Add a linearlayout to listview rows xml file :
For add dynamically EditText to this layout try this :
EditText editText = new EditText(context);
editText.setHint(hint);
editText.requestFocus();
editText.setSelection(editText.getText().length());
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
linearlayout.addview(editText);
I am kind of new to android. For the life of me I can not figure out how to delete an item from a ListView from within my Adapter. Each row in the list view has an edit and delete option. I populate a dialog asking user to confirm deletion, after confirming, i'd like the ListView to remove that Item. Any help would be greatly appreciated.
Contacts.java
public class Contacts extends ActionBarActivity {
private Button mButton;
private ContactsAdapter mAdapter;
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emergency_contacts);
mAdapter = new ContactsAdapter(Contacts.this,new ArrayList<SingleContactInfo>());
mListView = (ListView) findViewById(R.id.listView);
mListView.setAdapter(mAdapter);
mButton = (Button) findViewById(R.id.addContactButton);
updateData();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goToAddContacts = new Intent(getApplicationContext(), AddContactInfo.class);
startActivity(goToAddContacts);
}
});
}
public void updateData(){
ParseQuery<SingleContactInfo> query = ParseQuery.getQuery(SingleContactInfo.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<SingleContactInfo>() {
#Override
public void done(List<SingleContactInfo> contacts, ParseException error) {
if(contacts != null){
mAdapter.clear();
for (int i = 0; i < contacts.size(); i++) {
mAdapter.add(contacts.get(i));
mAdapter.notifyDataSetChanged();
}
}
}
});
}
ContactsAdapter.java
public class ContactsAdapter extends ArrayAdapter<SingleContactInfo> {
private final Context mContext;
private List<SingleContactInfo> mContacts;
public TextView mContactName;
public TextView mNumber;
public TextView mEdit;
public TextView mDelete;
public ContactsAdapter(Context context, List<SingleContactInfo> objects) {
super(context, R.layout.add_emergency_contacts_two, objects);
this.mContext = context;
this.mContacts = objects;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
convertView = mLayoutInflater.inflate(R.layout.add_emergency_contacts_two, null);
}
final SingleContactInfo contact = mContacts.get(position);
mContactName = (TextView) convertView.findViewById(R.id.emergency_contact_name);
mNumber = (TextView) convertView.findViewById(R.id.emergency_contact_number);
mEdit = (TextView) convertView.findViewById(R.id.edit_textView);
mDelete = (TextView) convertView.findViewById(R.id.delete_textView);
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteContactDialog(contact, mContext, position);
Toast.makeText(getContext(), "Deleted", Toast.LENGTH_LONG).show();
}
});
mContactName.setText(contact.getName());
mNumber.setText(contact.getNumber());
return convertView;
}
//TODO Look below here
public void deleteContactDialog(final SingleContactInfo contact, Context context, final int position) {
AlertDialog.Builder confirmDelete = new AlertDialog.Builder(context);
confirmDelete.setMessage("Are You Sure You Want to Delete Contact Person")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
} catch (ParseException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = confirmDelete.create();
dialog.show();
}
}
You just need to remove the item at the desired position from the ArrayList of contacts, and then notify the dataset:
public void onClick(DialogInterface dialog, int which) {
try {
mContacts.remove(position);
notifyDataSetChanged();
}
catch (ParseException e) {
e.printStackTrace();
}
}
Also, it's enough to call mAdapter.notifyDataSetChanged(); from outside your for cycle.
public void deleteContactDialog(final SingleContactInfo contact, Context context, final int position) {
AlertDialog.Builder confirmDelete = new AlertDialog.Builder(context);
confirmDelete.setMessage("Are You Sure You Want to Delete Contact Person")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Just add these two lines and you should be good.
mContacts.remove(position);
ContactsAdapter.this.notifyDataSetChanged();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = confirmDelete.create();
dialog.show();
}