How to create alert dialog on button when it is clicked? - java

I am trying to develop a small app as a part of my exam. Basically, I have a button that goes to a webpage and I want an alert dialog to pop up when the button is clicked and before the web page opens. This is what I have so far:
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
webViewAndroidWeekly();
}
private void webViewAndroidWeekly (){
Button btnWebpage = findViewById(R.id.btnwebpage);
btnWebpage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://androidweekly.net/"));
startActivity(intent);
}
});
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Thank you for using this app! :)", Toast.LENGTH_SHORT).show();
finish();
}
}
The button works and it opens the webpage so that part is set. I created a separate java class for the alert dialog and tried to implement it to work but I can't figure it out.
Dialog class:
public class InternetWarningDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIconAttribute(android.R.attr.alertDialogIcon);
builder.setTitle("Go to WebPage");
builder.setMessage("Are you sure you want to proceed to webpage? This may incur additional charges based on your mobile data plan!");
builder.setCancelable(false);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getActivity().finish();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = builder.create();
return alertDialog;
}
}

create this method in mainActivity ...... Call this showDialog() method in your main Activity where you want
public void showDialog(){
InternetWarningDialog exampleDialog = new InternetWarningDialog();
exampleDialog.show(getFragmentManager(),"Internet Dialog");
}
If its works accept the answer

You have created the AlertDialog, but to get the Alert dialog view use the method show() on AlertDialog.Builder as shown below
AlertDialog alertDialog = builder.create();
builder.show();

I cannot see any call for AlertDialog. You need to add the call for AlertDialog along with AlertDialog.show() and then open the webpage if the user clicks on Yes.
AlertDialog alertDialog = builder.create();
builder.show();
A familiar question has already been asked before. Please refer this
open a dialog when i click a button

Related

Problem with DialogFragment creation and invocation

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

DialogFragment OnDismissListener not working

i created a DialogFragment with a layout which contains a listview with some items and wanna do something with the value of the selected item but when i try to set the OnDismissListener it gives me an error.
If someone could help me, here is the code snippet where the error occurs.
When the execution reaches the dialog.getDialog().setOnDismissListener... then it gives the exception
FragmentManager manager = getFragmentManager();
PopupRecentBanderolNrs dialog = new PopupRecentBanderolNrs();
dialog.listitems[0] = GetFileContentsFromInternalStorage();
dialog.show(manager, "dialog");
manager.executePendingTransactions();
dialog.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
... some code ..,
}
});
DialogFragment already implements DialogInterface.OnDismissListener, You can override the onDismiss() method in your PopupRecentBanderolNrs class.
if you want set your Listener, you can set in onCreateDialog method:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = ...;// your dialog
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
return dialog;
}

AlertDialog is opened again

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 :)

popping up an AlertDialog on click a button in a ListView

I have ListView that is populated using a CursorAdapter. In each ListView row there are too textviews and a button. An AlerDialog is supposed to pop on button click.The AlertDiaog itself is filled with a cursor.
the problem is that when i try to make and alert dialog builder it needs an argument that i don't know how to get it. the code that i"m posting here has a syntax error that i don't know how to fix it.
i tried to move the ItemClickListener to original activity class but the button has null value when i try to assign it to an object.
this is the bindView of the CursorAdapter:
public void bindView(final View view, Context context, Cursor cursor) {
//ListView list= (ListView) view.findViewById(R.id.words);
Button addButton=(Button)view.findViewById(R.id.add_btn);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view1) {
//Dictionary d=new Dictionary();
AlertDialog.Builder builder=new AlertDialog.Builder(Dictionary.this); // the error
final Cursor boxes=Dictionary.getCursor();
builder.setCursor(boxes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dictionary.getCursor().moveToPosition(i);
String text = boxes.getString(boxes.getColumnIndex("_id"));
Log.d("select", "onClick: "+text);
}
}, "name");
builder.show();
}
});
TextView english=(TextView) view.findViewById(R.id.english);
TextView farsi=(TextView) view.findViewById(R.id.farsi);
english.setText(cursor.getString(1));
farsi.setText(cursor.getString(2));
}

Closing alert dialog after onClick from extended activity

In my main activity I have an alert dialog which creates a new intent when clicked. When the alert dialog is clicked and the new activity is opened I cannot dismiss the alert dialog even though I have included dialog.cancel(); in my main activity code.
Dialog builder (Main activity)
final Builder alertDialogBuilder = new Builder(this);
alertDialogBuilder.setTitle("Navigation");
alertDialogBuilder.setMessage("Go to the new activity.");
alertDialogBuilder.setNeutralButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "$$ onClick");
dialog.cancel();
Intent newactivity = new Intent(MAINACTIVITY.this,NEWACTIVITY.class);
startActivity(newactivity);
}
});
alertDialogBuilder.show();
After I click on the "Okay" button the dialog closes, but when the new activity is loaded the dialog reappears. The new activity extends the activity that the dialog is created in (Main activity).
Is there a way that I can close the alert dialog from the new extended activity?
try this way:
alertDialogBuilder.setPositiveButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "$$ onClick");
Intent newactivity = new Intent(MAINACTIVITY.this,NEWACTIVITY.class);
startActivity(newactivity);
dialog.cancel();
}
});
alertDialogBuilder.show();
good luck.

Categories