Get User Selection in Alert Dialog - java

I have a button inside a popupwindow that when clicked initializes an alertdialog with a list from which the user can choose from. I'm stuck trying to get the string value of the selected item from the list. I'm trying to get the item and then change the description text on the button to reflect the user's selection.
countryButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//String countryResult = countryList.get(which);
//countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});

You have to use ArrayAdapter.getItem() method. And if it isn´t just a copy paste mistake, don´t forget the #Override annotation. But what do You mean with "missing reference error"?
countryButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String countryResult = countryAdapter.getItem(which);//use this getItem() method
countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});

Related

The button that I have created does not work. Is there something wrong with my code?

I am building an app in Android studio and basically I want a window to popup when a user clicks the add button. I used the setOnClickListener but when I run the app, nothing happens. Could there possibly something wrong with my code?
Here's my MainActivity code
public class MainActivity extends AppCompatActivity {
Button addBtn;
ListView itemListView;
DatePickerDialog.OnDateSetListener dateSetListener;
String dateString = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button)findViewById(R.id.addBtn);
itemListView = (ListView)findViewById(R.id.itemListView);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.activity_popup_window, null);
EditText itemName = (EditText)view.findViewById(R.id.itemName);
Button expirationDateBtn = (Button)view.findViewById(R.id.expirationDateBtn);
builder.setView(view)
.setTitle("Add Item")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (itemName.getText().toString().isEmpty() || dateString == null) {
Toast.makeText(MainActivity.this,
"Item name or expiration date is missing",
Toast.LENGTH_LONG).show();
}
else{
//do action
}
}
});
//when clicked on Expiration Date Btn
//display date on button
AlertDialogBuilder doesn't create and show a new AlertDialog implicitly. It only prepares the dialog before explicitly calling create() (or you can directly call show() if you need to display your dialog in the moment it gets built).
Your code misses the following lines at the end of onClick():
AlertDialog dialog = builder.create();
dialog.show();
or just:
builder.show();

close Alert Dialog without using negative Buttons

I created an AlertDialog, which will either refresh the activity (when btnConfirm1 is pressed), or does nothing and simply closes down (when btnDisconfirm1 is pressed). Everything is working apart from btnDisconfirm1. How can I close the dialog?
So apparently AlertDialog does not have a dismiss or cancel method, but is there another way without using negative buttons? The thing is, I created a layout file for this dialog and I don't know how to put a negative button in my xlm-file.
Or should I use a completely different approach apart from AlertDialog? Thanks!
btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder2 = new AlertDialog.Builder(ScoreScreen.this);
View mView2 = getLayoutInflater().inflate(R.layout.dialog_confirm_delete, null);
Button btnConfirm1=(Button) mView2.findViewById(R.id.btnConfirm1);
Button btnDisconfirm1=(Button) mView2.findViewById(R.id.btnDisconfirm1);
btnConfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.setPlayerScore(0);
player2.setPlayerScore(0);
player3.setPlayerScore(0);
player4.setPlayerScore(0);
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
btnDisconfirm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT DO I PUT HERE???
}
});
mBuilder2.setView(mView2);
AlertDialog dialog = mBuilder2.create();
dialog.show();
}
});
First you should create the AlertDialog with
AlertDialog mDialog = mBuilder2.create();
And secondly you can dismiss the dialog inside the OnClickListener with
mDialog.dismiss();
You can put this method in your Util class. and use callbacks
public interface OnDialogDismiss {
void onPositiveClick();
void onNegativeClick();
}
Modify it as your requirement.
public void showDialogForMultipleCallback(Context context, String title, String message, boolean cancellable, String neutralBbtn, String negativeBtn, String positiveBtn, final OnDialogDismiss onDialogDismiss) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(cancellable);
if (neutralBbtn != null) {
builder1.setNeutralButton(neutralBbtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (negativeBtn != null) {
builder1.setNegativeButton(negativeBtn,
new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (alert11 != null)
alert11.dismiss();
}
});
}
if (positiveBtn != null) {
builder1.setPositiveButton(positiveBtn, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
onDialogDismiss.onPositiveClick();
}
});
}
alert11 = builder1.create();
alert11.show();
}

Adding and removing textviews from a dynamic list in Android Studio?

I've been struggling with this for a while now, looking for any tips how to proceed. I'm trying to create a fragment that has an add button, that will create a new textview and when clicking the textview , you would have the option to delete it.
Adding textviews works fine. The problem is in the foreach loop that sets up listeners for each textview and adds the option to delete them. It's forcing me to declare the current parameter final, or the deletion won't work. But if I do declare it final, then I can't add any new textviews to the list, so they wont have listeners.
So if anyone could give me some kind of a hint, that would be hugely appreciated.
Here's the list and the adding part.
//Variables
List<TextView> TextViews = new ArrayList<TextView>();
#Override
//Put button functionality here
public void onClick(View v) {
final LinearLayout myLayout = (LinearLayout) view.findViewById(R.id.linearlayout);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// Set up the input/
final EditText input = new EditText(getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notesIndex = new Integer(notesIndex + 1);
noteText = input.getText().toString();
TextView a = new TextView(view.getContext());
a.setText(noteText);
a.setHeight(150);
a.setGravity(Gravity.CENTER);
myLayout.addView(a);
TextViews.add(a);
noteTexts.add(noteText);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
And here is the foreach loop that sets up listeners for each TextView. They are both called in OnCreateView.
for (final TextView current : TextViews) {
current.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete?");
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myLayout.removeView(current);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
}
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
addViewToLayout();
}
});
void addViewToLayout(){
notesIndex = new Integer(notesIndex + 1);
noteText = input.getText().toString();
TextView a = new TextView(view.getContext());
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertToDelete(v)
}
});
a.setText(noteText);
a.setHeight(150);
a.setGravity(Gravity.CENTER);
myLayout.addView(a);
TextViews.add(a);
noteTexts.add(noteText);
}
void showAlertToDelete(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete?");
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myLayout.removeView(v);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}

Returning checked items from multi-choice dialog

By reading the documentation, I have managed to create a multiple choice dialog box. However, there's one bit that still has me completely stumped. When the user clicks "Okay", how do I return them to the parent Activity?
I"m referring to this particular comment:
// Set the action buttons
.setPositiveButton(R.string.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
...
}
How exactly would I 'return them to the component that opened the dialog'?
My dialog call in my activity:
public void chooseTeam(View v) {;
DialogFragment newDialog = MultiChoiceDialog.newInstance(teamNamesArray);
newDialog.show(getFragmentManager(), "Choose_team");
}
and my dialog code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] team = getArguments().getStringArray("team");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.choose_team).setMultiChoiceItems(team, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
list.add(team[which]);
} else if (list.contains(team[which])) {
list.remove(team[which]);
}
}
}).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selections = "";
for (String ms : list) {
selections = selections + "\n" + ms;
}
Toast.makeText(getActivity(), "Team Selected: " + selections,
Toast.LENGTH_LONG).show();
AddTaskActivity.chosenTeam = list;
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(getActivity(), "Cancelled.", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
You can make the ArrayList a class member variable like private ArrayList mSelectedItems;
See example code below
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList mSelectedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
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(R.string.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
// in this case the OK button has more or less no function but if want save the check options in database or shared preference, you can put your code here. So it depends on your use case.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
}

how to unselect all my checkbox

I'm trying without success to unselect all my checkbox picks
by pressing any button that in my java android program with this code
public void onListItemClick(ListView parent, View v, int position, long id)
{
parent.setItemChecked(position, parent.isItemChecked(position));
}
#Override
protected Dialog onCreateDialog(int id, Bundle args){
switch(id){
case 1:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"OK clicked!", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":" unchecked!"),Toast.LENGTH_SHORT).show();
}
})
.create();
}
return(null);
}
how to select all and unselect all ?
Well, my best guess is to save a reference for all of them on a list, and go through all of them selecting or unselecting them all. Something like this.
Crete a reference to hold all your checkboxes
List<CheckBox> myCheckBoxes = new ArrayList<CheckBox>();
myCheckBoxes.add(cb1);
myCheckBoxes.add(cb2);
myCheckBoxes.add(cb3);
....
Create a method that will get the value you want to set on the check boxes and call it whenever you want.
:
private checkAll(boolean value) {
for(CheckBox cb : myCheckBoxes) {
cb.setChecked(value);
}
}
Create two buttons:
Button unselectAllButton = (Button) findViewById(R.id.unCheckButton);
Button selectAllButton = (Button) findViewById(R.id.checkButton);
unselectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(false);
}
});
selectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(true);
}
});

Categories