Listview Error on longpress of item for deletion - java

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 .

Related

Cannot Sucessfully Delete Item From ListView In Set Counterpart

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))

Data Won't Save To Shared Preferences

Layout
Hi! So I've been trying to make a basic note app and I've run into a wall. I've spent hours trying to get my data to save to my sharedPreferences, but no matter what I try it doesn't seem to work. I've added logs to the app so we can examine what is happening.
LOGS:
02-22 18:27:56.767 4929-4929/com.example.jackson.collegeplanner I/TEST: notesSet didn't return null!
(When I click the addnote button)
02-22 18:29:54.500 4929-4929/com.example.jackson.collegeplanner I/TEST: newNote added to notesSet
Code:
public class Schedule extends AppCompatActivity {
ArrayList<String> notes = new ArrayList<>();
// SharedPreferences sharedPreferences = this .getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences myPref = this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = myPref.getStringSet("NN", null);
if(notesSet != null){
notes.addAll(notesSet);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "notesSet didn't return null!");
}
else{
notesSet = new HashSet<String>();
notesSet.add("Ya note's set is empty");
notes.addAll(notesSet);
listView.setAdapter(arrayAdapter);
Log.i("TEST", "noteSet returned null");
}
myPref.edit().putStringSet("NN", notesSet).apply();
}
public void AddNote(View view){
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
ListView listView = (ListView) findViewById(R.id.listView);
EditText editText = (EditText) findViewById(R.id.editText);
String newNote = editText.getText().toString();
SharedPreferences myPref = this.getSharedPreferences("com.example.jackson.collegeplanner", Context.MODE_PRIVATE);
Set<String> notesSet = myPref.getStringSet("NN", null);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
notesSet.add(newNote);
Log.i("TEST", "newNote added to notesSet");
notes.clear();
notes.addAll(notesSet);
editText.setText("");
myPref.edit().putStringSet("NN", notesSet).apply();
listView.setAdapter(arrayAdapter);
}
}
You can use
if(myPref.edit().putStringSet("notes", set).commit())
Log.d(TAG , "SAVED");
else
Log.d(TAG , "Not Saved");
To check if shared preferences were actually saved.
in your code change
`
if(set == null){
set = new HashSet<String>();
notes.add("Initial Notes");
set.addAll(notes);
}
`
to
`
if(set == null){
set = new HashSet<String>();
notes.add("Initial Notes");
set.addAll(notes);
myPref.edit().putStringSet(set).apply();
}
`
the answer is from a duplicate post I made and it was answered there.
Oh, I just remembered a catch with String Sets in SharedPreferences that you're probably coming up against. (I admit I didn't really test your code very thoroughly when I did it.) You cannot try to modify the Set you get from getStringSet() and then save it back. You need to instantiate a new one, and pass that to putStringSet(). In your code, a simple fix would be: Set<String> notesSet = new HashSet<String>(myPref.getStringSet("NN", null));. – Mike M.

Android - listView Problems -

I created an app that it should work as a telephone directory. Firstly I enter the data, then save, and finally I should see a list (listView) with my saved data.
But I don't see no list, although the data are present in the database. I inserted an "else" statement for to control if the db is full.
MainActivity.java
if(gridList.size()!=0){
Log.i("PROVA", "size: " + gridList.size());
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
id_grid = (TextView) view.findViewById(R.id.id_grid);
String id_gridValue = id_grid.getText().toString();
Intent theIntent = new Intent(getApplication(),EditSheet.class);
theIntent.putExtra("id_grid", id_gridValue);
startActivity(theIntent);
ListAdapter adapter = new SimpleAdapter(MainActivity.this,gridList, R.layout.grid_entry, new String[]{
"id_grid", "site"}, new int[] {R.id.id_grid, R.id.edit_site});
/*String[] values = new String[]{"id_grid", "edit_site", "edit_tab"};
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
values);*/
setListAdapter(adapter);
}
});
} else {
Log.i("PROVA", "size = 0");
}
and the result is this:
[
I/PROVA: size: 1
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7fa218cf5a00, error=EGL_SUCCESS
D/OpenGLRenderer: endAllStagingAnimators on 0x7fa218e4dc00 (RippleDrawable) with handle 0x7fa21bc653a0
Application terminated.
This is the layout of the activity_main:
I believe it's a list display issue.
try to use
listView.notifyDataSetChanged();

Saved SharedPreferences changes lost when app is cleared from memory

I am updating and saving an array of values in SharedPreferences from within a Settings activity. Specifically, from an AlertDialog in an onCLickListener for a ListView. The changes seem to be saved fine - i.e. they are still intact after I close and re-open the MainActivity, but as soon as my app is released from memory and restarted the SharedPreferences revert to their previous state.
I read somewhere that calling editor.clear() before editor.commit() can prevent this happening, but this also has the effect of deleting all of the other values in my SharedPreferences (i.e. the ones that I am not editing in this code).
Can anyone explain why I am losing my SharedPreference updates, and how I can fix this?
The code is below:
final ListView lv = (ListView) findViewById(R.id.list_folders);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
final String itemValue = (String) lv.getItemAtPosition(position);
// Ask the user to confirm deletion of the item using an AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(SourceFolders.this);
builder.setTitle("Confirm");
builder.setMessage("Remove " + itemValue + "?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Yes - remove the current item from SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SourceFolders.this);
Set<String> set = prefs.getStringSet("source_folders", null);
if (set == null) {
dialog.dismiss(); // List of folders in Preferences is empty - shouldn't happen
}
// Remove the selected item from the list
set.remove(itemValue);
// Update Shared Preferences
SharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("source_folders", set);
edit.commit();
folderlist = new ArrayList<String>(set);
refreshListViewFromPrefs();
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});

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