NotifyDatasetChanged not working in customListView in android - android

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

Related

List is not refreshed after i delete an item in android

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

Delete item from listview after pressing delete textview in Adapter

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();
}

Android AlertDialog multiple choice mode issues

I have set my AlertDialog to CHOICE_MODE_MULTIPLE and get the data for the list from an API. It works almost fine, however, there are 2 problems I am having troubles with now.
The first one is more serious: After I check the items then click OK, sometimes when I go back to the dialog again it unchecks all of my checked items. This happens only 10-20% the times when I test so I do not know why it happens. I tried to save the values into a global variable in my class, or a public static variable I created when the app first started, still no luck.
When I click "Cancel", the checked items still update (it's supposed not to do so).
I am having a hard time against these 2 issues, any help is very much appreciated.
EDIT: Here is my custom dialog:
public class CustomMultichoiceDialog {
Set<String> selectedString = new HashSet<String>();
private String[] items;
private AlertDialog dialog;
private Builder builder;
private Context context;
private TestAdapter adapter;
public CustomMultichoiceDialog(Context context, String[] items) {
this.context = context;
this.items = items;
builder = new AlertDialog.Builder(context);
this.adapter = new TestAdapter(context, android.R.layout.simple_list_item_checked, this.items);
builder.setAdapter(this.adapter, null);
}
public AlertDialog show() {
if (this.dialog == null) {
this.create();
}
this.adapter.notifyDataSetChanged();
this.dialog.show();
return this.dialog;
}
public String[] getSelectedItems() {
String[] result = new String[this.dialog.getListView().getCheckedItemCount()];
SparseBooleanArray checked = this.dialog.getListView().getCheckedItemPositions();
int k = 0;
for (int i = 0; i < this.items.length; i++) {
if (checked.get(i)) {
result[k++] = this.items[i];
}
}
return result;
}
public String getSelectedItemAsString() {
return Arrays.toString(this.getSelectedItems()).replace("[", "").replace("]", "")
.replace(", ", ",");
}
public AlertDialog create() {
this.dialog = builder.create();
this.dialog.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
this.dialog.getListView().setSelector(new ColorDrawable(Color.TRANSPARENT));
return this.dialog;
}
public void setPositiveButton(final Callbacks callbacks) {
this.builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] selected = getSelectedItems();
callbacks.run(selected, getSelectedItemAsString());
cacheSelectedItems(selected);
}
});
}
public void setNegativeButton(final Callbacks callbacks) {
this.builder.setNegativeButton(this.context.getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
private void cacheSelectedItems(String[] selected) {
selectedString.addAll(Arrays.asList(selected));
}
public interface Callbacks {
public void run(String[] selectedItems, String selectedItemAsString);
}
class TestAdapter extends ArrayAdapter<String> {
public TestAdapter(Context context, int resource, String[] objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.text = ((CheckedTextView) view.findViewById(android.R.id.text1));
holder.text.setCheckMarkDrawable(R.drawable.checkbox);
}
if(selectedString!=null){
if(selectedString.contains(holder.text.getText().toString())) {
holder.text.setSelected(true);
holder.text.setChecked(true);
}
}
return view;
}
class ViewHolder {
CheckedTextView text;
}
#Override
public long getItemId(int position) {
return position;
}
}
}

my OnItemClickListener and OnItemLongClickListener didn't function at all

This is my MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
ArrayList<Product> products = new ArrayList<Product>();
final Context context = this;
ListAdapter boxAdapter;
String[] dataArray;
EditText editText;
//name that get back through the dialog
private String getName;
private String selectedItem;
private ArrayAdapter<String> adapter; // The list adapter
/** Called when the activity is first created. */
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
fillData();
boxAdapter = new ListAdapter(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
Button btn = (Button) findViewById(R.id.AddItem);
//the add item button function
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
//get the dialog view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.insert);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
getName=userInput.getText().toString();
products.add(new Product(getName,false));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
// Create the listener for normal item clicks
OnItemClickListener itemListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long rowid) {
Toast.makeText(
getApplicationContext(),
"You have clicked on " + parent.getItemAtPosition(position).toString() + ".",
Toast.LENGTH_SHORT).show();
}
};
//the long press to delete function
OnItemLongClickListener itemLongListener = new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Store selected item in global variable
selectedItem = parent.getItemAtPosition(position).toString();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Do you want to remove " + selectedItem + "?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
products.remove(selectedItem);
boxAdapter.notifyDataSetChanged();
Toast.makeText(
getApplicationContext(),
selectedItem + " has been removed.",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
// Signal OK to avoid further processing of the long click
return true;
}
};
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
}
void fillData() {
dataArray = getResources().getStringArray(R.array.ChecklistData);
for(String productName : dataArray)
{
products.add(new Product(productName,false));
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
This is ListAdapter.java
public class ListAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
ListAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
/*((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);*/
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
OnItemClickListener and OnItemLongClickListener didn't function at all. Anyone help me out here.. I did diagnose the problem but it still doesn't have function
OnItemClickListener itemListener = new OnItemClickListener() {
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
You just define those variables but you don't assign them to your ListView.
You should call these lines somewhere:
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
UPDATE:
You also miss to register the list for context menu.
registerForContextMenu(lvMain);
implement View.OnItemClickListener and AdapterView.OnItemLongClickListener and their corresponding methods in your class.
initialize your views correctly (findViewById...)
set click listeners to your views (button.setOnClickListener(this) / button.setOnLongClickListener(this)
react to the push events in the implemented methods like:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
this.doSomething();
}
}
and
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//react to the view or react to the position
switch (view.getId()) {
case R.id.button:
this.doSomething();
}
return true;
}
You need to register listeners. Add following lines to the end of your onCreate() method.
lvMain.setOnItemClickListener(itemListener);
lvMain.setOnItemLongClickListener(itemLongListener);
I had the exact same problem. When onclick or onlongclick are enabled in the Layout; onitemclickListener wont work. Just remove the tags android:clickable and android:longclickable from your Layout XML resource and it will all work.

ListView not reloading after data delete

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();
}

Categories

Resources