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();
}
Related
I am passing an integer array-list that hold the selection and retrieve it based on selection but when I remove the item from check selection it is not remove from array list displayed in text. Here is my logic to handle multiple check.
public class MainFragment extends Fragment {
private Button buttonUser;
String[] listItems;
boolean[] checkedItems;
ArrayList<Integer> mUserItems = new ArrayList<>();
private Context context;
private AppCompatTextView compatTextView;
public static MainFragment newInstance() {
return new MainFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listItems = getResources().getStringArray(R.array.person_array);
checkedItems = new boolean[listItems.length];
context = getActivity();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
buttonUser = (Button) view.findViewById(R.id.buttonUser);
compatTextView = (AppCompatTextView) view.findViewById(R.id.text_view_selection);
buttonUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Select Person");
alert.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(which)) {
mUserItems.add(which);
}
} else if (!mUserItems.contains(which)){
mUserItems.remove(which);
}
}
});
alert.setCancelable(false);
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String items = "";
for (int i = 0; i < mUserItems.size(); i++) {
items = items.concat(listItems[mUserItems.get(i)]);
if (i != mUserItems.size() - 1) {
items = items + ", ";
}
compatTextView.setText(items);
}
}
});
alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
});
return view;
}
}
And I am not getting this part of logic how to handle
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
if (!mUserItems.contains(which)) {
mUserItems.add(which);
}
} else if (!mUserItems.contains(which)){
mUserItems.remove(which);
}
}
It's somewhat correct but when I deselects the choice from alert dialog the list is not update and display the previous check data.
I think the else if part would yield false if isChecked is false. May be it should be like this?: else if (mUserItems.contains(which))
I want to display user chats from a Firebase List in a ListView with a custom Adapter. But somehow it does not work. I get a response when I try to look at the data in the logcat but when I pass the list to the CustomAdapter it does not display anything in my ListView. What is the issue?
My Adapter:
public class ChatAdapter extends ArrayAdapter<String> {
private Activity context;
private List<Chats> chatsList = new ArrayList<>();
public ChatAdapter(Activity Context, List<Chats> chatsList) {
super(Context, R.layout.abc_main_chat_item);
this.context = Context;
this.chatsList = chatsList;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.abc_main_chat_item, null, true);
TextView tvusername = (TextView) listViewItem.findViewById(R.id.group_name);
TextView tvuid = (TextView) listViewItem.findViewById(R.id.useruid);
TextView tvlastmessage = (TextView) listViewItem.findViewById(R.id.latestMessage);
TextView tvlastmessagetime = (TextView) listViewItem.findViewById(R.id.latestMessageTime);
ImageView ivphoto = (ImageView) listViewItem.findViewById(R.id.profileImg);
tvusername.setText(chatsList.get(position).getUsername());
tvlastmessage.setText(chatsList.get(position).getLastMessage());
tvlastmessagetime.setText(chatsList.get(position).getLastMessageTime());
tvuid.setText(chatsList.get(position).getUseruid());
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(ivphoto);
listViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, Chat_Room.class);
i.putExtra("room_name", chatsList.get(position).getUsername());
i.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(i);
}
});
listViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_listview_alertdia_layout);
ArrayList<String> list_of_chats = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list_of_chats);
list_of_chats.add(0, "Chatverlauf mit "+ chatsList.get(position).getUsername()+" löschen?");
list_of_chats.add(1, "Profil von "+chatsList.get(position).getUsername()+" anschauen");
arrayAdapter.notifyDataSetChanged();
final ListView lv = (ListView) dialog.findViewById(R.id.lv);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position2, long id) {
if (position2 == 0) {
dialog.dismiss();
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Chatverlauf mit "+chatsList.get(position).getUsername()+" löschen?")
.setMessage("Du kannst das Löschen nicht rückgängig machen. Bist du dir sicher?")
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(chatsList.get(position).getUseruid()).setValue(null);
FirebaseDatabase.getInstance().getReference().child("chats").child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("messages").child(chatsList.get(position).getUseruid()).setValue(null);
}
}).setCancelable(true)
.show();
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
if (position2 == 1) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
}
});
dialog.show();
return true;
}
});
ivphoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.abcd_profile_pic_dialog_layout);
ImageView imageView = (ImageView) dialog.findViewById(R.id.alertImage);
TextView textView = (TextView)dialog.findViewById(R.id.alertdialogtv);
ImageView message = (ImageView)dialog.findViewById(R.id.alertMessage);
ImageView profile = (ImageView)dialog.findViewById(R.id.alertProfile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ViewContact.class);
intent.putExtra("useruid", chatsList.get(position).getUseruid());
context.startActivity(intent);
dialog.dismiss();
}
});
message.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), Chat_Room.class);
intent.putExtra("room_name", chatsList.get(position).getUsername());
intent.putExtra("room_uid", chatsList.get(position).getUseruid());
context.startActivity(intent);
}
});
Picasso.with(getContext()).load(chatsList.get(position).getPhotoURL()).placeholder(R.drawable.ic_person_grey_round).into(imageView);
textView.setText(chatsList.get(position).getUsername());
dialog.setCancelable(true);
dialog.show();
}
});
return listViewItem;
}
...
}
And this is how I get the data for the List:
FirebaseDatabase.getInstance().getReference().child("chats").child("userchats").child(myUiD).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<chatapp.chatapp2.Chats.Chats> chatsList = new ArrayList<chatapp.chatapp2.Chats.Chats>();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
chatapp.chatapp2.Chats.Chats chats = new chatapp.chatapp2.Chats.Chats();
chats.setUsername(snapshot.child("roomname").getValue().toString());
chats.setPhotoURL(snapshot.child("photoURL").getValue().toString());
chats.setLastMessage(snapshot.child("lastMessage").getValue().toString());
chats.setLastMessageTime(snapshot.child("lastMessageTime").getValue().toString());
chats.setUseruid(snapshot.child("userUiD").getValue().toString());
chatsList.add(chats);
Log.d("CHATS", chats.getUsername());
Log.d("CHATS", chats.getUseruid());
}
ChatAdapter chatAdapter = new ChatAdapter(getActivity(), chatsList);
chatAdapter.notifyDataSetChanged();
listView.setAdapter(chatAdapter);
listView.setVisibility(View.VISIBLE);
}
...
});
I dont really know why it does not worked, but I found the Solution:
You have to override the getCount method like this:
#Override
public int getCount() {
return chatsList == null ? 0 : chatsList.size();
}
I do not know what it does but it works :) :)
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
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.
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();
}