I am building an Android app that uses AlertDialog. I am following Google's guide to building an AlertDialog, but it keeps giving me an error. I set an onClickListener on a FAB, but it either never works or it throws an error.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("This is an alert dialog.").setTitle("alert dialog");
builder.create();
}
});
}
But the Android Studio throws an error, saying:
"error: cannot find symbol method getActivity()"
I've tried declaring a context variable and passing that, tried using getApplicationContext(), and getApplication(), but they all don't work.
What am I doing wrong?
Everything seems to be correct but some minor tweaks required in your code.
If you are going to display the alert dialog in the Activity use Activity.this , if it is in Fragment then use getActivity() during initialization of AlertDialog.Builder(*****).
Write the logic of the alert dialog in a separate function and call them in your clicklistener. Below code will help you.
void showAlert(){
// If using activity use this
AlertDialog.Builder adb = new AlertDialog.Builder(*YOUR ACTIVITY NAME*.this);
// If using Fragment use this
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
adb.setMessage("Alert Dialog Welcomes You");
adb.setTitle("Google alert dialog");
AlertDialog ad = adb.create();
ad.show();
}
Then call it in your fab onclicklistener.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAlert();
}
});
Happy coding..!!
If your class extend to activity, you should declare like this
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);
If extend to fragment:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
It appears that Android Studio is bugged in some way. I would try to fix that by selecting "invalidate caches / restart" from the File menu.
That said, you can also get a context by getting it from the view.
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
//do your stuff here.
}
Related
I'm trying to make it so a clear button will open up an alert dialog which has a yes or no. When clicking the yes button, it should pass a bool value from the dialog frag to the other frag. If the value is true, which it should be when yes is clicked, it will call methods which will clear a database. Here is the dialog frag and the part of the frag where I'm trying to implement it. I can't get the dialog box to appear, but so far it does make the screen darker which I assume means I'm not hooking it up right.
Dialog frag:
public class DialogClear extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.clear_dialog, null);
final Button yes = dialogView.findViewById(R.id.yes);
final Button no = dialogView.findViewById(R.id.no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
return builder.create();
}
}
Here is how I'm trying to call it from my frag
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogClear = new DialogClear();
dialogClear.setTargetFragment(BloodPressureFragment.this, 1);
dialogClear.show(getFragmentManager(),"");
dataManager.clearDatabase();
dataManager.createDatabase();
dataText.setText("");
dataText.setBackgroundResource(R.drawable.no_border);
updateList();
}
});
welcome to code party
you have many choices to do this job, but i will show you best way for using fragments.
As you know, all fragments changes in one activity and extend from it.
So the easy way is this:
1.build public fields in your activity
2.build a getInstant method on activity
3.fill and get values of that activity from any fragments that you want show on this
see this example:
public boolean isLocationOn;
this field is build in activity
now:
in any fragment:
MainActivity.getInstance().isLocationOn = true;
in other fragment:
if(MainActivity.getInstance().isLocationOn){
//todo show map or ...
}
in this way you can use anything in fragments
update me in comments
You should read and try using 3 thing's to solve this.
1. Navigation Component
easy to navigate to fragment's and DialogFragment
2. View Model
Share same View Model between different fragment's of an activity
Data is not lost on Orientation change's
All business logic at one place and easy to unit test
3. Live Data
recommended for responsive ui
Easy to understand Api's
I'm creating a simple DialogFragment with two buttons, which is supposed only to show a Toast when you select any of the two options. This dialog is displayed when you press one certain button on a activity.
For some reason, the code doesn't show any kind of error but when i click the button, the app crashes.
How do I resolve this?
I was first trying to do a custom XML file and java file for the Dialog, but i couldn't make that work either. Google's documentation and other tutorials didn't help either
public class Config extends AppCompatActivity {
Button btncanc;
Button btnreestab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config);
btncanc = (Button) findViewById(R.id.btncnacelset);
btnreestab = (Button) findViewById(R.id.btnrest);
btncanc.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(),"OperaciĆ³n cancelada",Toast.LENGTH_SHORT);
toast.show();
Config.this.finish();
}
});
btnreestab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Hola");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(getApplicationContext(),"hola",Toast.LENGTH_SHORT);
toast.show();
}
});
builder.setNegativeButton("cancela", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(getApplicationContext(),"adios",Toast.LENGTH_SHORT);
toast.show();
}
});
AlertDialog dialog = builder.create(); dialog.show();
}
});
}
}
You can copy your style from your context. Make your alert dialog initialization with.
new AlertDialog.Builder(Config.this)
in other way you can define a custom style in style.xml such as
<style name="myDialog" parent="Theme.AppCompat.Dialog">
<item name="android:windowNoTitle">true</item>
...
</style
and initialize alert dialog with
AlertDialog.Builder dialog = new AlertDialog.Builder(getApplicationContext(), R.style.myDialog);
The reason for this crash is the AppCompatActivity has the Theme.AppCompat so you should use this theme.
checkout that crash.
You need to use a Theme.AppCompat theme (or descendant) with this
activity
I have a dialog in my launcher activity that requires some user input and to display it I have this code in onCreate()...
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
DialogBinding dialogBinding = DataBindingUtil.setContentView(this, R.layout.dialog);
popupBinding.dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
The dialog button has an onClick listener to close it, but in order to do that, the dialog must be declared final. Previously (when this activity was not the launcher), I had the dialog declared as an instance variable, but this causes an error now.
private Dialog dialog = new Dialog(this);
However, declaring the dialog in the onCreate method causes the launcher activity's layout to be replaced with the dialog's so that the dialog appears over a copy of itself.
I'm not sure why it is doing that, but I was wondering if there is a way to prevent this. Thanks!
This accidentily sets the dialog layout as the content view for your activity.
DialogBinding dialogBinding = DataBindingUtil.setContentView(this, R.layout.dialog);
So you're mixing your activity with the dialog.
For your Activity, this should be something like
MyActivityBinding activityBinding = DataBindingUtil.setContentView(this, R.layout.my_activity);
There is a fragment. When I press button on this fragment alert dialog is shown. This dialog is dissmissed after clicking on OK button. If I go to next fragment from current fragment and then come back - previous fragment is appeared with opened alert dialog. I use Cicerone for navigating. Maybe somebody faced with this problem?
// for navigating
router.navigateTo(screenKey);
// show dialog
AlertDialog alert = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, (dialog, which) -> dialog.dismiss())
.setCancelable(true)
.create();
alert.show();
// in my second fragment
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
showBackButton();
}
// in my main activity
#Override
public void showBackButton() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(Utils.getDrawable(this, R.drawable.ic_arrow_back_white_24dp));
toolbar.setNavigationOnClickListener(v -> {
onBackPressed();
});
}
#Override
public void onBackPressed() {
hideKeyboard();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
hideDrawerLayout();
} else {
super.onBackPressed();
}
}
#Override
protected void onResume()
{
super.onResume();
dialog.close()
}
This will do the trick, in your parent activity where you are creating your dialog add this. Try to comment and uncomment super.onResume(); while testing.
What i got that You are navigating in first line and in next step you are showing the Dialog. These will execute one after another. I Hope you got my point . Do it as below :
AlertDialog alert = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, (dialog, which) ->
dialog.dismiss()// Optinal
router.navigateTo(screenKey);
)
.setCancelable(true)
.create();
alert.show();
And no need to dismiss the dialog, cause its the default behavior of AlertDialog.Let me know its solved your problem. Thanks.
Well, I have find a solution. Point is that Moxy framework is used in my project and I didn't set right state strategy type in my views. Now I use SkipStrategy to not pile up commands in the queue. Sorry for your time I spent :)
I am trying to build a alert box in android studio, i have 2 xml and 1 activity class where on click of a button i want to show the other layout.
I am getting a error, here is my code of MainActivity
cancelBookingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.alert_cancel_confirm, null);
final TextView disAgree = (TextView) alertLayout.findViewById(R.id.TextDisagree);
final TextView Agree = (TextView) alertLayout.findViewById(R.id.TextAgree);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Current Booking");
// This will set the view from XML inside ALertDialog
alert.setView(alertLayout);
// disabling cancel of AlertDialog on click of back button and outside touch
alert.setCancelable(false);
AlertDialog dialog = alert.create();
dialog.show();
}
});
In this line i am getting error
AlertDialog.Builder alert = new AlertDialog.Builder(this);
In Builder cannot be applied
Any idea why i am getting this.
AlertDialog.Builder alert = new AlertDialog.Builder(YourActivity.this);
alert.setTitle("Current Booking");
// This will set the view from XML inside ALertDialog
alert.setView(alertLayout);
// disabling cancel of AlertDialog on click of back button and outside touch
alert.setCancelable(false);
AlertDialog dialog = alert.create();
dialog.show();