how Create setAdapter() for a AlertDialog - android

I created a CustomDialogBuilder that extends Dialog... I want to create the method setApater().. I created that section but the onClick method on the adapter is not working..
My customDialogBuilder class is given below.
public class CustomAlertDialog extends Dialog
{
public CustomAlertDialog(Context c, int theme) {
super(c, theme);
}
public static class Builder
{
private Context context;
private String title;
private String message;
private String positiveButtonText;
private String negativeButtonText;
private View contentView;
private ListAdapter adapter;
private ListView listView;
private DialogInterface.OnClickListener
positiveButtonClickListener,
negativeButtonClickListener,adapterListener;
public Builder(Context c)
{
context =c;
}
public Builder setTitle(String title)
{
this.title =title;
return this;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public Builder setContentView(View v)
{
contentView =v;
return this;
}
public Builder setAdapter(ListAdapter adapter,DialogInterface.OnClickListener listener)
{
this.adapter=adapter;
return this;
}
public Builder setPositiveButton(String positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = positiveButtonText;
this.positiveButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(String negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = negativeButtonText;
this.negativeButtonClickListener = listener;
return this;
}
public CustomAlertDialog create()
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final CustomAlertDialog dialog = new CustomAlertDialog(context,
R.style.Dialog);
View layout = inflater.inflate(R.layout.dialog_title_layout, null);
dialog.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
((TextView) layout.findViewById(R.id.tv_custom_dialog_title)).setText(title);
if (positiveButtonText != null) {
((Button) layout.findViewById(R.id.bt_custom_dialog_positive))
.setText(positiveButtonText);
if (positiveButtonClickListener != null) {
((Button) layout.findViewById(R.id.bt_custom_dialog_positive))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
positiveButtonClickListener.onClick(
dialog,
DialogInterface.BUTTON_POSITIVE);
}
});
}
}
else
layout.findViewById(R.id.bt_custom_dialog_positive).setVisibility(
View.GONE);
if (negativeButtonText != null) {
((Button) layout.findViewById(R.id.bt_custom_dialog_negative))
.setText(negativeButtonText);
if (negativeButtonClickListener != null) {
((Button) layout.findViewById(R.id.bt_custom_dialog_negative))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
positiveButtonClickListener.onClick(
dialog,
DialogInterface.BUTTON_NEGATIVE);
}
});
}
} else {
// if no confirm button just set the visibility to GONE
layout.findViewById(R.id.bt_custom_dialog_negative).setVisibility(
View.GONE);
}
if (message != null) {
((TextView) layout.findViewById(
R.id.tv_custom_dilaog_message)).setText(message);
}
else if(adapter!=null)
{
listView = new ListView(context);
listView.setAdapter(adapter);
((LinearLayout) layout.findViewById(R.id.Layout_custom_dialog_content))
.removeAllViews();
((LinearLayout) layout.findViewById(R.id.Layout_custom_dialog_content))
.addView(listView);
if(adapterListener!=null)
{
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
}
});
}
}
else if (contentView != null) {
// if no message set
// add the contentView to the dialog body
((LinearLayout) layout.findViewById(R.id.Layout_custom_dialog_content))
.removeAllViews();
((LinearLayout) layout.findViewById(R.id.Layout_custom_dialog_content))
.addView(contentView,
new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
return dialog;
}
}
}
how we can create the correct setAdapter() which is similar to setAdapter() in AlertDialog.
This is how I create dialog using this class:
Dialog dialog = null;
String[] items = {"Edit profile","Change doctor","Change password","Logout"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Loged.this,
R.layout.my_spinner_layout, items);
CustomAlertDialog.Builder customBuilder = new
CustomAlertDialog.Builder(Loged.this);
customBuilder.setTitle("Options")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.e("dis",""+which);
}
});
dialog = customBuilder.create();
dialog.show();

hureyyy...... got the answer........
change the setAdapter function in our CustomDialog class... as
public Builder setAdapter(ListAdapter adapter,DialogInterface.OnClickListener listener)
{
this.adapter=adapter;
this.adapterListener=listener;
return this;
}

Related

How to wire up a delete button to delete one item on a listview?

I know there are lots of threads with more or less same topic but none of them covers my situation:
I am trying to get my delete button to delete one row on the list view and the delete button appear in each row I got this part to work but I can't get it to work in my Main Activity. The code keeps breaking every time I put this part in my code:
ImageButton removeButton = (ImageButton) findViewById(R.id.btnDel);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRemoveButtonClick();
}
private void onRemoveButtonClick() {
ToDoItem item = (ToDoItem) v.getTag();
notifyDataSetChanged();
}
my MainActivity works fine without this bit of code. I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
ToDoItemAdapter adapter = new ToDoItemAdapter(this, listManager.getList());
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
listManager.saveList();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Add item to list
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
Log.i(LOG_TAG, input.getText().toString());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int Which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
public ToDoItemAdapter(Context context, List<ToDoItem> items){
super(context,-1, items);
this.context = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
}
TextView textView = (TextView) convertView.findViewById(R.id.item);
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
textView.setText(items.get(position).getDescription());
checkBox.setChecked(items.get(position).isComplete());
convertView.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) v.getTag();
item.toggleComplete();
notifyDataSetChanged();
}
});
return convertView;
}
}
}
ToDoListManager.java
public class ToDoListManager {
private static final String APP_PREFERENCES = "todoapp";
private static final String TODO_ITEMS = "itemslist";
private List<ToDoItem> items;
private SharedPreferences savedData;
public ToDoListManager(Context context) {
savedData = context.getSharedPreferences (
APP_PREFERENCES,
Context.MODE_PRIVATE
);
String json = savedData.getString(TODO_ITEMS, null);
if (json == null) {
items = new ArrayList<>();
} else {
Type type = new TypeToken<List<ToDoItem>>() {}.getType();
items = new Gson().fromJson(json, type);
}
}
public List<ToDoItem> getList() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
saveList();
}
public void saveList() {
SharedPreferences.Editor edit =savedData.edit();
edit.clear();
String json = new Gson().toJson(items);
edit.putString(TODO_ITEMS, json);
edit.apply();
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
public ToDoItem (String description,boolean isComplete) {
this.description = description;
this.isComplete = isComplete;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
#Override
public String toString() {
return description;
}
}
enter image description here
1.) Add a button to your to_do_item_layout first
2.) Now add this code to add a button to each item
Button btn = (Button) convertView.findViewById(R.id.my_btn);
3.) Add a listener to it
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
}
});

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

How to make dynamically add or remove edit text in listview

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

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

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