Change values of predefined Items in Multichoice AlertDialog - java

I have been trying to implement a multichoice alertdialog and for the most part everything is clear and understandable but the alertdialog gets the state of the items from a boolean array and all the items are set as true. I can't quite work out how I could change the state of an item in the array if it is checked in the alertdialog.
private void showCategorySelectionDialog() {
// Prepare the dialog by setting up a Builder.
final String selectionTitle = "Show on map: ";
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(selectionTitle);
final String[] categories = new String[]{"Camping grounds","Abandoned places","Nature areas","Lookout Points"};
// Find the current map type to pre-check the item representing the current state.
boolean[] checkedItems = new boolean[]{
true,
true,
true,
true
};
// Add an OnClickListener to the dialog, so that the selection will be handled.
builder.setMultiChoiceItems(
categories,
checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
//check which item is clicked and if it was true then set it as false.
if (isChecked && checkedItems[which] == true){
checkedItems[which]= false;
}else{
//If item was clicked and the value was false then set it as true.
checkedItems[which] = true;
}
}
}
);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
// Build the dialog and show it.
AlertDialog categoryDialog = builder.create();
categoryDialog.setCanceledOnTouchOutside(true);
categoryDialog.show();
}
This current solution does not change values and my assumptions are that I am handling the Array in an incorrect way but I am not sure how the right way would be.

Since you want to change the value for an element in the array when it was checked then you can try to set the value to be equal with the isChecked variable that is passed through onClick() method.
Check the code below:
// Add an OnClickListener to the dialog, so that the selection will be handled.
builder.setMultiChoiceItems(
categories,
checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked;
}
}
);

Related

How to disable positive button in onClick Function

I wanna disable positive button when one of input fields is empty.
I tried to use ((AlertDialog)dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
But it does not work.
new AlertDialog.Builder(MainActivity.this)
.setView(viewInput)
.setTitle("Add task")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String title = edtTitle.getText().toString();
String des = edtDes.getText().toString();
String date = edtDate.getText().toString();
String time = edtTime.getText().toString();
if(isEmpty(title) || isEmpty(des) || isEmpty(date) || isEmpty(time)){
((AlertDialog)dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
Toast.makeText(MainActivity.this,"Please, enter all fields.",Toast.LENGTH_SHORT).show();
}else{
Task task = new Task(title, des, date, time);
boolean isInserted = new TaskHandler(MainActivity.this).create(task);
if(isInserted){
Toast.makeText(MainActivity.this,"Task Saved",Toast.LENGTH_SHORT).show();
loadTasks();
}else{
Toast.makeText(MainActivity.this,"Unable to save",Toast.LENGTH_SHORT).show();
}
dialogInterface.cancel();
}
}
}).show();
You disable positive button after DialogInterface.OnClickListener. it means your positive button already set on your AlertDialog...
according to your need you have to disable positive button before you show dialog...
check this link...
Reference

how can i display a list of selected checkboxes in an alert dialog?

am trying to properly display a list of selected checkboxes stored in an array and display them as a list in an alert dialog.
if(registeredCourseList.getcoursessize() <= 5){
System.out.println(registeredCourseList.getCoursesArray());
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure you want to register the following courses? ");
// add a checkbox list
String[] courses ={String.valueOf(registeredCourseList.getCourses().toString())};
boolean[] checkedItems = {true, true, true, true, true};
builder.setMultiChoiceItems(courses, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// user checked or unchecked a box
}
});
// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// user clicked OK
// send the map or array to the server
try {
processRegistration(mView,registeredCourseList.getCoursesArray());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Context context = getApplicationContext();
CharSequence text = "Registered Courses Successfully";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
onBackPressed();
}
});
builder.setNegativeButton("Cancel", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
} else {
Context context = getApplicationContext();
CharSequence text = "Choose at least 5 courses";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//back to the reg activity
// onBackPressed();
}
i can get the courses but they display and an array object. i want to display the courses as a list of checkeboxes in the alert dialog.
I have checked your code like this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Are you sure you want to register the following courses? ");
// add a checkbox list
String[] courses ={"acx","sadsa","ksk","ksj","ywtgd"};
boolean[] checkedItems = {true, true, true, true, true};
builder.setMultiChoiceItems(courses, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// user checked or unchecked a box
}
});
builder.show();
and it is showing five different checkboxes. Check your String[] courses ={String.valueOf(registeredCourseList.getCourses().toString())};
I guess output of this line is all String Data at 0 index instead of showing on different indexes.
So instead of using above line Use for loop to insert values inside array
Edited for FOR Loop
Just an Example
ArrayList courses=new ArrayList();
for(int i=0;i<registeredCourseList.size;i++){
courses.add(registeredCourseList.get(i).getCourses());
}
Try something like this

Custom AlertDialog disappears on back button press

Hi guys I have a custom alert dialog I created. In the builder I set cancelable to false yet it still disappears when I press the back button, any ideas?
This is the code for the dialog:
public final class HemisphereDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View customTitle = inflater.inflate(R.layout.hemisphere_dialog_custom_title, null);
builder.setCustomTitle(customTitle);
String[] entries = new String[2];
entries[0] = getResources().getString(R.string.northern_hemisphere);
entries[1] = getResources().getString(R.string.southern_hemisphere);
builder.setItems(entries, new DialogInterface.OnClickListener() {
//The 'which' argument contains the index position of the selected item
public void onClick(DialogInterface dialog, int which) {
if( which == 0 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(true);
} else if( which == 1 ) {
GlobalVariables.getShared().setIsInNorthernHemisphere(false);
}
ToolbarActivity.outfitsFragment.hemisphereSelected();
GlobalVariables.getShared().setHasAskedForHemisphere(true);
}
});
builder.setCancelable(false);
//Create the AlertDialog object and return it
return builder.create();
}
And this is how it's displayed:
new HemisphereDialogFragment().show(getSupportFragmentManager(), "hemisphereDialog");
Another small side question, is there a way to change the text size for the items in the dialog?
You set your alert dialog cancelable to false, but your fragment is still set to cancelable, you need to add setCancelable(false) to your fragment as well.
You should call setCancellable(false) in the Dialog fragment itself not the AlertDialog.Builder.

How to set checkbox checked and disabled

I have this code for showing list of languages for download:
public void onCreateDialog(ArrayList<String>fullLangArray, final ArrayList<String>codeLangArray) {
final String[] items = fullLangArray.toArray(new String[fullLangArray.size()]);
final ArrayList mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle("Updates...")
.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(Utils.SERVER_ADDRESS + "/" + codeLangArray.get(indexSelected) + ".zip");
} else if (mSelectedItems.contains(indexSelected)) {
mSelectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("Download", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DownloadTask downloadTask = new DownloadTask(MainActivity.this);
downloadTask.execute(mSelectedItems.toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
I want to make a one item of a checkbox is checked and "disabled" like in a photo (Option 3) when AlertDialog is loaded.
Can you help me how to do it?
You can check the checkbox by using the setChecked() method which boolean value as parameter.
Example:
option1.setChecked(true);
and also uncheck it using
option2.setChecked(false);
If you want to set it to checked and disabled you have use setEnabled() which takes boolean as it's parameters.
Example.
option3.setChecked(true);
option3.setEnabled(false);
This will disable your checkbox and even check it. I hope this was helpful. ThankYou.
For setting Opacity
mSelectedItems.getBackground().setAlpha(128);
Where the INT ranges from 0 (fully transparent) to 255 (fully opaque).
For setChecked item
mSelectedItems.setChecked(true);
Disable checking
mSelectedItems.setEnabled(false)

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

Categories

Resources