Referencing multiple Checkboxes in AlertDialog - java

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.

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;
}

How to search inside a table with textWatcher or different

So I have a table of data I download into the app from a online server, I have a search button that at click brings up a AlertDialog where I want the user to enter the searching text and it looks like this:
public void buscar() {
final EditText myView = new EditText(getApplicationContext());
myView.setHint("Introduce texto aqui");
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setView(myView);
alt_bld.setMessage("Introduce el texto o nombre del medio que deseas buscar:")
.setCancelable(false)
.setPositiveButton("Listo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
TextWatcher filterTextWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
public void onTextChanged(CharSequence s,int start, int before,int count)
{
}
#Override
public void afterTextChanged(Editable arg0)
{
}
};
buscartext = myView.getText();
myView.addTextChangedListener(filterTextWatcher);
AlertDialog alert = alt_bld.create();
alert.setTitle("Buscar");
alert.setIcon(R.drawable.searcha);
alert.show();
}
It works by the means of showing the alert dialog and asking for the search text, but obviously I don't now exactly how it works, I have try this inside the onTextChanged and the afterTextChanged:
for(webResult currentItem: arrayOfWebData)
{
//Check if the Medio property of the current item matches the search
if(currentItem.Medio.equals(s))
{
FilteredArrayOfWebItems.add(currentItem);
}
}
// here call my list adapter to display items
webResult is the table from the internet and aFilteredArrayOfWebItems is meant to be list resulting from the search, but it doesn't work. I know currentItem.Medio.equals(s) is checking only one column of my table and I need to search in more than one plus that line is not good for searching because of the .equal How can I make a in-discriminated (%searchtext%) search? and use this textWatcher or should I use another way for searching in my table?

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

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

How to get the checked items from a multi choice item in a Alert.Builder?

Is there a way to get some infomation about the checked items in the next Alert.Builder? I need to save some booleans in SharedPreferences when somebody clicked the positive button. Those booleans are from the choices the user made in the alert. How can I get them?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final SharedPreferences preferences = getSharedPreferences("type_settings", MODE_PRIVATE);
boolean[] selectedTypes = getSelectedTypes(preferences);
builder.setIcon(R.drawable.menu_type)
.setTitle(R.string.list_dialog_title)
.setMultiChoiceItems(R.array.select_type_items, selectedTypes,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
}
})
.setPositiveButton(R.string.types_save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences.Editor prefEditor = preferences.edit();
}
})
.setNegativeButton(R.string.types_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
})
.create();
builder.show();
You could use getCheckedItemIds() or getCheckedItemPositions () to get a list of checked items from the listview. You should use AlertDialog.getListView() to get the dialog's listview first.
mAlert.getListView().getCheckedItemPositions ();
I managed to resolve the problem in some way, but i don't know if it's a good practice. Here is the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final SharedPreferences preferences = getSharedPreferences("type_settings", MODE_PRIVATE);
final String[] availableTypes = getResources().getStringArray(R.array.select_type_items);
final boolean[] selectedTypes = getSelectedTypes(preferences, availableTypes);
builder.setIcon(R.drawable.menu_type)
.setTitle(R.string.list_dialog_title)
.setMultiChoiceItems(R.array.select_type_items, selectedTypes,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
selectedTypes[whichButton] = isChecked;
}
})
.setPositiveButton(R.string.types_save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences.Editor prefEditor = preferences.edit();
saveSelectedTypes(prefEditor, availableTypes, selectedTypes);
}
})
.setNegativeButton(R.string.types_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
})
.create();
builder.show();
For storage efficiency, you could convert the boolean array to an integer before storing it as a preference. But beware, the boolean array that initializes the AlertDialog list has the reverse order of the boolean array results from the AlertDialog. (Seems to be a consistent reversal: happens on OS 2.3.6 and 4.2.2 ... I haven't checked any other versions.)

Categories

Resources