How to implement an AlertDialog.Builder selected item click event? - java

I want to implement AlertDialog.Builder selected items click event. Below is what I have tried so far. I'm quite new to Android and I'm not sure how to access that event. How to implement the click event for each individual item in the list?
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class MakeCallAlertDialog {
public static AlertDialog.Builder getAlertDialog(String strArray[],
String strTitle, Activity activity) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(strTitle);
alertDialogBuilder.setItems(strArray, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int arg) {
// TODO Auto-generated method stub
}
});
return alertDialogBuilder;
}
}

Since you assigned an OnClickListener specific to that method, the int parameter is the position in the list:
Parameters
dialog The dialog that received the click.
which The button that was clicked (e.g. BUTTON1) or the position of the item clicked
This means inside your method, you should be able to do this:
public static AlertDialog.Builder getAlertDialog(final String strArray[],
String strTitle, final Activity activity) {
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(strTitle);
alertDialogBuilder.setItems(strArray,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(activity, strArray [which], Toast.LENGTH_SHORT).show();
//rest of your implementation
}
});
return alertDialogBuilder;
}

in onClick() event use switch statement to write click method for each button.
#Override
public void onClick(DialogInterface dialogInterface, int arg) {
// TODO Auto-generated method stub
switch (arg) {
case 0:
//you code for button at 0 index click
break;
case 1:
//you code for button at 1 index click
break;
default:
break;
}
}
Here, arg indicates the index of the button pressed. you can also access that button using strArray[arg]

Check my answer below if you are using single choice item selected for the strArray: Try this code
int selectedItem = 0;
// here take TempSelectOneTypeList = strArray
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
Activity_Form_Data.this);
alt_bld.setTitle("Select One");
selectedItem = 0;
for (int j = 0; j < TempSelectOneTypeList.length; j++) {
if (txt_sub_lable2
.getText()
.toString()
.equals(TempSelectOneTypeList[j].toString())) {
selectedItem = j;
}
}
Log.i(TAG, "Selected Item is " + selectedItem);
alt_bld.setSingleChoiceItems(
ArraylistSelectOneTypeList.get(selected),
selectedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
selectedItem = item;
// you can ocde here for the perticular selected item
}
});
alt_bld.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
txt_sub_lable2
.setText(""
+ TempSelectOneTypeList[selectedItem]
.toString());
}
});
alt_bld.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
Hope it will solve your problem

Related

Alert Dialog Button Pressed returning 0 values always

So, I want to detect button pressed by the user when an alert dialog pops up. This is my code.
public class AlertUtils {
private int BTN_PRESSED;
private AlertDialog.Builder builder;
public AlertUtils(Context context){
builder = new AlertDialog.Builder(context);
}
public int ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
dialogInterface.dismiss();
}
});
builder.show();
return BTN_PRESSED;
}
}
By calling ShowAlertWithTwoButtons method, returns int value detecting Positive or Negative Button pressed. My Problem is it's giving me default 0 value when I chose from an alert dialog and when I again open us alert dialog it returns the correct value.
Try in this way. Make AlertUtils class like this.
public class AlertUtils {
private AlertDialog.Builder builder;
private AlertDialogListener alertDialogListener;
// Interface to send back the response of click
interface AlertDialogListener {
void onClick(int a);
}
public AlertUtils(Context context, AlertDialogListener alertDialogListener) {
builder = new AlertDialog.Builder(context);
this.alertDialogListener = alertDialogListener;
}
public void ShowAlertWithTwoButtons(String Title, String Message, String PositiveButtonText,
String NegativeButtonText) {
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i,then pass the i in onClick or if you want 1 on
// positive button click then pass 1 here.
alertDialogListener.onClick(1);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i, then pass the i in onClick or if you want 1 on
// negative button click then pass 0 here.
alertDialogListener.onClick(0);
dialogInterface.dismiss();
}
});
builder.show();
}
}
Call the dialog in this way where you need this.
AlertUtils alertUtils = new AlertUtils(getContext(), new AlertUtils.AlertDialogListener() {
#Override
public void onClick(int a) {
if (a == 1) {
// Do your work on Positive button click
} else {
// Do your work on Negative button click
}
}
});
alertUtils.ShowAlertWithTwoButtons("Alert Dialog", "Alert Dialog Description ", "Positive", "Negative");
You'll always get BTN_PRESSED with 0 value whenever you're instantiating your AlertUtils object and the calling the ShowAlertWithTwoButtons method. But you'll get another value if you're recalling the ShowAlertWithTwoButtons again.
I think what you're currently doing is like the following:
// First, you're instantiating the object
AlertUtils alertUtils = new AlertUtils(getContext());
// then you're calling the method
int pressedButton = alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
// which will return pressedButton as 0
// then you calling the method again after clicked yes or no
int anotherPressedButton = alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
// which will not zero. But can be -1, -2, -3 like in the
// https://developer.android.com/reference/android/content/DialogInterface.html
Which is incorrect if want to get the button value directly after the click because of asynchronous nature of AlertDialog interface.
Instead, you need to add a listener (ohh no, another listener) to your AlertUtils.
UPDATE
You need to add another listener for click button, something like this:
public class AlertUtils {
public interface Listener {
void onButtonClicked(int pressedButton);
}
private Listener mListener;
private AlertDialog.Builder builder;
public AlertUtils(Context context, Listener listener){
builder = new AlertDialog.Builder(context);
mListener = listener;
}
public void ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
...
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onButtonClicked(i);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onButtonClicked(i);
dialogInterface.dismiss();
}
});
builder.show();
}
}
then you can create and call the method with:
// create the listener to listen for the clicked button.
AlertUtils.Listener listener = new AlertUtils.Listener() {
#Override
public void onButtonClicked(int pressedButton) {
// here you'll receive the button value
// do something here.
}
};
AlertUtils alertUtils = new AlertUtils(getContext(), listener);
// then you're calling the method
alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");

AlertDialog not working properly

I am creating an AlertDialog which will ask the user to whether to delete the record or not ? so for that i have declare a global flag variable (above the onCreate() method)
private int yes;
if user press Yes then value of yes will be 1 &
if press No then value of yes will be 0
The Code of my AlertDialog is below
public int dialog()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(DataListActivity.this);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure to delete ?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
yes = 1;
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
yes=0;
}
});
alertDialog.show();
return yes;
}
on the basis of this yes i want to delete the record but either i press yes or no, the value of this flag int yes remains 0, See the LOGCAT
this one for press no
12-25 00:52:22.144 2133-2133/? E/Logggggggg:: 0
this one for press Yes
12-25 00:52:33.408 2133-2133/? E/Logggggggg:: 0
now i am checking the flag yes as,
int dd = dialog();
Log.e("Logggggggg: "," "+yes);
if (dd == 1)
{
Boolean r = mydb.deleteData(selections);
}
else
{
/////// do Nothing;
}
Can anyone tell me what's going wrong here..??
You cannot capture the value of yes as the return value of your method, because it has not been set yet at the time the return statement happens. Instead, just do the database cleanup directly in the onClick listeners for the yes and no buttons, e.g.
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// delete the record here
Boolean r = mydb.deleteData(selections);
}
});
The above should be considered as pseudo-code, because I am not familiar with the details of your code base. But the basic idea to respond the user selecting yes by directly handling that action in the onClick listener.
try this
private void dialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure to delete ?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
yes = 1;
Toast.makeText(getActivity(), String.valueOf(yes), Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
yes =0;
Toast.makeText(getActivity(), String.valueOf(yes), Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
checking flag
if(yes==1){
Boolean r = mydb.deleteData(selections);
}else
{
/////// do Nothing;
}
you may just need to use onClick() signature value i.e. int which and assign it yes value like below code
public int dialog()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure to delete ?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
which = 1;
yes = which;
Toast.makeText(LoginActivity.this,"value : "+yes,Toast.LENGTH_SHORT).show();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
which = 0;
yes = which;
Toast.makeText(LoginActivity.this,"value : "+yes,Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
Toast.makeText(LoginActivity.this,"value : "+yes,Toast.LENGTH_SHORT).show();
return yes;
}

Android DialogFramgment loads item from arrayList twice but only on Samsung

I am cleaning up some code where a DialogFrament i supposed to diaplay items from an ArrayList (ref. "arr" in the code) and then the user can choose severeal items from it and then hit OK. This work fine, no problemo. But, only on Samsung Phones, the DialogFrament lists the item from the ArrayList twice. so, on all the other phone the list displays the values arr[0]->arr[n] but on Samsung(again ONLY on Samsung) the values are arr[0]->arr[n] + arr[0]->arr[n]. Since it's the same code for all android phones but the problem only occurs on Samsung Phones, im out of ideas.
A quick google search pointed me towards a difference in layout rules by Samsung depending on the resolution of their phone but it seeamed unlikely.
Have any of you heard about this before?
CODE FOR MY FRAGMENT
public ArrayList mSelectedItems;
public int type;
public boolean single = false;
int count;
boolean search;
public int single_item = -1;
public interface CategoriesDialogFragmentListener {
public void onOkay(ArrayList items, int type);
public void onCancel();
public void onSingleOkay(int item, int type);
}
CategoriesDialogFragmentListener mListener;
public void setType(int type_id) {
/*
1 = Category
2 = Genre
3 = Availability
*/
type = type_id;
}
public void setSearch(boolean isSearch) {
search = isSearch;
}
public void setList(ArrayList temp) {
mSelectedItems = temp;
}
public void isSingle(boolean is_single){
single = is_single;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (CategoriesDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
CharSequence[] arr;
String title;
switch(type){
case 1:
title = "Välj kategori";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
single = true;
break;
case 2:
title = "Välj genre";
arr = MainActivity.GENRE_STRINGS.toArray(new CharSequence[MainActivity.GENRE_STRINGS.size()]);
single = false;
break;
case 3:
title = "Välj tillgängligheter";
arr = MainActivity.AVAIL_STRINGS.toArray(new CharSequence[MainActivity.AVAIL_STRINGS.size()]);
single = false;
break;
default:
title = "ett fel uppstod";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
}
if(!single) {
if(type == 2 && search == false) {
count = 0;
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
//Kod för att starta fragment med valda entiteter
/*
if(mSelectedItems != null || !mSelectedItems.isEmpty()){
for(Object e : mSelectedItems){
}
}
*/
if (isChecked) {
if (count < 5) {
mSelectedItems.add(which);
count++;
} else {
new android.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.five)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
count--;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}else{
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}
} else {
builder.setTitle(title).setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
single_item = item;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onSingleOkay(single_item, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});;
}
return builder.create();
}
}

Referencing multiple Checkboxes in AlertDialog

Hey fellow Android Developers, Im having a issue currently with the below code. I am unable to figure out a way i can easily reference which Checkbox is clicked, Currently the code below is simply a Preference that when clicked, displays a AlertDialog with multiple Checkboxes.
The goal is do something specific when that Checkbox is checked, however i want to do something different possibly with each item.
Code
Preference checkboxalert = (Preference) findPreference("checkboxalert");
checkboxalert
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};
final ArrayList<Integer> selectedItems=new ArrayList<Integer>();
public boolean onPreferenceClick(Preference preference) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
//WHERE I WANT TO REFERENCE WHICH CHECKBOX IS CLICKED
selectedItems.add(indexSelected);
Log.i("Preference - Checkbox", "Something was clicked");
} else if (selectedItems.contains(indexSelected)) {
selectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();
return true;
}
});
What's wrong with using the index?
#Override
public void onClick(DialogInterface dialog, int indexSelected,boolean isChecked)
{
if (isChecked) {
selectedItems.add(indexSelected);
//WHERE I WANT TO REFERENCE WHICH CHECKBOX IS CLICKED
switch (indexSelected)
{
case 0:
// do something if the first box is checked
break;
case 1:
// do something if the second box is checked
break;
...
}
}
It seems like this should work unless I am missing what you want.

Return data from Dialog displayed to the user in Android

Here is the relevant code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case SORT_MENU:
showDialog(ORDER_DIALOG);
showDialog(COLUMNS_DIALOG);
String orderBy = bundle.getString("column") + bundle.getString("order");
break;
}
return false;
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
final String[] columns = { "title", "completed" };
final String[] order = { "Ascending", "Descending" };
switch (id) {
case COLUMNS_DIALOG:
AlertDialog.Builder columnBuilder = new AlertDialog.Builder(this);
columnBuilder.setTitle("Columns");
columnBuilder.setItems(columns, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
bundle.putString("column", columns[which]);
dialog.dismiss();
}
});
dialog = columnBuilder.create();
break;
case ORDER_DIALOG:
AlertDialog.Builder orderBuilder = new AlertDialog.Builder(this);
orderBuilder.setTitle("Order");
orderBuilder.setItems(order, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String orderS;
if (order[which].equalsIgnoreCase("Ascending"))
orderS = "ASC";
else
orderS = "DESC";
bundle.putString("order", orderS);
dialog.dismiss();
}
});
dialog = orderBuilder.create();
break;
default:
dialog = null;
break;
}
return dialog;
}
I know that a Dialog is asynchronous from the main UI thread. So calls like these:
showDialog(ORDER_DIALOG);
showDialog(COLUMNS_DIALOG);
String orderBy = bundle.getString("column") + bundle.getString("order");
Only result in orderBy being null. Is there any way to have orderBy wait until both dialogs are confirmed to be finished? Even if dialog.isShowing() is false, this may be because the dialog has already finished or hasnt't even started.
In that case you must override and hook the DialogInterface.OnClickListener and, from its implementation, set the value of orderBy. In fact, this is a better aproach:
case SORT_MENU:
showDialog(ORDER_DIALOG);
break;
Then, on onCreateDialog:
case ORDER_DIALOG:
AlertDialog.Builder orderBuilder = new AlertDialog.Builder(this);
orderBuilder.setTitle("Order");
orderBuilder.setItems(order, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String orderS;
if (order[which].equalsIgnoreCase("Ascending"))
orderS = "ASC";
else
orderS = "DESC";
bundle.putString("order", orderS);
dialog.dismiss();
showDialog(COLUMNS_DIALOG); // <-- NEW!!!
}
});
dialog = orderBuilder.create();
break;
Again, on onCreateDialog:
case COLUMNS_DIALOG:
AlertDialog.Builder columnBuilder = new AlertDialog.Builder(this);
columnBuilder.setTitle("Columns");
columnBuilder.setItems(columns, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
bundle.putString("column", columns[which]);
dialog.dismiss();
configureString(); // <-- NEW!
}
});
dialog = columnBuilder.create();
break;
Somewhere else:
private void configureString(){
String orderBy = bundle.getString("column") + bundle.getString("order");
}

Categories

Resources