Cannot Sucessfully Delete Item From ListView In Set Counterpart - java

I feel like this shouldn't be a complicated problem, but I've tried reworking it and cannot think of a solution as to why it isn't working.
I have a listView that adds a ArrayList notes to it. For this listView, when you longpress on an item, it creates a pop up that deletes the item clicked. my set notesSet takes data from sharedPreferences and adds it to notes and gets updated when notes changes. This deletion is controlled by a Yes/No box. For some reason, I cannot remove the item from notes and have the listView show the updated form.
Here is the code for the long click:
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
new AlertDialog.Builder(Schedule.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Pop Up!")
.setMessage("Ready to delete this task?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences myPref = Schedule.this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));
ArrayAdapter arrayAdapter = new ArrayAdapter(Schedule.this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
notesSet.remove(i);
notes.clear();
notes.addAll(notesSet);
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setAdapter(arrayAdapter);
/*
notes.remove(i);
notesSet.addAll(notes);
notes.clear();
*/
}
})
.setNegativeButton("No", null).show();
return false;
}
});
I've actually pinpointed the problem, I think, to these three lines of code. Problem is, I can't figure out what it is I'm doing
notesSet.remove(i);
notes.clear();
notes.addAll(notesSet);

Actually it is a simple mistake, instead of passing String value to notesSet.remov(), you are passing integer value to it.
So make change like this
notesSet.remove(i)
to
notesSet.remove(notes(i))

Related

how to get the items changed in spinner android studio

I want to change the value of the second spinner when the value of the first spinner is changed I tried the solutions but did not get an exact solution so anyone have a solution for that so please suggest or any question then please ask
ArrayAdapter<String> deptArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.Province));
deptArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProvinceEyeTest.setAdapter(deptArrayAdapter);
deptArrayAdapter.notifyDataSetChanged();
Set a OnItemSelectedListener() first.
spinnerProvinceEyeTest.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString(); //this is your selected item
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
In onItemSelected() of above Listener, place your condition and set resource for second Spinner as:
If(selectedItem == "YourText"){
//Here, you're initalizing the second `Spinner`
ArrayAdapter<String> secondArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.YourList));
secondArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
secondSpinner.setAdapter(secondArrayAdapter);
}
else{
//Use any other list with arrayAdapter in case of other item selected.
//Use can use If-else-if or Switch to select different resource for different item of first spinner
}
Reference - Official Documentations.

Listview Error on longpress of item for deletion

Visual Reference
EDITED WITH COMMENT FIX
My listView is supposed to, on long tap, delete whatever you tap on. There is data in sharePreferences, so that shouldn't be the problem. So, what I am doing is I am taking data from noteSet, which gets it from myPref. Then, where the listView gets clicked, the notesSet deletes that note. Then, it reuploads the modified notesSet to sharedPreferences and then notesSet is added to notes, which is used by the listview.
I think this is the error code I am getting:
02-23 12:20:12.384 5211-5229/com.example.jackson.collegeplanner E/OpenGLRenderer: GL error: GL_INVALID_OPERATION
02-23 12:20:28.461 550-710/system_process W/InputDispatcher: channel '17b2c24b com.example.jackson.collegeplanner/com.example.jackson.collegeplanner.Schedule (server)' ~ Consumer closed input channel or an error occurred. events=0x9
02-23 12:22:12.723 54-54/? E/EGL_emulation: tid 54: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
new AlertDialog.Builder(getApplicationContext()).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Pop Up!")
.setMessage("Ready to delete this task?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences myPref = getApplicationContext().getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));
ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
notesSet.remove(i);
notes.clear();
notes.addAll(notesSet);
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
})
.setNegativeButton("No", null).show();
return false;
}
});
This is a snippet of code from my program for convienence. The rest of the program works, and app crashes only occur when I introduced this new code. Thanks for your time.
Use Acivity's context instead of getApplicationContext() . Do not use getApplicationContext() anywhere unless it meant to be use . Do it as below .
new AlertDialog.Builder(YourActtivity.this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Pop Up!")
.setMessage("Ready to delete this task?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
SharedPreferences myPref = getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));
ListView listView = (ListView) findViewById(R.id.listView);
notesSet.remove(i);
notes.clear();
notes.addAll(notesSet);
myPref.edit().putStringSet("NN", notesSet).apply();
ArrayAdapter arrayAdapter = new ArrayAdapter(YourActtivity.this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
})
.show();
Also Debug your code check and for returned values .

Android Spinner Doesn't Return Id Properly

I'm having a difficulty in spinner android, more specifically in the data saving part.
First, I'm going to tell you what is the purpose behind the code below.
I want to create a spinner that user can choose which planet to buy, then when he/she hits the submit button, a toast will appear saying "You wanted to buy: ...." then followed by a purchase summary like username & price.
However, in the middle of the process I'm having a hard time to save the id of each spinner's element.
Every time I chose "Earth" (id= 1) & hit submit, the toast will always refer back to "Mars" which has id = 0. So it seems that the problem is my submit button will always reset the chosen id.
I intentionally set planetSpinner() method to return int, thus I could always track down the "id" being returned. But again, the submit button would always make it shows to id = 0.
Can anyone help me? I would really appreciate that. Thank you.
Spinner Code (MainActivity.java)
public int planetSpinner(){
context = this;
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
cSpinner = (Spinner) findViewById(R.id.coffee_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cSpinner.setAdapter(dataAdapter);
cSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You selected: " + cSpinner.getItemAtPosition(position), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_LONG).show();
}
});
return cSpinner.getSelectedItemPosition();
}
Submit Purchase Code (MainActivity.java)
public void submitOrder(View view){
Toast.makeText(MainActivity.this, "You wanted to buy: " + planetSpinner(), Toast.LENGTH_LONG).show();
displayMessage(confirmationOrder(userName, price));
}
public class MySpinner extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.coffee_spinner);
spinner.setOnItemSelectedListener(this);
List<String> categories = new ArrayList<String>();
categories.add("Mars($12 billions)"); //0
categories.add("Earth ($99 billions)"); //1
categories.add("Jupiter ($13 billions)"); //2
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Have you try this:
Toast.makeText(MainActivity.this, "You selected: " + categories.get(position), Toast.LENGTH_LONG).show();
It is because the spinner was reinitialized everytime you call the function. Thus, the selected value was the first item, that is why your function always returns 0. Hope that helps.

Array position using onItemClickListener

I'm trying to get the position of an array using the onItemClickListner.
With the following code, I am able to pass the text of the item clicked but not the position of the array eg 0, 1, 2 etc.
String[] menuItems = new String[]{"Hello", "Is it me", "Youre", "Looking for"};
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.menulists, R.id.menulistsTextView1, menuItems);
ListView listView = (ListView) findViewById(R.id.mainListView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
String selected = (String) l.getItemAtPosition(position);
}
Any tips on whether it is possible to do that, I tried changing String to int and also to use the getItemIDAtPosition function but would not work, would just close the application.
Cheers
EDIT
I have just taken a different approach to achieving what I want to do using if statements for the string of the item clicked. Thanks for the input
You can get the position from method signature :
public void onItemClick(AdapterView<?> l, View v, int position, long id)
position give you index of selected item.
you may try this :
String itemClicked = menuItems[position];
As I understand Your problem - You want to get item on clicked position. Do do so use getItem(position) method of adapter. Code:
String[] menuItems = new String[]{"Hello", "Is it me", "Youre", "Looking for"};
//VERY IMPORTANT
//adapter must be declared final to use it in onItemClick
//or adapter should be object parameter
final ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.menulists, R.id.menulistsTextView1, menuItems);
ListView listView = (ListView) findViewById(R.id.mainListView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
String selected = <String>adapter.getItem(position);
}
});

how can i change visibility of menuitem from another activity?

can anybody tell me how to change the visibility of a menuitem from another activity?
I have two activities "activity A and B". in one activity A when I press a menu item it saves some strings to the list of activity B and In activity A menuitem visibility set to false. now I want that when I delete that item from activity B which I saved from activity A, with this delete the menuitem visibility in activity A changes to true and it become visible again? so how can I do this. I using database to populate listview.
Activity A
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.atherosclerosis, menu);
return true;
}
// for starting activity from the option or menu//
#Override
public boolean onOptionsItemSelected(MenuItem item) {
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = myPrefs.edit();
favClicked = myPrefs.getBoolean("menu_item", false);
switch (item.getItemId()) {
case R.id.id_favorit:
// Add it to the DB and re-draw the ListView
myDb.insertRow("Atherosclerosis", 0, "");
Toast.makeText(getApplicationContext(), "Item Added to favorite list!", Toast.LENGTH_SHORT).show();
favClicked=true;
editor.putBoolean("menu_item", favClicked);
editor.commit();
invalidateOptionsMenu();
return true;
case R.id.id_favorit2:
myDb.deleteRow("Atherosclerosis");
Toast.makeText(getApplicationContext(), "Item deleted from favorite list!", Toast.LENGTH_SHORT).show();
favClicked=false;
editor.putBoolean("menu_item", favClicked);
editor.commit();
invalidateOptionsMenu();
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(favClicked==true){
menu.findItem(R.id.id_favorit).setVisible(false);
menu.findItem(R.id.id_favorit2).setVisible(true);
}else{
menu.findItem(R.id.id_favorit).setVisible(true);
menu.findItem(R.id.id_favorit2).setVisible(false);
}
Activity B
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.item_name};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.favlistView1);
myList.setAdapter(myCursorAdapter);
}
private void registerListClickCallback() {
ListView myList = (ListView) findViewById(R.id.favlistView1);
//This code is for to delete the single item from the listview of favorite list
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, final long arg3) {
Cursor cursor = myDb.getRow(arg3);
if (cursor.moveToFirst()) {
new AlertDialog.Builder(FavoriteDiseases.this)
.setTitle("Delete Item")
.setMessage("Do you want to delete this disease?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
myDb.deleteItem(arg3);
populateListViewFromDB();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
return true;
}
});
Need a little more context for a good answer how are the activities related is one calling the other?
But in general if activity a is calling activity b. Then you could just call startActivityForResult when starting activity b. When b is finished return a status that informs activity a that the item has been deleted.
To update the menu assuming you are creating your menu by overriding onCreateOptionsMenu, then just have that method check a flag to set a state of the menu item. Then in your onActivityResult method set the flag based on the result of activity b and call invalidateOptionsMenu() which will redraw your options menu.

Categories

Resources