I am trying to implement ListView with Delete functionality to delete item from the listview. I am successful to delete but failed to refresh the listview after deletetion of an item from the database.
Actually, Click on listitem, i am displaying AlertBox for "Delete" and "Cancel" action, on clicking "Delete", item should be removed from the database and as well as from the listview and listview should be refreshed. I have also used notifyDataSetChanged() method.
lview = (ListView) findViewById(R.id.lview);
adapter = new ListView_CustomAdapter(this, listitemDisplay);
lview.setAdapter(adapter);
lview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
Show_Alert_box(v.getContext(),"Please select action.",position);
}
});
and the code for Show_Alert_box:
public void Show_Alert_box(Context context, String message,int position)
{
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
db.open();
String[] whereArgs={String.valueOf(pkID)};
return db.delete(DATABASE_TABLE_4,"pk_pkID == ?",whereArgs);
adapter.notifyDataSetChanged();
db.close();
}
catch(Exception e)
{
}
} });
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
alertDialog.setMessage(message);
alertDialog.show();
}
Does it remove it from your list adapter?
If not that would be the reason the notifyDataSetChanged() won't do you much good.
Actually looking at your code again i can only find that you're removing it from your database and not the adapter itself.
edit (to answer comment):
Well that's hard to do without your ListView_CustomAdapter class.
The problem is, in this adapter there's a data set (the one you put in the constructor (listitemDisplay)) which needs to be updated as well. Only then the notifyDataSetChanged() will work.
Call that Activity once again Using Intent
I'm guessing that using
getActivity().recreate();
instead of restarting the activity via a new Intent is better because using a new Intent will only stop the current activity and not destroy it.
Anyway, it works.
if you have the cursor, call requery() before calling notifyDataChanged()
I did something like this in my adapter:
((Activity)cxt).finish();
Intent intent = new Intent(cxt, YourActivity.class);
cxt.startActivity(intent);
This ends the activity and then starts the same one again.
I think instead of calling the activity again, you should set the adapter to the listview on the alertBox delete option after getting the updated data from the database and putting into listitemDisplay list like this.
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try
{
db.open();
String[] whereArgs={String.valueOf(pkID)};
return db.delete(DATABASE_TABLE_4,"pk_pkID == ?",whereArgs);
listitemDisplay = db.getItemFromDB();
adapter = new ListView_CustomAdapter(this, listitemDisplay);
lview.setAdapter(adapter);
db.close();
}
catch(Exception e)
{
}
} });
This will refresh the listView
I have the solution:
If you want to delete a row from a list view clicking on the DELETE button of each of that row do this. Here you have an example of a custom adapter class with a name and a delete button. Every time you press the button the row is deleted
public class UserCustomAdapter extends ArrayAdapter<User>{
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.btnDelete.setTag(position);
holder.textName.setText(user.getName());
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pos = v.getTag().toString();
int _posicion = Integer.parseInt(pos);
data.remove(_posicion);
notifyDataSetChanged();
}
});
return row;
}
static class UserHolder {
TextView textName;
Button btnDelete;
}
}
Try calling refreshDrawableState to tell the list to redraw.
Make a new function outside your onCreate block {something like... getdata()} and inside that insert and get all your data and set to the adapter.
Then call the function again in your onResume() block. So whenever you will delete the data from the list it will reflect immediately.
Related
Some Context: I have a Custom ArrayAdapter for a ListView that has 3 parameters Name, Edit Button, Delete Button. I have setup onClicks in the ArrayAdapter to be able to detect which profile is being clicked with the specific edit/delete button press. When the user deletes a profile I remove the profile from SQLite DB however now I've ran into the problem of trying to update the ArrayList with the removed item and notifyDataSetChanged for my ListView.
Question 1: I can't figure out if I should be doing this in the Class that is containing the ListView and ArrayList or if I should be trying to update this from the ArrayAdapter in the onClicks.
Question 2: Whatever method might be right how can I correctly update the deleted item from the ListView when the user confirms the delete in the Dialog.
Current ArrayAdapter Class
public class ListViewItemAdapter extends ArrayAdapter<ListViewItem>
{
private Context mContext;
private List<ListViewItem> list = new ArrayList<>();
private DatabaseHelper databaseHelper;
private String profileName;
public ListViewItemAdapter(#NonNull Context context, ArrayList<ListViewItem> listItem) {
super(context, 0 , listItem);
mContext = context;
list = listItem;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.custom_listview,parent,false);
final ListViewItem listViewItem = list.get(position);
//Text View Profile
final TextView name = (TextView) listItem.findViewById(R.id.textView_name);
name.setText(listViewItem.getmName());
profileName = listViewItem.getmName();
//Edit Button Profile
ImageButton image = listItem.findViewById(R.id.imageView_poster);
image.setImageResource(listViewItem.getmImageDrawable());
image.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(mContext,
"Edit Profile:" + listViewItem.getmProfile() + " Name:" + listViewItem.getmName(),
Toast.LENGTH_SHORT).show();
}
});
//Delete Button Profile **Currently Testing**
ImageButton image2 = listItem.findViewById(R.id.imageView_poster2);
image2.setImageResource(listViewItem.getmImageDrawable2());
image2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
databaseHelper = new DatabaseHelper(getContext());
Toast.makeText(mContext,
"Delete Profile:" + listViewItem.getmProfile() + " Name:" + listViewItem.getmName(),
Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(),R.style.AlertDialogTheme);
builder.setTitle("Delete Profile?")
.setMessage("Are you sure you want to delete\n" + listViewItem.getmName())
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteRowProfile(listViewItem.getmName());
//
//This is where I'm try to update the ListView
//
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
});
return listItem;
}
}
Function in Fragment Class that Populates the ListView onViewCreated
public void getProfileList()
{
arrayList = new ArrayList<ListViewItemAdapter>();
listViewItemAdapter = new ListViewItemAdapter(getContext(),arrayList);
Cursor result = databaseHelper.getAllDataCarProfile();
if(listViewItemAdapter != null){
listViewItemAdapter.clear();
listViewItemAdapter.notifyDataSetChanged();
}
if (result.getCount() != 0)
{
while (result.moveToNext())
{
arrayList.add(new ListViewItem("CarProfile",
result.getString(0),
R.drawable.ic_edit_gray_24dp,
R.drawable.ic_delete_grey_24dp));
}
listViewItemAdapter.notifyDataSetChanged();
}
listViewCarProfile.setAdapter(listViewItemAdapter);
}
You can do this in either way . You can create a function in your adapter class and perform the clickListener on it .
deleteItem.setOnClickListener(v -> {
potsList.remove(getAdapterPosition());
notifyDataSetChanged();
}
Or in your class , when remove the item from list , don't forget to notify the adapter . One the adapter get notified , it will reflect the change on screen.
There seems to be a problem when there are more than 5 records to
display on Manage Practice. For e.g. if there are 6 records to display on
Manage Practice. If I check the check box number 1, the check box number 6 also
gets checked. If there are 7 records, and if I check on 2nd record, then
the 7th record also gets automatically checked.I don't what's going on there I am very confusing, Please check my code let me know what's problem is there.
public class ManagePracticeLogAdapter extends BaseAdapter
{
//Variables to save class object.
Context context;
// variable to instantiates a layout XML file into its corresponding View objects.
LayoutInflater inflater;
MenuItem menu,addlog;
List<Integer> SelectedBox= new ArrayList<Integer>();;
// Variable to accept list data from Produce log activity
ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> temp_data;
HashMap<String, String> resultp = new HashMap<String, String>();
List<String> deleteData=new ArrayList<String>();
// Constructor to accept class instance and data.
public ManagePracticeLogAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist,MenuItem mymenu,MenuItem myaddlog)
{
this.context = context;
data = arraylist;
//temp_data.addAll(data);
menu=mymenu;
addlog=myaddlog;
}
#Override
public int getCount()
{
return data.size();
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
// Method to display data of Produce log Activity in list view
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if(convertView==null)
{
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView= inflater.inflate(R.layout.logitem1, parent, false);
}
TextView datetime;
TextView totminutes;
TextView skills;
TextView weather;
TextView day_night_icon;
final CheckBox chkdelete;
TextView approval_icon;
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
datetime = (TextView) convertView.findViewById(R.id.id_datetime);
totminutes = (TextView) convertView.findViewById(R.id.totminutes);
skills= (TextView) convertView.findViewById(R.id.id_skills);
weather=(TextView)convertView.findViewById(R.id.id_weather);
day_night_icon=(TextView)convertView.findViewById(R.id.day_night_icon);
approval_icon=(TextView)convertView.findViewById(R.id.conditions);
chkdelete=(CheckBox)convertView.findViewById(R.id.id_chkDelete);
// Capture position and set results to the TextViews
datetime.setText(resultp.get("date_time"));
if(!resultp.get("Day_minutes").toString().equalsIgnoreCase("0"))
{
totminutes.setText(resultp.get("Day_minutes")+" min");
day_night_icon.setBackgroundResource(R.drawable.sun);
}else
{
totminutes.setText(resultp.get("Night_minutes")+" min");
day_night_icon.setBackgroundResource(R.drawable.moon);
}
skills.setText(resultp.get("Skill"));
weather.setText(resultp.get("weather"));
String supervisorText=resultp.get("super");
Log.w("SUPERVISOR", supervisorText);
if(supervisorText.equals("No supervisor"))
{
approval_icon.setBackgroundResource(R.drawable.pending);
}else
{
approval_icon.setBackgroundResource(R.drawable.approve);
}
String fontPath = "fonts/Roboto-Light.ttf";
Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
datetime.setTypeface(tf);
totminutes.setTypeface(tf);
skills.setTypeface(tf);
weather.setTypeface(tf);
// chkdelete.setTag(R.id.id_chkDelete);
chkdelete.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
// int checkBoxId = (Integer) buttonView.getTag();
if(SelectedBox.size()-1==0)
{
menu.setVisible(false);
addlog.setVisible(true);
}else
{
addlog.setVisible(false);
}
if(isChecked)
{
SelectedBox.add(position);
menu.setVisible(true);
addlog.setVisible(false);
}else /*if(!isChecked)*/
{
SelectedBox.remove(SelectedBox.indexOf(position));
}
}
});
menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Student Driving Practice Log");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure want to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
try
{
NewNewDataHelper db=new NewNewDataHelper(context);
if(!SelectedBox.isEmpty())
{
for(int i=0;i<SelectedBox.size();i++)
{
resultp=data.get(SelectedBox.get(i));
String str[]=resultp.get("date_time").split(" ");
Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+resultp.get("Skill"));
db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);
/*resultp=data.get(SelectedBox.get(i));
String str[]=resultp.get("date_time").split(" ");
db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);*/
Toast.makeText(context,"Record Deleted", Toast.LENGTH_LONG).show();
}
Log.d("LISTSTSTSTST", SelectedBox.toString());
Intent intent = new Intent(context,ManagePracticeLogActivity.class);
intent.putExtra("s11", "delete");
context.startActivity(intent);
}
}catch(Exception e)
{
}
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return false;
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
resultp = data.get(position);
String str1 = null;
String str[]=resultp.get("date_time").toString().split(" ");
str1=str[0]+"~"+resultp.get("Skill")+"~"+str[1];
Log.d("PARTICULAR SKILLLLL", str1);
Intent intent = new Intent(context,LogEdit.class);
intent.putExtra("s11","Update Practice");
intent.putExtra("dataupdate",str1);
context.startActivity(intent);
}
});
return convertView;
}
private void deleteItems(List<Integer> list)
{
data.clear();
}
}
The problem is, view gets recycled due to recycling of ListView and the value of Checkbox(check or uncheck) is not maintained. You can check this link.
just have a look at this. This will explain the "problem" with checkboxes in listviews. There's also a link with a solution, if needed :)
When you load the view in getView, you need to set the check state for that particular item. I assume for each row you store this information somewhere? Just retrieve the correct state for the row (position) and set the correct state on the checkbox. The reason why you are seeing the behavior is because in a ListView rows are reused. The 6th row is in fact the 1st row. It is done this way to conserve memory and optimize a ListView for speed.
Inside your getView() add :
if(SelectedBox.contains(new Integer(position))) {
chkdelete.setChecked(true);
} else {
chkdelete.setChecked(false);
}
I delete database entry using onclicklistener but it is not refreshing the listview. how can i refresh this listview?
This is main class for listview:
public class AFragment extends Fragment implements OnItemClickListener {
protected static final String file_name ="user";
ListView list;
Database entry;
View v;
String values[];
MySimpleArrayAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
SharedPreferences settings = getActivity().getSharedPreferences(file_name, 0);
String name = settings.getString("name", null);
entry = new Database(getActivity());
entry.open();
values=entry.planlist(name);
entry.close();
if(values.length>0){
v = inflater.inflate(R.layout.activity_afragment, container,false);
adapter = new MySimpleArrayAdapter(getActivity(), values);
list=(ListView)v.findViewById(R.id.list);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(this);
}else{
v = inflater.inflate(R.layout.activity_my_tabs_listener, container,false);
}
// Toast.makeText(getActivity(),String.valueOf(values.length), Toast.LENGTH_LONG).show();
return v;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(),Details.class);
i.putExtra("sub", values[arg2]);
startActivity(i);
Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT).show();
}
}
Here i use onclicklistener to delete data from database but it is not refreshing:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public Business aFragment = new Business();
int mypos =0;
ViewHolder holder;
View row;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context,R.layout.activity_my_simple_array_adapter, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
mypos = position;
row = convertView;
holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(R.layout.activity_my_simple_array_adapter, parent, false);
TextView textView = (TextView) row.findViewById(R.id.text);
Button btn = (Button) row.findViewById(R.id.button1);
holder.tv = textView;
holder.btn = btn;
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.tv.setText(values[position]);
final int id = position;
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Database entry = new Database(context);
entry.open();
entry.delete(values[id]);
entry.close();
// Toast.makeText(getContext(), String.valueOf(id), Toast.LENGTH_LONG).show();
}
});
return row;
}
static class ViewHolder{
TextView tv;
Button btn;
}
}
as anil said, you should put notifyDataSetChanged(); inside the onClickListener
this basically tells the adapter to render the list again and will call getView() again for every visible item in the list, if your code crashes, you should check two things:
first - debug the program and check that the new data fits what you want, in your case, check that the entry was deleted properly.
second - debug the getView method, step through each call and see what gives you the crash.
in your case the problem is that you are only updating the database, but in fact your listview data is taken from the values[] array which is not updated after you delete the database entry, you should create a function for updating it.
Put adapter.notifyDataSetChanged(); on click of ListView
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Database entry = new Database(context);
entry.open();
entry.delete(values[id]);
entry.close();
adapter.notifyDataSetChanged();
// Toast.makeText(getContext(), String.valueOf(id), Toast.LENGTH_LONG).show();
}
If you do lots of adding and deleting to the list I think you should do the things below.
You should use ArrayList<String> instead of simple String[] so that you can easily delete. Database deletion do not effect the list directly unless you use Loaders
After you delete and item from the list, you should call notifyDataSetChanged() to the adapter. If you do not call this method, the list wont be updated.
adapter.notifyDataSetChanged();
you are removing it from the database but you are not removing it from the dataset that fills up your ListView. The simplest thing you can do is to change values from array to ArrayList, and since you are using an ArrayAdapter, you can call remove(int position). You need a List<T> of objects otherwise remove will throws an exception.
You can do one thing.
Firstly create a method called myAdapter().
In this put your creation of adapter code,so you can create new adapter for loading new data by simply calling myAdapter() method.
Whenever there should be modification in your ListView just called the following code,
listview.invalidate();
Then simply call the myAdapter().
That's it.Hope this is useful to you..:)
So I have a listview that I want to add checkboxes to.
lv = (ListView)findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems);
lv.setAdapter(adapter);
lv.setItemsCanFocus(true);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
This works and the checkboxes show up. Then I have my setOnItemClickListener() for my listview because the user needs to select an item, then the next acitivty will be launched
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
Intent components = new Intent();
components.setClass(context, ComponentsActivity.class);
components.putExtra("studyID", studyID);
components.putExtra("studyName", studyName);
startActivity(components);
}
});
However, I want to add a checkbox so that the user can tick that item in the listview to perform other actions. The problem is I can't differentiate the events. When I click on the checkbox, it gets checked but then the list item also gets selected and the new activity starts. I only want the checkbox to be affected when they click on it, not have it launch the new acitivty. I know you can also just create your own adapter but why bother if I can make a checkbox in 2 lines of code. Any suggestions? I just want to be able to check the textbox and get the id of the checked items.
I never managed to find anything for what I was looking for so I bit the bullet and decided to learn how to make my own custom adapter class. Here is my code if anybody ever runs into this problem. This adapter class is for a listview with text(TextView) and a checkbox.
public class CustomAdapter extends BaseAdapter
{
ArrayList<String> studies;
Context context;
LayoutInflater myInflater;
ArrayList<Boolean> positionArray;
public CustomAdapter(ArrayList<String> arr, Context c)
{
studies = arr;
context = c;
myInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
positionArray = new ArrayList<Boolean>();
for(int i = 0; i < studies.size(); ++i)
{
positionArray.add(false);
}
}
#Override
public int getCount() {
return studies.size();
}
#Override
public Object getItem(int i) {
return studies.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
public void remove(int i)
{
this.studies.remove(i);
this.positionArray.remove(i);
}
#Override
public View getView(int position, View view, ViewGroup viewGroup)
{
final int pos = position;
Holder holder = null;
//Create the views and populate it with an element from teh array
if(view == null)
view = myInflater.inflate(R.layout.custom_list_layout, viewGroup, false);//made my own layout for each listview 'cell'
holder = new Holder();
TextView study = (TextView)view.findViewById(R.id.adapterTextView);
holder.ckbox = (CheckBox)view.findViewById(R.id.adapterCheckBox);
holder.ckbox.setOnCheckedChangeListener(null);
study.setText(studies.get(position));
holder.ckbox.setFocusable(false);
//Since this method gets called whenever we scroll(view recycling), we have to re-check the checkboxes
holder.ckbox.setChecked(positionArray.get(position));
holder.ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
//checkBoxArray[pos].setChecked(isChecked);
positionArray.set(pos, isChecked);
}
});
return view;
}
static class Holder
{
CheckBox ckbox;
}
}
I want to delete a row from my list view on click of "delete" button. My listview item has following things placed horizontally: TextView-1,TextView-2,TextView-3,ImageButton-delete button. Now when I click delete button, the row should be deleted from the view. Below is the adapter code;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = (View) v.getParent();
TextView tv = (TextView) view.findViewById(R.id.item_name);
String item = tv.getText().toString();
String tableno = mListItems.get(0).getTableNumber();
orderDetailsDB = new OrderDetailsDBAdapter(
getApplicationContext());
orderDetailsDB.deleteItem(item,tableno);
I tried by setting Individual textviews to blank but its not working.
holder.itemName.setText("");
holder.amount.setText("");
holder.quantity.setText("");
I read couple of posts and they suggest to remove item from my list(mListItems) and then do adapter.notifyDataSetChanged();. Problem is I am not using array adapter for populating list view but using Custom adapter, so unable to get the position for item to be deleted. Please advise. thanks.
First write below line in your adapter's getView method.
button.setTag(position)
in onClick method
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
yourarraylistObject.remove(position);
// your remaining code
notifyDataSetChanged();
}
Just use remove() to remove list item from the adapter
for your reference
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
What you can do in order to get the position that you want to delete is to pass that into your listener:
// inside custom adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
.....
deleteButton.setOnClickListener(new MyClickListener(position);
}
private class MyClickListener implements OnClickListener
{
int position = -1;
public MyClickListener(final int position)
{
this.position = position;
}
#Override
public void onClick(View v) {
// do your delete code here
notifyDataSetChanged();
}