Confirmation before deleting from an ArrayList (Android) - java

I've set up OnContextItemSelected to show an alert when the user tries to delete an item and asks them for confirmation. The problem being that the "confirmationReceived" variable is getting set to true the first time the code is executed with nothing else happening, then when it's executed a second time the item is deleted before the user has a chance to confirm that they want it deleted.
onCreateContextMenu
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Timetable Item");
menu.add(0, Remove_Item, Menu.NONE, R.string.Remove_Item);
}
onContextItemSelected
#Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AlertDialog diaBox = AskRemoveConfirm();
diaBox.show();
switch (item.getItemId()) {
case (Remove_Item): {
if(confirmationReceived == true) {
AdapterView.AdapterContextMenuInfo menuInfo;
menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = menuInfo.position;
removeItem(index);
confirmationReceived = false;
return true;
}
}
}
return false;
}
AskRemoveConfirm()
private AlertDialog AskRemoveConfirm()
{
AlertDialog myRemovalDialogBox =new AlertDialog.Builder(this)
.setTitle("Confirmation")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
confirmationReceived = true;
dialog.dismiss();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
return myRemovalDialogBox;
}

do somthing like this
private AlertDialog AskRemoveConfirm()
{
AlertDialog myRemovalDialogBox =new AlertDialog.Builder(this)
.setTitle("Confirmation")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
confirmationReceived = true;
if(confirmationReceived == true) {
AdapterView.AdapterContextMenuInfo menuInfo;
menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int index = menuInfo.position;
removeItem(index);
confirmationReceived = false;
return true;
}
dialog.dismiss();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
return myRemovalDialogBox;
}

Related

Getting Parse Row Wrong ObjectId

I have a listview that contains 4 objects in it.When I long press one of them ,a menu open with "Delete" option that I can delete the row.
However,I am getting the wrong row objetId for some reason and I can't figure out what is it I am doing wrong.
This is what I have done:
Creating context menu:
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the list
feedListView = (ListView)v;
// Get the list item position
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
int position = info.position;
position -= feedListView.getHeaderViewsCount();
int finalPosition = position;
if (ParseUser.getCurrentUser().getUsername().equals(data.getUserName())){
Log.e("Test","Same user + ObjectId = " + ((AdapterView.AdapterContextMenuInfo) menuInfo).position);
if (v.getId()==R.id.feedListView) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
}
}else{
Log.e("Test","Not Your Post");
Toast.makeText(this, "Its not your post", Toast.LENGTH_SHORT).show();
}
}
Choosing from context menu:
if (item.getItemId() == R.id.deleteMenu){
new AlertDialog.Builder(FeedActivity.this)
.setTitle("Are you sure ?")
.setMessage("Are you sure you want to delete this post?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Feed");
objects.get(finalPosition).deleteInBackground(new DeleteCallback() {
#Override
public void done(ParseException e) {
Log.e("Done","Item Deleted Successfully !!!");
arrayList.remove(finalPosition);
adapter.notifyDataSetChanged();
}
});
}
});
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
Thanks
So I fix it by adding these 2 lines:
The first:
MyData Editdata = (MyData) adapter.getItem(position);
To
MyData Editdata = (MyData) adapter.getItem(finalPosition);
The second line I added is(I added it because my listview display the same way):
query.orderByDescending("updatedAt");

Ask dialog to delete an item from listview

I have this code that work perfect to delete an item from listview and it disappear. I want to show dialog to ask if the user want to delete an item.
public void ShowdatainlstView() {
Boodschappenlst.clear();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
Boodschappenlst);
lstviewProducten.setAdapter(arrayAdapter);
lstviewProducten.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Boodschappenlst.remove(position);
arrayAdapter.notifyDataSetChanged();
}
});
}
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("do you want to delete this?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i("Button Tapped","Yes");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i("Button Tapped","No");
}
})
.show();

Remove an item from a ListView using an alert dialog

I have this ListView containing items and I want to create an alert dialog that removes any of these items when I long click on an item. onLongClick on an item shows an AlertDialog and if I click yes, it removes the item.
Here is my code.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Are You Sure You Want to Delete This Note?!")
.setTitle("Attempt to Delete A Note")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
notesList.remove(i);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "ooooooh No!!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "Good Choice", Toast.LENGTH_SHORT).show();
}
})
.show();
return true;
}
});
I think the problem is 'i' position of alert dialog click listner and u need to user list item clicked position in order to delete item from list.
Please use below code :
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Are You Sure You Want to Delete This Note?!")
.setTitle("Attempt to Delete A Note")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
if(notesList!=null){
notesList.remove(position);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "ooooooh No!!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "Good Choice", Toast.LENGTH_SHORT).show();
}
})
.show();
return true;
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Are You Sure You Want to Delete This Note?!")
.setTitle("Attempt to Delete A Note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
dataModels.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "ooooooh No!!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "Good Choice", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
This is works for me...try this

Is Possible for on Back Pressed method with alert dialog in fragment

#Override
public void onBackPressed() {
Log.d("back button", "back button pressed");
AlertDialog.Builder ad1=new AlertDialog.Builder(getActivity());
ad1.setMessage("Are you sure you want to exit? ");
ad1.setCancelable(false);
ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(getActivity(), LoginActivity.class);
startActivity(i);
}
});
ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(getActivity(), FrndsearchFragment.class);
startActivity(i);
}
});
AlertDialog alert=ad1.create();
alert.show();
}
By using the code i getting the error in #Override and i write the super.onBackPressed i got onBackPressed in super.onBackPressed .
Yes you can do the same by overriding onKeyDown method.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Exit");
builder.setMessage("Do you want to exit the application?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
exit();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void exit() {
finish();
}

How do I reduce alert-dialogue code from main-activity in android?

I have a class where I am writing three different alert dialogue. These three alert dialogue extends the line of code of this class drastically. So for re-factoring purpose, I want to make base class for three alert dialogue and use this class in the main activity. Can anyone suggest me how to achieve this? My three alert dialogue are given below:
public boolean onJsConfirm(WebView view, String url, String message,
final android.webkit.JsResult result) {
new AlertDialog.Builder(currentActivity)
.setTitle("Confirmation")
.setMessage(message)
.setPositiveButton(android.R.string.yes,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.no,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.cancel();
}
}).setCancelable(false).create().show();
return true;
}
public boolean onJsAlert(WebView view, String url, String message,
final android.webkit.JsResult result) {
new AlertDialog.Builder(currentActivity)
.setTitle("Alert !")
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
final boolean remember = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
WebviewActivity.this);
builder.setTitle("Locations");
builder.setMessage(" Would like to use your Current Location")
.setCancelable(true)
.setPositiveButton("Allow",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
callback.invoke(origin, true, remember);
SharedPreferences pref = currentActivity
.getPreferences(currentActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref
.edit();
editor.putBoolean("isLocationAvailable",
true);
editor.commit();
webview.loadUrl(getUrl(gps.getLatitude(),
gps.getLongitude(), "true"));
}
})
.setNegativeButton("Don't Allow",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
callback.invoke(origin, false, remember);
webview.loadUrl(getUrl("", "", "false"));
}
});
AlertDialog alert = builder.create();
alert.show();
Complete solution Try this is a Generic Alert dialog with cutom tilte,message,yes,no button caption
1) Createa Interface
import android.content.DialogInterface;
public interface AlertMagnatic {
public abstract void PositiveMethod(DialogInterface dialog, int id);
public abstract void NegativeMethod(DialogInterface dialog, int id);
}
2) Generalize method for confirm dialog.
public static void getConfirmDialog(Context mContext,String title, String msg, String positiveBtnCaption, String negativeBtnCaption, boolean isCancelable, final AlertMagnatic target) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
int imageResource = android.R.drawable.ic_dialog_alert;
Drawable image = mContext.getResources().getDrawable(imageResource);
builder.setTitle(title).setMessage(msg).setIcon(image).setCancelable(false).setPositiveButton(positiveBtnCaption, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
target.PositiveMethod(dialog, id);
}
}).setNegativeButton(negativeBtnCaption, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
target.NegativeMethod(dialog, id);
}
});
AlertDialog alert = builder.create();
alert.setCancelable(isCancelable);
alert.show();
if (isCancelable) {
alert.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
target.NegativeMethod(null, 0);
}
});
}
}
3) How to use
getConfirmDialog(getString(R.string.logout), getString(R.string.logout_message), getString(R.string.yes), getString(R.string.no), false,
new AlertMagnatic() {
#Override
public void PositiveMethod(final DialogInterface dialog, final int id) {}
#Override
public void NegativeMethod(DialogInterface dialog, int id) {
}
});

Categories

Resources