In my code there is a listview in which i am doing an operation to delete the listview item. it works but remains displayed in the listview. It is in the second activity.It disappears only after going to the firstactivity and then returns.Please give me the changes that i have to make.
Getclicker.java
public void onItemClick(AdapterView<?> a, View v, int position, final long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(Getclicker.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete the event" + (position+1));
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
eventsData1.delete( id);
adapter.notifyDataSetChanged();
}});
adb.show();
}
delete method in database
public void delete(long id) {
SQLiteDatabase db = this.getReadableDatabase();
db.delete(DATABASE_TABLE, KEY_ROWID + " = ?",
new String[] { String.valueOf(id )});
db.close();
}
As I see, right now you're deleting an item from Database, but you're not deleting it from adapter, that's why deleted item is still in the ListView. When you go to another activity and then go back to the listView, you load changed data in the adapter.
You should delete an item from the adapter too if you want notifyDataSetChanged() to have an effect . . .
Your code should be something like this:
eventsData1.delete( id);
adapter.deleteItem(id);
adapter.notifyDataSetChanged();
add delete() method in your Adapter class . . .
You are deleting on the basis of id i.e Long Type
eventsData1.delete( id);
You should use "position"
eventsData1.delete(position);
adapter.notifyDataSetChanged();
As you mentioned your deleting operation is working fine but the problem is in listView refreshing. Untill and unless you are changing the activity it is not refreshing your list. What you have to really do is that you have to add this piece of code at the end of the line where deleting operation is ending within onItemClick:
yourListView.setAdapter(yourAdapter);
Related
I have a database app.I want to make each item disappear from main screen after deleting it. It gets deleted after long press but becomes invisible after I exit the app and then again enter. So, how to disappear each item from main screen instantly after a long press?
Here is my code snippet to delete each item----
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
FriendsDbHelper fdb = new FriendsDbHelper(MainActivity.this);
SQLiteDatabase db = fdb.getWritableDatabase();
db.delete(TABLE_NAME,_ID+"=?",new String[]{Long.toString(id)});
return true;
}
});
As you appear to be using a Cursor Adapter (i.e. you are deleting according to the id) then you need to
a) re-build the Cursor and then
b) use either the adapter's swapCursor or notifyDataSetChanged methods.
Note! If you are not using a Cursor Adapter then you will probably
encounter issues if you use the id passed to the
setOnItemLongClickListener method, as this will not necessarily be
the row's id but it will be the same value as position. At first it
would appear to work but could the start deleting the wrong rows or
not delete any rows.
You code would be along the lines of :-
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
FriendsDbHelper fdb = new FriendsDbHelper(MainActivity.this);
SQLiteDatabase db = fdb.getWritableDatabase();
db.delete(TABLE_NAME,_ID+"=?",new String[]{Long.toString(id)});
mycursor = fdb.your_method_to_get_the_cursor(); //<<<< will need changing
your_adapter.swapCursor(mycursor); //<<<< will need changing
return true;
}
});
Here's a working example :-
// Get the ListView according to it's id
imagelist = (ListView) findViewById(R.id.imagelist);
// Get the Cursor
images = imgdbhlpr.getAllImages();
// Instantiate the Cursor Adapter
sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
images,
new String[]{ImgDBHelper.DSCR_COL},
new int[]{android.R.id.text1},
0
);
//
imagelist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
imgdbhlpr.deleteImageRow(id);
images = imgdbhlpr.getAllImages();
sca.swapCursor(images);
return true;
}
});
imagelist.setAdapter(sca);
You need to remove it from the listView. You need to call your list adapter and then call the method notifyDataSetChanged()
I pass data from a ListView to another ListView with SharedPreference. I can write items and can remove an item of them.
After I delete item,I restart this page and I see item which I deleted. I cannot remove it permanently.
MainActivity
final DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
final List<DataProvider> list = new ArrayList<>(Arrays.asList(providers));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final DataProvider dataProvider = (DataProvider) adapterView.getItemAtPosition(i);
AlertDialog.Builder builder = new AlertDialog.Builder(Listele1.this);
builder.setMessage("Silinsin mi ?")
.setCancelable(false)
.setPositiveButton("EVET", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
list.remove(dataProvider);
prefAdapter.notifyDataSetChanged();
}
})
try change
prefAdapter.notifyDataSetChanged();
for notifyItemRemoved("here, position you has deleted");
notifyItemRangeChanged("here, position you has deleted" ,"your array".size());
When you are passing data form ListView 1 to ListView 2 using SharedPreference.
using below 2 lines.
final DataProvider[] providers = gson.fromJson(jsonurun, DataProvider[].class);
final List<DataProvider> list = new ArrayList<>(Arrays.asList(providers));
You only remove data from Listview 2 ie: list in your
case : list.remove(dataProvider);
And forgot to delete the data from SharedPreference at same time.That's why when restart the page your deleted item is visible again.
In short try to remove data form SharedPreference as well after performing
list.remove(dataProvider);
prefAdapter.notifyDataSetChanged();
I am making a ToDo List and have troubles with deleting an item from ListView.
If the User has done one thing on his list, he can click on that item and it will be either striked through, or the strike trhough will be undone:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
int i_strikethrough = tv.getPaintFlags();
if(i_strikethrough == 1297){
tv.setPaintFlags(tv.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
} else if (i_strikethrough == 1281){
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
});
If the user makes a long click, a message will pop up and he can choose to delete this item:
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Delete");
alertDialogBuilder.setMessage("Are you sure you want to delete?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
adapterInhalt.remove(adapterInhalt.getItem(position));
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
});
Now, my problem is the following:
Imagine the second Item is striked through but the third is not.
If i delete the second Item, then the third Item is at second place and is striked through. But it should not be striked through.
I hope that you understand my problem and that you can help me solving this issue.
I hope this picture will help you understanding the issue:
A helping Picture
You aren't implementing a list view properly. List views recycle views. This means they reuse the same views and put different positions in your list into them. This provides very efficient UI code. It also means that if you make any changes to the view outside of getView of your adapter that those changes will be applied to the wrong item when you remove or scroll.
The write way to make a listview is that if you want to update the UI of any position, you change the model of that position. THen you tell the adapter that it needs to update by calling notifyDataSetChanged(). The getView function will then get called to redraw each visible element and should apply the strike through.
You should define a class for your items, that has a boolean field for strike status. for example:
public class MyItem{
String name;
boolean isStriked;
}
then you can check if an item is striked through on adapter's getView() method. you can increase the cohesion in your code this way. BTW I recommend using RecyclerView as it has predefined methods and animations for item deletion
I can't get this working. I want the item from list view to be deleted when I click on the button. But I really don't know how to implement this.
Here is my adapter
public class PersonalRecordsAdapterDialog extends CursorAdapter {
public PersonalRecordsAdapterDialog(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_view_personal_layout, parent, false);
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
final DatabaseAdapter db = new DatabaseAdapter(context);
TextView weightTV = (TextView) view.findViewById(R.id.weight_tv);
TextView dateTV = (TextView) view.findViewById(R.id.date_tv);
final Button deleteRecord = (Button) view.findViewById(R.id.delete_record);
final String id = cursor.getString(cursor.getColumnIndex(DatabaseAdapter.DatabaseHelper.COL_1));
String weight = cursor.getString(cursor.getColumnIndex(DatabaseAdapter.DatabaseHelper.COL_3));
String date = cursor.getString(cursor.getColumnIndex(DatabaseAdapter.DatabaseHelper.COL_4));
weightTV.setText(weight);
dateTV.setText(date);
deleteRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.remove(Integer.parseInt(id));
notifyDataSetChanged();
}
});
}
}
and here is my ListView
AlertDialog.Builder builder = new AlertDialog.Builder(holder.mContext);
View dialogView = View.inflate(holder.mContext,R.layout.dialog, null);
ListView myList = (ListView) dialogView.findViewById(R.id.dialog_list_view);
Cursor cursor = holder.myDb.getRows(exercise[position]);
PersonalRecordsAdapterDialog adapter = new PersonalRecordsAdapterDialog(holder.mContext,cursor);
myList.setAdapter(adapter);
builder.setView(dialogView)
.setTitle("History of your " + exercise[position].toLowerCase() + " records")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
});
AlertDialog b = builder.create();
b.show();
Thank you for your help
Remove the item from your model when onClick happens n call notifyDatasetChanged() for the same adapter
and in your case you are passing cursor directly to your custom adapter which is a very bad practice as in this case your connection with the db will stay open and can lead to Memory and DB issues
So you can create your own model (ArrayList) , get values from cursor, add them into your model,Close your db connection and pass that model to your adapter. and to remove a particular item remove that from your model and call notifyDatasetChanged().(Note: Removing from model will only remove the data from list but not from db. In case you want to delete that data from your db, you also have to execute Delete Query )
for this : I don't want to delete it when I click on ListView item. I want to delete it only when I click on button in ListView item
Go to your adapter class.. get the object instance over there in OnGetView(...) method and the the onClickListener for the same over there.
To delete row from DB you can use a unique id from db table like this
public void delete_byID(int id){
sqLiteDatabase.delete(MYDATABASE_TABLE, KEY_ID+"="+id, null);
}
Where MYDATABASE_TABLE is your table to delete from.
KEY_ID is the name of the coloumn to put where condition.
id is the unique id associated with the row you want to delete
So in this case you will not need the cursor to delete a particular record
The reason that bindView method doesn't refresh by the db change is :
The cursor is steel the old cursor .
You need to requery the data base get new cursor and then
Call adapter.change cursor(passHereTheNewCursor)
Adding to above answer by Nitesh - To delete item from listview on button click, Either 1. first you need to delete item from listview's adapter like below -
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Object objToRemove = adapter.getItem([POSITION]);
adapter.remove(objToRemove);
}
}
or 2. you can delete this item from your arrayList & call notifyDataSetChanged().
But this will not delete from database. you have to implement delete query for it.
and yes as above said -
in your case you are passing cursor directly to your custom adapter which is a very bad practice as in this case your connection with the db will stay open and can lead to Memory and DB issues.
UPDATE
The original question i asked was about my long id value but because you guys were right in the way u said i had the correct id i removed my error. Thanks for the help. read my answer for more detail.
1) My app uses the local android SQLiteDatabase and has three tables. I have no problems for two of the tables but turns out my third one is presenting some issues because of my column declarations are public static final string COLUMN_NAME = "name"; ,etc.
My Activities are not extending the ListActivity so that I can have custom lists and listviews for each activity.
I am getting my listview by listview = (ListView) findViewById(R.id.myList); and adding a listener to the listview by listview.setOnItemClickListener(ListListener); Then here is my method for the list listener:
OnItemClickListener ListListener = new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View v, int position,
final long id)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(ExerciseList.this)
.setIcon(R.drawable.edit)
.setTitle("Update Selected Exercise")
.setMessage("Would you like to update the current Exercise? Click continue to proceed.")
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
final Intent i = new Intent(getBaseContext(), AddExercise.class);
i.putExtra(ExerciseDbAdapter.KEY_ROW_ID, id);
startActivityForResult(i, EDIT_EXERCISE);
}
})
.setNegativeButton("Back", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
};
This above method is just a working on list item click listener!
Intent.putExtra("Key",value) is right way to put the data in intent so
i.putExtra("INSERT THE KEY HERE",ExerciseDbAdapter.KEY_ROW_ID, id);
Okay guys so i found the issue with my application and you were all right. I was getting the correct row id from the application.
I however was passing another data member through my intent causing the setRowIdFromIntent() method to change the id from null to 0. or from not null to 0.
Basically no matter what the value i was passing it was being set to 0 from my setRowIdFromIntent() method because of the data member i passed through. Therefore the above code is almost irrelevant to my problem.
So if you want a working on click list listener the one above will definitely help you pass the correct id to your new activity. Sorry again for this confusion I had on my side. Thanks again for all other postings!