How do I reduce alert-dialogue code from main-activity in android? - java

I have a class where I am writing three different alert dialogue. These three alert dialogue extends the line of code of this class drastically. So for re-factoring purpose, I want to make base class for three alert dialogue and use this class in the main activity. Can anyone suggest me how to achieve this? My three alert dialogue are given below:
public boolean onJsConfirm(WebView view, String url, String message,
final android.webkit.JsResult result) {
new AlertDialog.Builder(currentActivity)
.setTitle("Confirmation")
.setMessage(message)
.setPositiveButton(android.R.string.yes,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.no,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.cancel();
}
}).setCancelable(false).create().show();
return true;
}
public boolean onJsAlert(WebView view, String url, String message,
final android.webkit.JsResult result) {
new AlertDialog.Builder(currentActivity)
.setTitle("Alert !")
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
final boolean remember = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
WebviewActivity.this);
builder.setTitle("Locations");
builder.setMessage(" Would like to use your Current Location")
.setCancelable(true)
.setPositiveButton("Allow",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
callback.invoke(origin, true, remember);
SharedPreferences pref = currentActivity
.getPreferences(currentActivity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref
.edit();
editor.putBoolean("isLocationAvailable",
true);
editor.commit();
webview.loadUrl(getUrl(gps.getLatitude(),
gps.getLongitude(), "true"));
}
})
.setNegativeButton("Don't Allow",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
callback.invoke(origin, false, remember);
webview.loadUrl(getUrl("", "", "false"));
}
});
AlertDialog alert = builder.create();
alert.show();

Complete solution Try this is a Generic Alert dialog with cutom tilte,message,yes,no button caption
1) Createa Interface
import android.content.DialogInterface;
public interface AlertMagnatic {
public abstract void PositiveMethod(DialogInterface dialog, int id);
public abstract void NegativeMethod(DialogInterface dialog, int id);
}
2) Generalize method for confirm dialog.
public static void getConfirmDialog(Context mContext,String title, String msg, String positiveBtnCaption, String negativeBtnCaption, boolean isCancelable, final AlertMagnatic target) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
int imageResource = android.R.drawable.ic_dialog_alert;
Drawable image = mContext.getResources().getDrawable(imageResource);
builder.setTitle(title).setMessage(msg).setIcon(image).setCancelable(false).setPositiveButton(positiveBtnCaption, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
target.PositiveMethod(dialog, id);
}
}).setNegativeButton(negativeBtnCaption, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
target.NegativeMethod(dialog, id);
}
});
AlertDialog alert = builder.create();
alert.setCancelable(isCancelable);
alert.show();
if (isCancelable) {
alert.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
target.NegativeMethod(null, 0);
}
});
}
}
3) How to use
getConfirmDialog(getString(R.string.logout), getString(R.string.logout_message), getString(R.string.yes), getString(R.string.no), false,
new AlertMagnatic() {
#Override
public void PositiveMethod(final DialogInterface dialog, final int id) {}
#Override
public void NegativeMethod(DialogInterface dialog, int id) {
}
});

Related

AlertDialog with EditText and Three buttons

So i have tis code and i'm trying to create a AlertDialog with an EditTet and Three buttons the positive one, the négative one and the neutral one , but it doesn't work and the application stops
b5.setOnClickListener(new View.OnClickListener() {
#SuppressLint("UseCompatLoadingForDrawables")
#Override
public void onClick(View view) {
AlertDialog.Builder boite;
boite = new AlertDialog.Builder(MainActivity.this);
boite.setTitle("boite de dialogue");
boite.setIcon(getDrawable(R.drawable.warning_shield_96px));
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
boite.setView(input);
boite.setPositiveButton("OUI", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//whatever action
}
});
boite.show();
boite.setNegativeButton("NON", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//whatever action
}
});
boite.show();
boite.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//whatever action
}
});
boite.show();
}
});
There is no need to call boite.show() several times, just call it once like below :
b5.setOnClickListener(new View.OnClickListener() {
#SuppressLint("UseCompatLoadingForDrawables")
#Override
public void onClick(View view) {
AlertDialog.Builder boite;
boite = new AlertDialog.Builder(MainActivity.this);
boite.setTitle("boite de dialogue");
boite.setIcon(getDrawable(R.drawable.warning_shield_96px));
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
boite.setView(input);
boite.setPositiveButton("OUI", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//whatever action
}
});
boite.setNegativeButton("NON", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//whatever action
}
});
boite.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//whatever action
}
});
boite.show();
}
});
AlertDialog uses Builder Pattern to initialize, so you can set different methods and buttons and anything you like, then when you call alertDialog.show() it builds the object with any configs you set before that call.

How to know the pressed button while opening AlertDialog?

i have this:
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(updatedActivity.this);
builder.setTitle("Choose the currency you would like to exchange.");
//list of items
String[] items = getResources().getStringArray(R.array.countries_array);
builder.setSingleChoiceItems(items, 0,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
String positiveText = getString(android.R.string.ok);
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//So here i wanna a code like : If pressbutton = buttonto, then buttonto.setText(selecteditem..)
}
});
String negativeText = getString(android.R.string.cancel);
builder.setNegativeButton(negativeText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}
In the on click event, i wanna know which the button was pressed, so for example if buttonto.ispressed then buttonto.settext(the selected item)
So how to do it
Thanks

Issues in onBackpressed()

Actually my issue is when i press the back button it shows a dialog and also at the same time the application finished without any operation on key? Can any one solve this?
#Override
public void onBackPressed() {
super.onBackPressed();
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Main.super.onBackPressed();
}
});
ab.create();
ab.show();
}
remove super.onBackPressed(); from method, keep it in onClick() only
#Override
public void onBackPressed() {
super.onBackPressed(); //remove it
}
seems you are performing same operation in both buttons, you should remove Main.super.onBackPressed() from negativeButton
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
super.onBackPressed();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ab.dismiss();
}
});
Don't call super method of onBackPressed.
#Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.create();
ab.show();
}
try this
#Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Main.super.onBackPressed();
}
});
ab.create();
ab.show();
}
You need to Remove, super.onBackPressed(); from onBackPressed(). then your function should as,
#Override
public void onBackPressed() {
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Really want to exit");
ab.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ab.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Main.super.onBackPressed();
}
});
ab.create();
ab.show();
}

how to test MultiChoiceItems android dialog box

I build an AlertDialog box with
public class ConstantDialogFragment extends DialogFragment {
private AlertDialog.Builder builder;
private AlertDialog alertDialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final int[] constantProtocol = {0};
builder = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
builder.setTitle(getResources().getString(R.string.some_message))
.setMultiChoiceItems(R.array.some_choice, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
// some method
}
})
.setPositiveButton(getResources().getString(R.string.ok_dialog), new DialogInterface.OnClickListener() {
class LoadConfigTask {
private ProgressDialog dialog;
private Activity activity;
public LoadConfigTask(Activity activity) {
this.activity = activity;
dialog = new ProgressDialog(activity, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
public void execute() {
try {
// some method
} catch (Exception e) {
// some method
}
}
}
#Override
public void onClick(DialogInterface dialog, int id) {
// some method
}
})
.setNegativeButton(getResources().getString(R.string.cancel_dialog), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// some thing
}
});
builder.create();
alertDialog = builder.show();
return alertDialog;
}
public AlertDialog getAlertDialog(){
return alertDialog;
}
Then I tried this espresso implementation:
onView(withText("my first choice")).
perform(click());
and I get
NoMatchingViewException: No views in hierarchy found matching: with text: is my string"
How can I fix that ?
Fetching in the Android source code, I found useful methods. So to get control on the items of the AlertDialog, I had to do that
ListView listView = alertDialog.getListView();
View child = listView.getChildAt(0);
child.performClick();

Inheriting classes from one main class

I am new in programming and i don't have much experience in inheritance. Now a days I am working in android development. This is my class code. I want to inherit all classes from this class. Only difference is inherited class should change AlertDialog message and dial number in call() method. Please tell me how to inherit this class to another what is the code should be?
public class PrepaidChineTown extends AppCompatActivity {
Button chinaButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prepaidchinatown);
chinaButton = (Button)findViewById(R.id.chinaTownBtn);
chinaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(PrepaidChineTown.this);
builder.setTitle("China Town Offer");
builder.setMessage("Are you sure you want to activate China Town Offer? Terms and condition apply");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
call();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public void call(){
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode("*2300#")));
try{
startActivity(in);
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Your Activity is not Found", Toast.LENGTH_LONG).show();
}
}
}
Create a Constant.class
private String number = "";
public class Constant {
public static void alertDialogShow(Context context,String title,String message,String _number)
{
this.number = _number;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//to do your stuff
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void call(){
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode(number)));
try{
startActivity(in);
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Your Activity is not Found", Toast.LENGTH_LONG).show();
}
}
}
And you can call this in any activity.
like this.
Constant.alertDialogShow(CurrentActivity.this,"Title","Message","*2300#");
public class PrepaidChineTown extends AppCompatActivity implements OnClickListener
{
Button chinaButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prepaidchinatown);
chinaButton = (Button)findViewById(R.id.chinaTownBtn);
chinaButton.setOnClickListener(this);
}
public void alertDialogue(String title,String message,Context context)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
call();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void call(){
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Uri.encode("*2300#")));
try{
startActivity(in);
}catch (ActivityNotFoundException e){
Toast.makeText(getApplicationContext(), "Your Activity is not Found", Toast.LENGTH_LONG).show();
}
}
Now Create object of PrepaidChineTown and call alertDialogue() by passing required parameters or by extending this class you can use that method to show dialogue

Categories

Resources