Single alert dialog for entire application - android

I have to display many error messages and alert dialogues in my application.
I do not want to use Toast, I prefer to use AlertDialog.
Instead of creating a new alert dialog in every activity, how do I create and maintain one alert dialog and just change the error message string in it?
Whatever activity I am in, I must be able to access the AlertDialog instance to show and dismiss it.
How can I achieve this? Kindly give me some lead on this.

make one class and paste this function...(may be Utils.java)
public static void alertDialogShow(Context context, String message)
{
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.dismiss();
}
});
alertDialog.show();
}
and call this by writing..
Utils.alertDialogShow(YourActivity.this,"Your Error Message")

You could always write a base class of Activity with your alertdialog call as a method and then for any of your activity classes instead of using extends Activity, use extends MyBaseActivity and then call the method whenever you need it by passing the string you want output.

I do something like this in a helper class
public static void AlertBox(final Activity activity, final String title, final String message)
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(activity);
alertbox.setTitle(title);
alertbox.setCancelable(false);
alertbox.setMessage(message);
alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
activity.finish();
}
});
alertbox.show();
}

Try this:
/**
* Class for showing validation message
*/
package com.prj.utility;
import com.prj.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.prj.utility.System;
public class ValidationPopup {
Context mContext = null;
public ValidationPopup(Context mContext) {
// TODO Auto-generated constructor stub
this.mContext = mContext;
}
/**
*
* #param strTitle - title of dialog
* #param strMessage - message to be shown in dialog
* #param value - edit text object
*/
public void showValidationDialog(String strTitle, String strMessage,
final EditText value) {
final AlertDialog dlgValidationPopUp = new AlertDialog.Builder(mContext)
.create();
final LayoutInflater lyInflaterForDlgTitle = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout lLayoutCustTitle = (LinearLayout) lyInflaterForDlgTitle
.inflate(R.layout.custom_title, null);
TextView tvTitle = (TextView) lLayoutCustTitle
.findViewById(R.id.tvTitle);
tvTitle.setText(strTitle);
dlgValidationPopUp.setCustomTitle(lLayoutCustTitle);
if (strMessage == null || strMessage.trim().equalsIgnoreCase("")) {
//If there isn't any message in database for validation of the field, then DEFAULT_MESSAGE will be used
strMessage = Config.DEFAULT_MESSAGE;
}
dlgValidationPopUp.setMessage(strMessage);
dlgValidationPopUp.setCancelable(true);
dlgValidationPopUp.setButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dlgValidationPopUp.dismiss();
//Edittext will be given focus if the field is edit text and it is not null
if (value != null)
value.requestFocus();
}
});
dlgValidationPopUp.show();
}
}
You can make this class's object anywhere in your application as,
ValidationPopup vPopup = new ValidationPopup(mContext);
And call method showValidationDialog according to your need
vPopup.showValidationDialog("Alert Msg","This is message content", objectOfEditText);//You can pass null as third arg if its not for edittext.

Related

setOnDismissListener resulting in dismissed DialogFragment being reshown after config change

In my Fragment's onCreateView() method, I call my showHelp() method to show a DialogFragment, employing an OnDismissListener so some other code can be executed when the dialog is dismissed:
protected void showHelp(DialogInterface.OnDismissListener onHelpDismissListener) {
String helpTitle = getHelpTitle();
String helpContent = getHelpContent();
InfoDialog helpDialog = InfoDialog.newInstance(helpTitle, helpContent);
helpDialog.showNow(getChildFragmentManager(), InfoDialog.TAG);
Dialog dialog = helpDialog.getDialog();
Log.d(TAG, "For helpDialog dialog, setting dismiss listener: " + onHelpDismissListener);
if (onHelpDismissListener != null) {
/*
* When I remove this line, InfoDialog behaves properly - i.e., if it is dismissed, then
* the device rotated, it is not displayed again.
*
* Even when the onHelpDismissListener's `onDismiss()` method performs no action, the problem still occurs.
*/
dialog.setOnDismissListener(onHelpDismissListener);
}
}
However, the inclusion of the dialog.setOnDismissListener(onHelpDismissListener); line results in the dialog being displayed again on the UI after a config change, despite it having been previously dismissed.
If I remove that line, it behaves as it should do. (But, obviously, I don't get my callback.)
For completeness, here is my InfoDialog class:
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;
public class InfoDialog extends DialogFragment {
public static final String TAG = InfoDialog.class.getSimpleName();
private static final String ARG_TITLE = "ARG_TITLE";
private static final String ARG_MESSAGE = "ARG_MESSAGE";
private InfoDialogViewModel mInfoDialogViewModel;
public static InfoDialog newInstance(String title, String message) {
InfoDialog infoDialog = new InfoDialog();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
infoDialog.setArguments(args);
return infoDialog;
}
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
Bundle args = getArguments();
if (args == null) {
throw new RuntimeException("Null args!");
}
Context context = requireContext();
mInfoDialogViewModel = new ViewModelProvider(requireActivity()).get(InfoDialogViewModel.class);
String title = args.getString(ARG_TITLE);
String message = args.getString(ARG_MESSAGE);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(Utilities.fromHtml(context, title, this, null));
builder.setMessage(Utilities.fromHtml(context, message, this, null));
builder.setPositiveButton(R.string.ok, (DialogInterface dialog, int id) -> {
mInfoDialogViewModel.setResult(InfoDialogViewModel.RESULT_OK);
});
builder.setCancelable(true);
builder.setOnCancelListener((DialogInterface dialog) -> {
mInfoDialogViewModel.setResult(InfoDialogViewModel.RESULT_CANCELLED);
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Any ideas why this problem is happening? And how can I prevent the dismissed dialog from re-appearing after a config change?
Alternatively, is there another way to listen for the dialog being dismissed?

My Dialog on Android comes up Blank

So I'm trying to create a dialog pop up. Here's the Dialog fragment I created in a separate DialogClass.Java file
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class DialogClass extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder newAlertDialog = new AlertDialog.Builder(getActivity());
newAlertDialog.setTitle("Dialog");
newAlertDialog.setMessage("This is a dialog");
newAlertDialog.setPositiveButton(("OK"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), ("You clicked Ok"), Toast.LENGTH_SHORT).show();
}
});
newAlertDialog.setNegativeButton(("Cancel"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), ("You clicked Cancel"), Toast.LENGTH_SHORT).show();
}
});
return super.onCreateDialog(savedInstanceState);
}
}
Then when I use this class to create a method it brings us a blank dialog box when I run the app. This is how I use it:
Note: myButtinClick is a method that runs on the click of a button.
public void myButtonClick(View view) {
DialogFragment myFrag = new DialogClass();
myFrag.show(getFragmentManager(), "");
}
Please can anyone figure out what I am doing wrong?
See a screenshot of what the Dialog looks like via this link.
http://i.stack.imgur.com/xsQQj.png
You've only created the Dialog builder, but not the Dialog itself.
You should return newAlertDialog.create() and rename newAlertDialog to dialogBuilder or something like that.

Alert Dialog with Number Picker - Without implementing Listner

I am new in Android Development. I want to open the Alert Dialog for Number Picker from Main Activity, and then take input from Alert Dialog and show it in the Main view.
I have written code from taking some references and its working correct. But i don't want to use " implements NumberPickerFragment.NoticeDialogListener" in main activity. Please help me, how can i return the value to main activity.
My code for Main Activity is:
package com.pinnacleappdesign.pinnacleappdesign;
import android.os.Bundle;
import android.app.Activity;
import android.app.DialogFragment;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements NumberPickerFragment.NoticeDialogListener{
int memoryIndex = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Button firstPaneButton = (Button)findViewById(R.id.first_pane_button1);
firstPaneButton.setOnClickListener(new OnClickListener() {
public void onClick(View v){
DialogFragment newFragment = new NumberPickerFragment();
Bundle args = new Bundle();
args.putInt("currentMemoryIndex", memoryIndex);
newFragment.setArguments(args);
newFragment.show(getFragmentManager(), "numberPicker");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onDialogPositiveClick(int newMemoryIndex) {
this.memoryIndex = newMemoryIndex;
/** Getting the reference of the textview from the main layout */
TextView tv = (TextView) findViewById(R.id.tv_android);
/** Setting the selected android version in the textview */
tv.setText("Your Choice : " + this.memoryIndex);
}
}
My code for NumberPickerFragment.java is:
package com.pinnacleappdesign.pinnacleappdesign;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.Toast;
public class NumberPickerFragment extends DialogFragment{
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callbacks.
* Each method passes the DialogFragment in case the host needs to query it. */
public interface NoticeDialogListener {
public void onDialogPositiveClick(int newMemoryIndex);
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = getArguments();
int currentMemoryIndex = bundle.getInt("currentMemoryIndex");
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View DialogView = inflater.inflate(R.layout.number_picker, null);
final NumberPicker np = (NumberPicker)DialogView.findViewById(R.id.numberPicker1);
np.setMinValue(1);
np.setMaxValue(100);
np.setWrapSelectorWheel(false);
np.setValue(currentMemoryIndex);
builder.setTitle(R.string.dialog_title)
.setView(DialogView)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User confirmed the dialog
int position = np.getValue();
mListener.onDialogPositiveClick(position);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
What is wrong with your current method? That appears to be the method Android encourages developers to use as seen here: Communicating with Fragments
You can also do something like this within your NumberPickerFragment:
((MainActivity) getActivity()).yourMethod();
But IMO it is much cleaner and re-usable to use the defined Interface method.

how to set a text to a Edittext which is in a dialog box?

The question is as you can see that I cant set the value of edittext dynamically before showDialog().
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int DIALOG_TEXT_ENTRY = 7;
private int user_id;
private int dialogChoice;
private String mobileNum;
private EditText input2 ;
private EditText input1 ;
public TextView textView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert_dialog_text_entry);
TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
mobileNum =tm.getLine1Number();
// input1.setText(mobileNum);
textView.setText("hello");
showDialog(DIALOG_TEXT_ENTRY);
}
#Override
protected Dialog onCreateDialog(int i) {
switch (i) {
case DIALOG_TEXT_ENTRY:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
input2 = (EditText) textEntryView.findViewById(R.id.number_edit);
input1 = (EditText) textEntryView.findViewById(R.id.username_edit);
textView = (TextView) textEntryView.findViewById(R.id.username_view);
return new AlertDialog.Builder(MainActivity.this)
// .setIconAttribute(android.R.attr.accountType)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent i = new Intent(MainActivity.this, IccActivity.class);
startActivity(i);
/* User clicked OK so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
}
return null;
}
}
textView.setText("hello"); this line kills the app.
thanks in advance.
you should put this line textView.setText("hello"); into onCreateDialog() method as you are setting the value before it gets initialized.
You haven't initialized textView. You need this in your onCreate() before you do the textView.setText()
textView = (TextView) textEntryView.findViewById(R.id.username_view);
I guess you are getting NullPointerException? You should first ser your 'textView' field.
Find the TexView text that is in the dialog and set the text of the TextView
Try this link

I want to display seperate alerts for name and pass fields

Here is my code:
package com.example.userpage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class UserPage extends Activity {
AlertDialog.Builder builder;
private final static int EMPTY_TEXT_ALERT = 0;
#Override
public Dialog onCreateDialog(int id) {
switch(id) {
case EMPTY_TEXT_ALERT: {
builder = new AlertDialog.Builder(this);
builder.setMessage("Message:Fields Empty!!!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
return null;
}
String tv,tv1;
EditText name,pass;
TextView x,y;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.widget44);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent obj = new Intent(UserPage.this,UserPage.class);
startActivity(obj);
}
});
x = (TextView) findViewById(R.id.widget46);
y = (TextView) findViewById(R.id.widget47);
name = (EditText)findViewById(R.id.widget41);
pass = (EditText)findViewById(R.id.widget43);
Button button1 = (Button) findViewById(R.id.widget45);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//tv= name.getText().toString();
//tv1 = pass.getText().toString();
x.setText(tv);
y.setText(tv1);
tv = name.getText().toString();
if(tv.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
tv1 = pass.getText().toString();
if (tv1.trim().equals(""))
{
showDialog(EMPTY_TEXT_ALERT);
}
}
});
}
}
What is happening when you try to run it? Which part are you having a problem with?
From what I can tell your code is not going to display any dialogs because you've never called the dialog.show() method. You'd have to do something like this for the way you have it set up:
showDialog(EMPTY_TEXT_ALERT).show();
If you are trying to make it two separate dialogs, one for name, and one for pass then all you'd have to do is make another id variable and add a case: for it inside the switch statement that inside your showDialog(id) method.
You should also really consider using descriptive names for your variables. Your code would be easier to understand if you didn't use names like x,y, and widget#.

Categories

Resources