Use method to create multiple AlertDialog with varying behavior - java

I have an activity with several buttons. I want each button to open an AlertDialog to confirm the user's action before continuing. I am looking for a way to create a method that will set up the AlertDialog, pass in a string for the title and message, and then pass a result back to the activity so I can have it select what action to do. I have looked around and not been able to find a way to pass a result back to the activity, but the if statement to check the result runs before the user clicks the dialog's button.
Here is what I have so far in Activity.java:
#Override
public void onClick(View v) {
String title, message;
switch (v.getId()) {
case R.id.settings_btn_cleardatabase:
title = getResources().getString(R.string.settings_dialog_clearstats_title);
message = getResources().getString(R.string.settings_dialog_clearstats_text);
showDialog(title, message);
// This is the part that gets bypassed before user clicks dialog button
if (mResultCode == RESULT_OK) {
Toast.makeText(SettingsActivity.this, "Player Scores Cleared", Toast.LENGTH_SHORT).show();
}
break;
case R.id.settings_btn_cleargaminggroup:
title = getResources().getString(R.string.settings_dialog_cleargroup_title);
message = getResources().getString(R.string.settings_dialog_cleargroup_text);
showDialog(title, message);
if (mResultCode == RESULT_OK) {
Toast.makeText(SettingsActivity.this, "Gaming Group Cleared", Toast.LENGTH_SHORT).show();
}
break;
}
}
Generic Alert Method:
private void showDialog(String title, String message) {
AlertDialog.Builder clearStatsDialogBuilder = new AlertDialog.Builder(this);
// Sets title
clearStatsDialogBuilder.setTitle(title);
// Sets message
clearStatsDialogBuilder
.setMessage(message)
.setIcon(R.drawable.ic_warning_white_24dp)
.setCancelable(false)
.setPositiveButton(R.string.settings_dialog_clear_confirmbtn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mResultCode = RESULT_OK;
}
})
.setNegativeButton(R.string.settings_dialog_clear_cancelbtn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mResultCode = RESULT_CANCELED;
dialog.cancel();
}
});
// Create alert dialog
AlertDialog clearStatsDialog = clearStatsDialogBuilder.create();
// Show it
clearStatsDialog.show();
}

Did you try this ?
create your DialogFragment and define an interface that the Activity will implement
Then in the DialogFragment when you want to return the result to the Activity you cast the activity to the interface
In the Activity you implement that interface and get the values
example :
//////////// 1 stage
public interface DialogFragmentListener {
public void onReturnValue(String reurnValue);
}
/////////////////////////// 2 stage
#Override
public void onClick(DialogInterface dialog, int id) {
DialogFragmentListener activityDL = (DialogFragmentListener) getActivity();
activityDL.onReturnValue("Pass the value");
}
/////////////////////////////// 3 stage
public class MyActivity implements DialogFragmentListener {
...
#Override
public void onReturnValue(String returnVal) {
Log.d("onReturnValue", "Got value " + returnVal+ " back from Dialog!");
}
}
refer ->Using DialogFragments

Related

Create and show Toasts/Snackbars from within AlertDialog

I have a recyclerlistview that is populated using inputs gathered from an AlertDialog, which is spawned from a floating action button. When the positive button in the AlertDialog is pressed and all inputs are formatted correctly the SQLite db gets updated and after that the snackbar is made and shown from within the same listener.
If the input is malformatted, then toast is displayed, but also the dialog closes which i do not want
If the input is correct the dialog closes and the data gets added to the list, but the SnackBar is not showing
This is the onClickListener in my MainActivity:
#Override
public void onClick(View view)
{
switch ( view.getId() )
{
case R.id.add_item_btn:
View addDialogView = getLayoutInflater().inflate(R.layout.add_dialog, null);
final EditText addItemNameTxt = addDialogView.findViewById(R.id.add_item_name_txt);
final EditText addItemCountTxt = addDialogView.findViewById(R.id.add_item_count_txt);
// something unimportant left out
new AlertDialog.Builder(this)
.setView(addDialogView)
.setCancelable(true)
.setPositiveButton("Add", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int i)
{
if ( addItemNameTxt.getText().length() == 0 )
{
Toast.makeText(MainActivity.this, "Text cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
String itemName = addItemNameTxt.getText().toString();
String itemCount = addItemCountTxt.getText().toString();
dbHelper.insertTask(itemName, Integer.parseInt(itemCount));
taskAdapter.swapCursor(dbHelper.getTasks());
dialog.dismiss();
Snackbar.make(getLayoutInflater().inflate(R.layout.activity_main, null).findViewById(R.id.rootLayout), String.format("Added \"%s (%s)\" to list", itemName, itemCount), Snackbar.LENGTH_LONG);
}
})
.create().show();
break;
}
}
It works (= not closing for toasting + snacking upon successful exit) when a button is put into the custom layout and that one is used instead of AlertDialog.PositiveButton.
final AlertDialog dialog = new AlertDialog.Builder(this)
.setView(addDialogView)
.create();
addDialogView.findViewById(R.id.add_confirm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
if ( addItemNameTxt.getText().length() == 0 )
{
Toast.makeText(MainActivity.this, "Text cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
String itemName = addItemNameTxt.getText().toString();
String itemCount = addItemCountTxt.getText().toString();
dbHelper.insertTask(itemName, Integer.parseInt(itemCount));
taskAdapter.swapCursor(dbHelper.getTasks());
Snackbar.make(view, String.format("Added \"%s (%s)\" to list", itemName, itemCount), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();

Android Studio, How to change dynamically view in dialog, case: Retrofit onSuccess

By using the retrofit as REST Client,
private void doGetRestBagLotNumber(int bagNumber, String lotNumber, final BagLotNumberRestService callback) {
Call<BagLotNumberModel> call = bagLotNumberRestService.getAntamBagLotNumber(bagNumber, lotNumber);
call.enqueue(new Callback<BagLotNumberModel>() {
#Override
public void onResponse(Call<BagLotNumberModel> call, Response<BagLotNumberModel> response) {
if (response.code() == 404 || response.code() == 422) {
Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
} else {
int id = response.body().getId();
int bagNumber = response.body().getBagNumber();
String lotNumber = response.body().getLotNumber();
// Adding the response to recylerview
preparedObjectDataBagLotNumber(id, bagNumber, lotNumber);
callback.onSuccess(response.body() != null);
}
}
#Override
public void onFailure(Call<BagLotNumberModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have a method to display a dialog that contains several edit text
to input data from the user.
Here's the code.
private void addItemTextMethod() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts_antam_incoming, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertDialog builder
alertDialogBuilder.setView(promptsView);
final EditText bagNumber = (EditText) promptsView.findViewById(R.id.editTextDialogAntamBagNumber);
final EditText lotNumber = (EditText) promptsView.findViewById(R.id.editTextDialogLotNumber);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Search", null)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
doGetRestBagLotNumber(
Integer.parseInt(bagNumber.getText().toString()), lotNumber.getText().toString(),
new BagLotNumberRestService() {
#Override
public void onSuccess(boolean value) {
if($value){
// The question is here
// Show Big Thick in center of dialog
// Show bottom option, Close or Adding More
// If user choose Adding More , display this dialog again
}
}
#Override
public Call<BagLotNumberModel> getAntamBagLotNumber(int bagNumber, String lotNumber) {
return null;
}
}
);
});
}
});
alertDialog.show();
}
How when the result of the doGetRestBagLotNumber callback is true,
the app show option like this:
Show Big Thick in center of dialog as Success message
Show bottom option, Close or Adding More.
If user choose Adding More , display this dialog again
Any help it so appreciated
Use the instance of your inflated view to change the child views inside it. For example use this inside your onSuccess method:
((ImageView)promptsView.findViewById(R.id.tickIndicationView)).setImageResource(R.drawable.ic_tick);

Change Color of Negative Button when It is clicked

.setNegativeButton("Favorite", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
fav=true;
user = db.userDao().findByName(email);
if(user.getmFavorite()==null)
{
// Log.i("Check List", user.getmFavorite());
Log.i("Number1", "Numer1");
//String favorite = user.getmFavorite();
user.setmFavorite(newFav);
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "Successfully Favorited", Toast.LENGTH_SHORT);
toast.show();
Log.i("Check List", user.getmFavorite());
db.userDao().Update(user);
}
else{
String favorites = user.getmFavorite();
tokenize(favorites);
Set<String> set = new HashSet<String>(items);
if(set.contains(newFav))
{
Log.i("Number221", "Numer221");
Log.i("Check List", user.getmFavorite());
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "This user is already favorite", Toast.LENGTH_SHORT);
toast.show();
}
else {
Log.i("Number331", "Numer331");
Log.i("Check List", user.getmFavorite());
String fav2 = favorites + "," + newFav;
user.setmFavorite(fav2);
Context context = getActivity();
fav = true;
toast = Toast.makeText(context, "Successfully Favorited", Toast.LENGTH_SHORT);
toast.show();
Log.i("Check List2", user.getmFavorite());
db.userDao().Update(user);
}
}
}
})
Hello I want to change the color of Button when I click the Negative button.
So if Negative Button was red , and I click it it should change to Blue, and If I click Positive Button change Negative Button's color to red. I dont know how to do this ....
You can try this -
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
if(clicked)
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.YOUR_COLOR_NAME));
}
});
If I got it straight, you simply want to change the button's colour from red to blue and vice-versa each time someone presses the button. You were kind of ambiguous in the objective.
The easiest way I know of doing that is using a flag to see which colour is supposed to be on the button. You also have the setBackgroundColor method that programmatically changes the color.
So I would do something like
if(!isRed)
btn.setBackgroundColor(getResources().getColor(R.color.red));
else
btn.setBackgroundColor(getResources().getColor(R.color.blue));
being that red and blue are custom colours. You can make them in your colors.xml file.
You need to have the setBackground method inside onClick to make sure it's triggered.
try this:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View alertDialog= View.inflate(this.getActivity(), R.layout.alert_dialog,
null);
builder.setTitle(getLocalizedString("Message"))
.setView(eventEditDialogView)
.setPositiveButton(getLocalizedString("Ok"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(getLocalizedString("Cancel"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
return builder.create();
}
#Override
public void onStart() {
super.onStart();
Button positive = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
positive.setTextColor(Color.BLACK);
positive.setBackgroundColor(getResources().getColor(R.color.GrayBGColor));
}
it helps you

Execute after close dialog

I have a button that open a dialog for change a number. The button is in activity, and generate a new class names dialogs, for storage different dialogs.
Dialog consigna: Dialogs.class
public String consigna(){
AlertDialog.Builder alert = new AlertDialog.Builder(ctxt);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(ctxt);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data = input.getText().toString();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data;
}
on click button: MainActivity
//I need change these two values:
final public double temperatura = 200.3;
String newData;
...
public void onClick(View v) {
switch (v.getId()){
case R.id.tempConsigna:
dialog = new Dialogs(MainActivity.this);
String data = dialog.consigna();
newData = data;
break;
...//other cases...
The issue is in newData = data; I doesn't have a data, because the dialog not are closed. The dialog work in other thread,no?
How to change newData var with the dialog result? It is posible into a dialogs class?
You need a callback method implemented via an interface:
public String consigna(final OnConfirm confirm){
final String[] data = new String[1];
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(activity);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data[0] = input.getText().toString();
confirm.onConfirm(data[0]);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data[0];
}
public interface OnConfirm {
void onConfirm(String s);
}
And in your Main Activity
Dialogs dialog = new Dialogs(MainActivity.this);
dialog.consigna(new Dialogs.OnConfirm() {
#Override
public void onConfirm(String s) {
Log.d("data", s);
}
});
It will not return result as you want but after click on dialog ok button then access data variable. no need to return.

Differentiate single Dialogs with DialogInterface.OnClickListener

We have two AlertDialog objects
AlertDialog dialog1, dialog2;
both dialogs are created via AlertDialog.Builder.
How can we recognize which dialog is source of event in DialogInterface.OnClickListener ?
with single dialog we can do this:
AlertDialogInstance.setOnClickListener(myListener);
//myListener
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1) {
case AlertDialog.BUTTON_NEGATIVE:
// do something
break;
case AlertDialog.BUTTON_POSITIVE:
// do something
break;
case AlertDialog.BUTTON_NEUTRAL:
// do something
break;
}
}
how to modify this switch logic to handle multiple dialogs?
(Or if there is better system to handle dialogs, other than inline button callbacks, what is it?)
I'll recommend you to put needed param in the custom listener.
private class CustomOnClickListener implements OnClickListener {
private int id;
public CustomOnClickListener(int id) {
this.id = id;
}
public void onClick(DialogInterface dialog, int which) {
//check id and which
}
}
Then, when you add onClickListeners to dialogs, you just provide an id to listener.
private AlertDialog dialog1;
private AlertDialog dialog1;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dialog1 = new AlertDialog.Builder(this).setTitle("dialog1").create();
dialog1.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", this);
dialog2 = new AlertDialog.Builder(this).setTitle("dialog2").create();
dialog2.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", this);
}
#Override
public void onClick(final DialogInterface dialog, final int which)
{
if (dialog == dialog1)
{
if (which == AlertDialog.BUTTON_POSITIVE)
{
//
}
else if (which == AlertDialog.BUTTON_NEGATIVE)
{
//
}
}
else if (dialog == dialog2)
{
if (which == AlertDialog.BUTTON_POSITIVE)
{
//
}
else if (which == AlertDialog.BUTTON_NEGATIVE)
{
//
}
}
}
If your dialogs have differentiable content, you can obviously tell the dialog directly by its content:
if(which==AlertDialog.BUTTON_NEGATIVE)return;
AlertDialog theDialog = (AlertDialog)dialog;
if(theDialog.findViewById(R.id.phoneinput)!=null) ...;//handle the phone
if(theDialog.findViewById(R.id.emailinput)!=null) ...;//handle the email
Of course the solution is NOT universal, but quite handy in some cases.

Categories