Deleting items from a listview troubles - java

So i'm learning android development and i started my first project a few weeks ago. Since then i've hit a few roadblocks but i've gotten past them. This one is different.
I'm trying to make it so when the user touches and holds on an item in a listview a dialogue boc pops up asking if they are sure and on Yes click it will delete the item. Simple enough right?
well here's my code:
//passwordList is a Set<String> and so is passList
final Set<String> passwordList = mPrefs.getStringSet("pass", new HashSet<String>());
if (passwordList != null) {
passList = passwordList;
listFinal = passList.toArray(new String[passList.size()]);
list2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listFinal);
passwordListView.setAdapter(list2);
//onClickListener for the main list
passwordListView.setLongClickable(true);
passwordListView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View strings, final int i, long l) {
AlertDialog.Builder deleteConf = new AlertDialog.Builder(main.this);
final int positionToRemove = i;
deleteConf.setTitle("Delete Password?");
deleteConf.setMessage("Are you sure you want to delete the password '" +listFinal[i] +"'?");
deleteConf.setNegativeButton("No", null);
deleteConf.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int w) {
Log.d("dialog", "Pressed YES");
passwordList.remove(positionToRemove);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(listFinal));
//Is this right?
passList.remove(positionToRemove);
//Or this one?
list.remove(positionToRemove);
list2.notifyDataSetChanged();
list2.notifyDataSetInvalidated();
}
});
deleteConf.show();
return false;
}
});
}
I feel like i'm not removing the item from the correct array. Since the Adapter source is set to listFinal I should remove the item from there right? but it won't let me call listFinal.remove(positionToRemove);
Can anyone help me figure out what's wrong here? the dialogue box shows but when I click yes nothing happens. It knows that i pressed yes (hence the log.d pressed YES) but the item is never removed.

First thing that i noticed is you have 2 objects: list and list2 and u call
list.remove();
list2.notifyDataSetChanged();
I dont see the rest of the code but this might be the case.

listFinal should have been an ArrayList and not just an array

Related

Remove the first element of the String array in Java : Android

Let say I have this String array "{Unclaimed", "Lost/Stolen", "Damaged/Defective", "Pawned", "Not Turned Over", "Others"} and I want to remove the first one which is Unclaimed , It will remove if aat_distribution_status is being clicked is there anyway to remove it? I tried Reasons = Reasons.Skip(1).ToArray() but it doesn't work
My sample code
AutoCompleteTextView aat_reason_not_presented;
aat_reason_not_presented = findViewById(R.id.aat_reason_not_presented);
String[] Reasons = new String[]{"Unclaimed", "Lost/Stolen", "Damaged/Defective", "Pawned", "Not Turned Over", "Others"};
ArrayAdapter<String> adapterYesNo = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, Reasons);
adapterYesNo.setDropDownViewResource(simple_spinner_dropdown_item);
aat_reason_not_presented.setAdapter(adapterYesNo);
aat_distribution_status.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos, long id) {
Reasons = Reasons.Skip(1).ToArray() //Trying to remove first element of reasons but it didn't work
}
});
You can use Arrays.copyOfRange(T[], int, int) like
Reasons = Arrays.copyOfRange(Reasons, 1, Reasons.length);
Also, Java variable names start with a lowercase letter by convention. Finally, I suspect that Reasons must be effectively final to use it in the inner class like that. So I doubt that will work as is.

First list disappears in recycler view disappears

I have a RecyclerView that shows different lists depending on which option I pick in my Spinner. I can add items to a list dynamically, but when I add items to the top option on the Spinner, two items appear everytime I add, when it is only supposed to add just one and when I choose a different option in the Spinner and then back to the top option, all items that are supposed to be in it are gone. However, when I repeat the same actions in another option, one item is added at a time, and they are still there if i switch to another and back, so it is only in the first option where I experience these problems.
Here are pictures that shows what happens. First picture shows the entire Spinner, second is the top option selected with items added, third is the second Spinner option selected and fourth is back to the top option and now the items are gone.
This method is used to add a Item to one of the lists. Each option in the Spinner is used to get an element in listOfLists where each element is an ArrayList<Item>(). mItemList is the list which the RecyclerView prints out.
public void addItem(){
mItemList.add(0, new Item(idText.getText().toString(), addAmountField.getText().toString()));
listOfLists.get(dropdown.getSelectedItemPosition()).add(0, new Item(idText.getText().toString(), addAmountField.getText().toString()));
System.out.println("ListSize: " + listOfLists.get(dropdown.getSelectedItemPosition()).size());
addAmountField.setVisibility(View.GONE);
btnAdd.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
saveData2();
}
This is the code for switching the lists when I choose another option from the Spinner. What I do here is that I clear the mItemList and then I fill it with one of the ArrayList<Item> inside listOfLists.
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mItemList.clear();
for (int i = 0; i < listOfLists.get(position).size(); i++) {
mItemList.add(listOfLists.get(position).get(i));
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
How can I resolve this so that the top option of the Spinner will work just like the other options where it adds one item at a time and still has the items after I switch to another option?
I managed to solve it so for anyone who faces similar problems this was the problem:
Unlike the other lists in listOfLists where I set mItemList to the chosen list like this
mItemList.clear();
for (int i = 0; i < listOfLists.get(position).size(); i++) {
mItemList.add(listOfLists.get(position).get(i));
}
mItemList is always set to the first list when I run the app like this
mItemList = listOfLists.get(dropDown.getSelectedItemPosition());
So I just changed it so it sets mItemList the same way it is done with the other lists and now it is working.

index list view with database cardview

I know there are alot of duplicates with issues like these but pleas do read mine and help me out.
I am very new to Android development as such I coded these with my own instincts and limited guides available.
I'd like to implement an indexable (A-Z) side panel just like in contacts. All the posts available are array strings with hard-coded entries but mine aren't, I am using DB Browser for SQLite and then populate each data in a cardview.
I have referred to (https://github.com/woozzu/IndexableListView/blob/master/src/com/woozzu/android/widget/IndexableListView.java) and tried all the solutions mentioned related to this post but to no avail. I believe I simply coded it the wrong way as the entries are hard-coded but mine aren't.
I am currently following this guide, (http://androidopentutorials.com/android-listview-with-alphabetical-side-index/) and have amended some codes here and there which I thought is necessary for my situation, such as adding my database into an array. However, there are multiple errors and I don't know what to do.
As such, I have no idea how to solve these errors proceed on. Please do help me out and provide me with, perhaps a step-by-step tutorial or even better video guides so that I could follow through.
Below are what I have tried:
Declaration
//indexable list view
Map<String, Integer> mapIndex;
List<String> dbList = new ArrayList<>();
OnCreate
//indexable list view
String[] dbList= database.getKeyword();
Arrays.asList(dbList);
dbList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, dbList));
etIndexList(dbList);
displayIndex();
//indexable list view
private void getIndexList(String[] dbList){
mapIndex = new LinkedHashMap<String, Integer>();
for(int i = 0; i < dbList.length; i++){
String db = dbList[i];
String index = db.substring(0,1);
if(mapIndex.get(index) == null)
mapIndex.put(index, i);
}
}
private void displayIndex(){
LinearLayout indexLayout = (LinearLayout) findViewById(R.id.side_index);
TextView textView;
List<String> dbList = new ArrayList<String>(mapIndex.keySet());
for (String index : dbList){
textView = (TextView) getLayoutInflater().inflate(R.layout.side_index_item, null);
textView.setText(index);
textView.setOnClickListener(this);
indexLayout.addView(textView);
}
}
public void onClick(View view){
TextView selectedIndex = (TextView) view;
dbList.setSelection(mapIndex.get(selectedIndex.getText()));
}
The errors are:
If you require any more codes do let me know and I will update this post. Thank you in advance.
follow this lib for indexing list no need to write extra function this lib manage all the case
Answer to the errors that you are getting:
You are calling dbList.setAdapter(): dbList is not a ListView or RecyclerView
Call setAdapter() method on appropriate ListView or RecyclerView variable.
You are passing this to setOnClickListener() method: this is pointing to your KnowledgeActivity and not a View.OnClickListener.
Solution: Either implement View.OnClickListener in your activity or call new OnClickListener like this,
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}});
database.keyword() returns List and you are trying to cast it to String[]

Android: Add listvew items to an array list or any work around to achieve the below?

In the below code, where the item’s position and title is getting saved in list_items works fine if list_items and items are ArrayList. For ex;
ArrayList.add(ArrayList.get(position));
But I am trying to use listview:
ArrayList.add(Listview.get(position));
Below is my code
final Listadapter Adapter =new Listadapter(this,packageList1,packageManager);
items.setAdapter(Adapter);
items.setChoiceMode(apps.CHOICE_MODE_MULTIPLE_MODAL);
items.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener()
{
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked)
{
count = count +1;
mode.setTitle(count + "items selected"); //problem resides in the below line
list_items.add(items.get(position));
}
In the above code, on selecting an item from listview I am trying to save it in an Arraylist i.e list_items which could be used in onActionItemClicked method for further action on that respective item.
Any ideas on how to solve or find a workaround to use a listview in the above situation?

ArrayAdapter : Remove by Index

I have a ListView that is populated by a news server rundown (just a list of story slugs) and an arrayAdapter to modify that ListView.
I can remove items by the 'remove(Object)' function but what if there are multiple instances of 'Object'? remove() only removed the first instance of 'Object'. I cannot remove, for example, the second 'Object' in my array adapter without removing the first one. So my question is how can i work around this?
ex : Rundown A
story 1
story 2
Break
story 3
story 4
Break
story 5
etc...
so in this example i cannot delete the Second 'Break' because remove('Break') will remove the first one. if i could removeByIndex(5), that would be perfect but....
Ive tried writing my own remove function that creates a whole new adapter with all members but the specified index. here is what i was messing around with.
public ArrayAdapter<String> removeIndex(ArrayAdapter<String> arr, int index) {
ArrayAdapter<String> temp = new ArrayAdapter<String>(arr.getContext(),R.layout.list_item);
for(int i =0 ; i<arr.getCount();i++){
if(i != index) temp.add(arr.getItem(i));
}
return temp;
}
Help or suggestions are appriciated.
Handle the collection of strings yourself with a List and pass the object into the constructor of the ArrayAdapter. This leaves you with a reference to the List so you can alter the data while allowing the adapter to manage and display as needed.
Note: When modifying the data object you must call
myAdapter.notifyDataSetChanged()
afterwards - which must also be on the UI thread. Obviously the changes to the list don't have to take place on the UI thread and should most likely not happen on the UI thread.
private ArrayList<String> mData = new ArrayList<String>();
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Code that adds the strings
// Create the list adapter
mAdapter = new ArrayAdapter<String>(myActivity.this, android.R.layout.simple_list_item_1, mData);
}
private void removeItem(int index) {
mData.removeAt(index);
myActivity.this.runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
}
}
}

Categories

Resources