I want to populate a CharSequence with one of two array constants, depending on a condition. I then want to pass it as an argument to an AlertDialog. The code below is what I'm trying to achieve, but line 7 gives a compile-time error "items cannot be resolved to a variable".
if (presetItemId == 0) {
final CharSequence[] items = { "Delete", "Edit" };
} else{
final CharSequence[] items = { "Delete"};
}
new AlertDialog.Builder(context).setTitle("Meal Item")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 1) {
Coding it a different way (as below) gives "Array constants can only be used in initializers" for lines 3 and 5:
final CharSequence[] items;
if (presetItemId == 0) {
items = { "Delete", "Edit" };
} else{
items = { "Delete"};
}
new AlertDialog.Builder(context).setTitle("Meal Item")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 1) {
editRecord(Integer.parseInt(id));
}
else if (item == 0) {
Any ideas for how I can achieve what I want to do here?
Java allows you to declare a final variable, and assign it later, as long as it's not used before then. Try including your array initializer ({ "Delete", "Edit" }) in an array creation expression (new CharSequence[] { "Delete", "Edit" }):
final CharSequence[] items;
if (presetItemId == 0) {
items = new CharSequence[] { "Delete", "Edit" };
} else{
items = new CharSequence[] { "Delete"};
}
new AlertDialog.Builder(context).setTitle("Meal Item")
.setItems(items, new DialogInterface.OnClickListener() { //...
Related
I am implementing a simple dialog with a checked listview in it. This is what I've done so far:
CharSequence[] items = {"Brand A", "Brand B", "Brand C"};
AlertDialog.Builder builder = new AlertDialog.Builder(StrengthOfDemandsView.this);
builder.setTitle("Select Brands");
final ArrayList seletedItems=new ArrayList();
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which checkbox checked)
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
} else{
seletedItems.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();
PROBLEM:
Initially, I'm passing an Array to setMultiChoiceItems method and it works fine but how to pass an ArrayList instead of an array? Like this:
ArrayList<Products> brandList = new ArrayList<>();
Whenever I'm trying to pass an ArrayList to setMultiChoiceItems method it gives me this error:
Cannot resolve method 'setMultiChoiceItems(java.util.ArrayList<com.application.marketvisit.dataItem.Products>, null, anonymous android.content.DialogInterface.OnMultiChoiceClickListener)'
You need to pass a String array to AlertDialog.Builder#setMultiChoiceItemsso collect it as a String array
String arr = new String[brandList.size()];
for(int i=0 ; i< brandList.size();i++){
arr[i] = brandList.get(i).getProductName();
//getProductName or any suitable method
}
Try this...and let me know if it works..
ArrayList<String> strBrandList = new ArrayList<String>();
for (int i = 0; i < brandList.size(); i++) {
strBrandList.add(brandList.get(i).getProductName())
}
I'm displaying checkboxes in alertdialog. When user clicks OK, toast should come up like You've selected PHP, Java, JSON. Right now, its displaying IDs. How can I get values?
Dialog dialog;
final String[] items = {" Objective C", " JAVA", " JSON", " C#", "PHP"};
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Languages you know : ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
Toast.makeText(MainActivity.this,"You've selected "+itemsSelected,Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();
[UPDATE] I found solution but it doesn't seem ideal. For now its working by adding following code.
String one="";
String two="";
String three="";
String four="";
String zero="";
if (s.contains("0" ))
{
zero="Obj C ";
}
if (s.contains("1"))
{
one="JAVA ";
} if (s.contains("2"))
{
two="JSON ";
} if (s.contains("3"))
{
three="C# ";
} if (s.contains("4"))
{
four="PHP ";
}
This part of your code
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
**itemsSelected.add(selectedItemId);**
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.add(selectedItemId) simply adds the id to your arraylist. You do not want the id added. Since you want the exact values added, You can simply use something like itemsSelected.add(items[selectedItemId]) since the items array contains what values you need to display. When you have put your correct values in your arraylist, then you display your toast maybe using itemsSelected.toString() or something. You also need to handle all the other checks.
In my code I can choose checkbox items and set their in my array:
protected ArrayList<Integer> selectedStatusId = new ArrayList<>();
But when I choose same checkbox item, need delet it from my array and... I cna't do it, becouse id in my array differs of my mStatuses.
How can I delete my desired item?
Maybe can I get all selected items after click positive button?
final ArrayList<String> statusesTitles = new ArrayList<>();
for (int i = 0; i < mStatuses.size(); i++) {
statusesTitles.add(mStatuses.get(i).StatusTitle);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.order_dialog_status_title)
.setMultiChoiceItems(statusesTitles.toArray(new String[statusesTitles.size()]), null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
if (b){
selectedStatusId.add(mStatuses.get(i).StatusId);
} else {
// TODO How I can delete my position from array?
}
}
})
.setPositiveButton(R.string.order_dialog_status_positive_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
refreshContent();
}
})
.setNegativeButton(R.string.order_dialog_status_negative_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
You can remove item by the following method.
ArrayList<Integer> selectedStatusId = new ArrayList<>();
if (true){
selectedStatusId.add(mStatuses.get(i).StatusId);
} else {
// delete the first occurrence of the specified element from array
selectedStatusId.remove(new Integer(mStatuses.get(i).StatusId));
}
final ArrayList<String> selectedStatusId = new ArrayList<>();
//MAKE IT STRING TYPE
final ArrayList<String> statusesTitles = new ArrayList<>();
for (int i = 0; i < mStatuses.size(); i++) {
statusesTitles.add(mStatuses.get(i).StatusTitle);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.order_dialog_status_title)
.setMultiChoiceItems(statusesTitles.toArray(new String[statusesTitles.size()]), null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean b) {
if (b) {
selectedStatusId.add(String.valueOf(mStatuses.get(i).StatusId));
} else {
// TODO How I can delete my position from array?
selectedStatusId.remove(String.valueOf(mStatuses.get(i).StatusId));
}
//OR_______________________YOU CAN USE THIS ALSO
// if (selectedStatusId.contains(String.valueOf(mStatuses.get(i).StatusId))) {
// selectedStatusId.remove(String.valueOf(mStatuses.get(i).StatusId));
// } else {
// selectedStatusId.add(String.valueOf(mStatuses.get(i).StatusId));
// }
}
})
.setPositiveButton(R.string.order_dialog_status_positive_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
refreshContent();
}
})
.setNegativeButton(R.string.order_dialog_status_negative_button, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
Hope this helps..
I am having some problem when trying to refresh the rating bar after user submitted their rating. So basically I am passing the existing rating amount when certain button on my other Activity was triggered:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Object[] obj = new Object[2];
obj[0] = String.valueOf(eventIDTV.getText());
obj[1] = eventReviewModel;
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Passing whole object with value into another activity
Intent eventDtlIntent = new Intent(context, EventDetailMain.class);
// Pass in a list of rating star together with amount
eventDtlIntent.putExtra("eventPopulateStarObj", populateRatingStar);
context.startActivity(eventDtlIntent);
}
}).execute(obj);
}
});
And I am populating the rating bar when onCreate():
ratingStarList = (ArrayList<EventReview>) i
.getSerializableExtra("eventPopulateStarObj");
public void populateRatingProgressBar() {
int totalStar = 0;
// Get the total amount of rate records
for (int j = 0; j < ratingStarList.size(); j++) {
if (ratingStarList.get(j).getStarAmt() != null) {
totalStar += Integer.parseInt(ratingStarList.get(j)
.getStarAmt());
}
}
txtTotalRate.setText(totalStar + " Ratings for this event");
// Set progress bar based on the each rates
for (int i = 0; i < ratingStarList.size(); i++) {
if (ratingStarList.get(i).getStarAmt() != null) {
if (ratingStarList.get(i).getEventReviewRate().equals("5")) {
pb5Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("4")) {
pb4Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("3")) {
pb3Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("2")) {
pb2Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("1")) {
pb1Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
}
}
}
}
It did populated correctly. However, I not sure how to refresh the rating bar after user submitted their rating. Here is the code when user submit their rating:
public void promptSubmitStar() {
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView
.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate
+ " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EventReview eventReviewModel = new EventReview();
eventReviewModel.setEventID(eventID);
eventReviewModel.setEventReviewBy(userID);
eventReviewModel.setEventReviewRate(String.valueOf(starRate));
new CreateEventReviewAsyncTask(context)
.execute(eventReviewModel);
dialog.dismiss();
// Disable the rating bar by setting a touch listener which
// always return true
ratingBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
return true;
}
});
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Dialog d = Dialog.show();
EventDialogueBox.customizeDialogueBox(context, d);
}
Any ideas? Thanks in advance.
Use setRating(starRate); to programmatically set the rating on the RatingBar.
I'm trying to follow the android docs about multiple selection dialog boxes. I'm having an issue, and I think it's with the type of arrays i'm trying to load in.
public void addCondition(View view){
ArrayList<String> mHelperNames= new ArrayList<String>();
mHelperNames.add("Test Item");
mHelperNames.add("Test Item");
mHelperNames.add("Test Item");
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Create onlcick method
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Create onlcick method
}
});
builder.show();
}
Above is my code, but it's red-line city in eclipse:
In the docs, mSelectedItems is never declared, and I'm not too sure what I'm declaring it as.
The error on .SetMultipleChoiceItems is:
The method setMultiChoiceItems(int, boolean[], DialogInterface.OnMultiChoiceClickListener) in the type AlertDialog.Builder is not applicable for the arguments (ArrayList, null, new DialogInterface.OnMultiChoiceClickListener(){})
But if i change it from a string, how do I show text items in it? Any help will be really appreciated.
Tom
You must provide a CharSequence[] to setMultiChoiceItems method, not an ArrayList.
You could create mHelperNames like this:
CharSequence[] mHelperNames = new CharSequence[] { "test item 1", "test item 2" };
And don't forget to declare mSelectedItems too:
final List<Integer> mSelectedItems = new ArrayList<Integer>();
(It has to be final because you access it from an inner class)
You can also keep mHelperNames as an ArrayList if you need to modify it later. Then you need to convert it to an array when calling setMultiChoiceItems:
List<CharSequence> mHelperNames = new ArrayList<CharSequence>();
mHelperNames.add("Test Item 1");
mHelperNames.add("Test Item 2");
final List<Integer> mSelectedItems = new ArrayList<Integer>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title")
.setMultiChoiceItems(mHelperNames.toArray(new CharSequence[mHelperNames.size()]), null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer
.valueOf(which));
}
}
})