Android Studio, Remove ListView Item without affecting another Item - android

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

Related

How to setOnItemSelectedListener on several Dynamically created spinners

I have an Activity where I need to create 1 or more spinners dynamically according to an external DB.
SOme of this spinner items have to show a dialog according what value does the spinner has. For example the spinner has this options:
-Own
-Rental
-Family House
If the user selects Rental I have to show a dialog (or anything) asking him how much does he pays per month. If he selects own, or family nothing should happen.
After I create the layout with the spinners, edittexts, etc. Im using something like this:
for(int q=0;q<=parent.getChildCount();q++){
View v = parent.getChildAt(q);
if (v instanceof Spinner) {
Spinner res = (Spinner) v;
res.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//Here its supposed to show dialog if the option is "RENT"
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
}
}
The problem is that when I do this the "setOnItemSelectedListener" only sets for the last spinner on the layout.
How can I do what Im trying? I dont know what else to do.
The easiest solution would probably be to make one Listener as a variable and use that for all of your spinners. To do this, you would not set it as you are currently (using the anonymous inner-class style) and instead would do this:
//This goes outside of the method
private AdapterView.OnItemSelectedListener listener =
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Spinner Selected ID = " + parent.getId());
/*
Put a check here for which one is being selected.
While you could use the parent to check, in your case, it will be easier
to use something from your DB table as a unique identifier (maybe a column
name would be ideal? Your pick)
*/
//Show your dialogs here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
return;
}
};
//This is the method you have where you are iterating the parent object
private void doStuff(){
for(int q=0;q<=parent.getChildCount();q++){
View v = parent.getChildAt(q);
if (v instanceof Spinner) {
Spinner res = (Spinner) v;
res.setOnItemSelectedListener(listener);
}
}
}
Good luck to ya!

List.Remove always removes last item for ListView

When i try to remove a specific item from a list View:
buyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tempToken -= selPerk.cost;
plrPerks.add(selPerk);
String tokStr = String.valueOf(tempToken);
tkn.setText(tokStr);
shopItems.remove(selPerk);
selPerk = new Perk();
perkDialog.dismiss();
}
});
It always seems to remove the last item. This is where i open the dialog:
perks.setClickable(true);
perks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Perk perk = (Perk) perks.getItemAtPosition(position);
showItem(perk);
}
});
}
This is the show Item function:
public void showItem(Perk perk) {
if (tempToken >= perk.cost) {
selPerk = perk;
How do i remove a specific item from a list and list view respectively?
Thanks for your time :)
In "setOnItemClickListener" listener, you are getting the perk object. So you can remove that object from your list like this-
shopItems.remove(perk);
and then you can call-
your_adapter.notifyDataSetChanged();
to refresh your listview.
To remove a specific item from a list view, your can call removeView(View toBeRemoved) if you have a reference to the view you wish to remove. If you have the index, you can call removeView(int index).
http://developer.android.com/reference/android/widget/ListView.html
You can remove a specific item from a list in the same way, using remove(Object item) or remove(int index).
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
Hope this helps!
I fixed it. Whenever i removed an item i had to do it like so:
shopItems.remove(selPerk);
perk_adapter.notifyDataSetChanged();
So i had to notify my listeview adapter that i removed an item.

How to change other items in a Android ListView when one item is clicked

I have a ListView that contains items with checkboxes that should behave sometimes like a CHOICE_MODE_MULTIPLE and sometimes like a CHOICE_MODE_SINGLE. What I mean is for certain items in the list, when selected certain other items needs to be deselected whilst other can remain selected.
So when item A is checked I can find in my data the item B that needs to be unchecked but how do I get the UI to refresh to show this as I (I believe) cannot find the actual View that represents B but just it's data?
It sounds like you're off to a good start. You're right that you should be manipulating the underlying data source for item B when A is clicked.
Two tips that may help you:
Your getView() method in the Adapter should be looking at your data source and changing convertView based on what it finds. You cannot find the actual View that represents B because in a ListView, the Views are recycled and get reused as different data needs to be displayed. Basically, when an item is scrolled off the list, the View that was used gets passed to the getView() function as convertView, ready to handle the next element's data. For this reason, you should probably never directly change a View in a ListView based on user input, but rather the underlying data.
You can call notifyDataSetChanged() from within your adapter to signal that somewhere the underlying data has been changed and getView() should be called again for the elements currently displayed in your list.
If you're still having trouble, feel free to post some code that illustrates the specific problem that you're having. It's much easier to provide concrete advice when the problem is better defined. Hope this helps!
you can use singleChoice alartDialog, i have used like:
private int i = 0; // this is global
private final CharSequence[] items = {"Breakfast", "Lunch", "Dinner"}; // this is global
Button settings = (Button)view.findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
//Title of Popup
builder.setTitle("Settings");
builder.setSingleChoiceItems(items, i,
new DialogInterface.OnClickListener() {
// When you click the radio button
public void onClick(DialogInterface dialog, int item){
i=item;
}
});
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (i == 0) {
//it means 1st item is checked, so do your code
}
if (i == 1) {
//it means 2nd item is checked, so do your code
} /// for more item do if statement
}
});
//When you click Cancel, Leaves PopUp.
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
});
i have initialized i=0, so that for the very first time when user click on settings button, the first item is selected. and after then when user select other item, i have saved the i value so that next time when user click settings button, i can show user his/her previously selected item is selected.
I come across and solve this question today.
public class ItemChooceActivity extends Activity implements OnItemClickListener {
private int chosenOne = -1;
class Madapter extends BaseAdapter {
.....
.....
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
if (chosenOne != position) {
set the view in A style
} else {
set the view in B style
}
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
,,,,
chosenOne = position;
adapter.notifyDataSetChanged();
,,,
}
}

Remove an item from a ListView and from a file

So, i'm storing my datas in an IO-file! My datas are displayed and i want to delete an item from the listview, i maked this code, and i'm stucking!
L.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
AlertDialog alert_reset;
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Supprimer cette donnée ?")
.setCancelable(false)
.setPositiveButton("Oui",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
.............
updatelv(activity);
}
})
.setNegativeButton("Non",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
alert_reset = builder.create();
alert_reset.show();
return true;
}
Have i to use List.remove(arg2)?
And for deleting the data from a file, how can i do this ?
Thank you.
To remove an item from a ListView (which is just a display of some data) you need to remove the item from the data that backs the ListAdapter.
A common example is an Adapter that contains a list. To remove an item from the list and update the ListView you would do something like this.
myList.remove(arg2); // remove the item
myAdapter.notifyDataSetChanged(); // let the adapter know to update
IMHO the easiest way is to start by deleting the entry in the file, and then restart the "buildList" process. As the old entry is no more in the file, the new list won't show it any more.
About deleting in the file, it's more a java based question than Android, and it depends also on the store format you use (xml, json, custom ?). You should consider using a database, which is more flexible and easy to update.

Open a Custom Dialog when clicking on a listview entry

I would like to open a custom dialog when someone clicks on a listview entry. That dialog will need to know the text that was clicked on in order to display additional information on that particular entry. Can anyone point me in the right direction on how to accomplish that?
Thanks!
On the ListActivity, override the onListItemClick method. There, you will get the position of the item that was clicked. As you said you want to know the text that is on the item that was clicked, I suppose you have a simple List. In that case, I guess you have, for instance, an array with strings to populate the list.
public void onListItemClick(ListView parent, View v, int position,
long id) {
String itemText = items[position]);
}
So, in this case I'm supposing you have an array of Strings called items. The next step would be to create a Dialog, which can be done this way:
public void onListItemClick(ListView parent, View v, int position,
long id) {
String itemText = items[position]);
new AlertDialog.Builder(this)
.setTitle("Title for " + itemText)
.setMessage("Custom message for "+itemText)
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do whatever you want to do
}
}).show();
}
By the way... if you want to receive nice answers here, make sure you provide nice questions. By "nice question" I mean something with a little bit of your code, so that we can get a better idea of how to help you ;)

Categories

Resources