Using Android AlertDialog - android

I want to create a single class which I can call when I need to show an AlertDialog with the parameters and son on I want.
The problem is I dont know if that class have to be an Activity... the alertDialog needs an context, but I can send the current one, because what I want is to show the alert on the actual activity (not to create a new one, I want to show the alert on the actual screen). But I cant get it. I get errors sending the context of the actual activity...
Only I get working it when I create that class like an Activity, but with that, the alertDialog appears alone without the actual screen behind.
What Can I do? I don't know if I understand the contexts...
Thanks

Your class does not need to extend anything to produce a dialog. You can try this way to produce a static method that creates a dialog for you.
Make sure when you call your method you use THIS and not getApplicationContext()
MyDialogClass.getDialog(this); //good!
MyDialogClass.getDialog(getApplicationContext()); //results in error
That is likely the cause of your error
Example class:
public class MyDialogClass
{
public static AlertDialog getDialog(Context context)
{
Builder builder = new Builder(context);
builder.setTitle("Title").setMessage("Msg").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
}
});
return builder.create();
}
}

AynscTask does not need the Context; and no, it doesn't need to be an activity.
http://developer.android.com/reference/android/os/AsyncTask.html
Anyways, you should be able to get the context anytime with no problems. Just do this:
public class MyApplication extends Application{
private static Context context;
public void onCreate(){
super.onCreate();
context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
Then you can get the context from wherever you want with MyApplication.getAppContext(); and pass it on and it should work.

Related

How do I succeed in declaring variables globally, issue with context

I'm following tutorials on how to put functions that are used frequently in activities all in one place.
For example, a toast message that comes up throughout my project, instead of having the function in each and every activity, just having it called in one place, GlobalFunctions.java.
So, I get it with simple functions, for example, in GlobalFunctions.java :
public class GlobalFunctions {
public void simpleMessage() {
System.out.println("simpleMessage text goes here");
}
}
And the I call it like this from Activity1:
GlobalFunctions simplemessage = new GlobalFunctions();
simplemessage.simpleMessage();
But what about? :
public class GlobalFunctions {
public void simpleMessage() {
Toast.makeText(getApplicationContext(), "simpleMessage text goes here", Toast.LENGTH_LONG).show();
}
}
I've looked at several posts including getApplicationContext() error Android and no matter what I put in the Context part of Toast I get a Cannot resolve method message. Also if there's any good tutorials for Dummies on this subject I'd be grateful.
The key is static .
Static values allow you to use static methods variables ..etc in whole project.
You can use following concept:
public static class GlobalFunctions {
public static void simpleMessage(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
And you have to invoke it like:
GlobalFunctions.simpleMessage(/*YourActivity.this*/ /*or*/ /*getActivity()*/, "toast");
One solution would be to pass the Context as a parameter from the Activity or Fragment.
And instead of instantiating GlobalFunctions, writing and using static methods can be a better approach.
Create a Java Utils class:
public class Utils {
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
}
// for example on the Activity code
Utils.showToast(this, "This is the toast text");
Keeping context in field beyond activity can be reason of memory leak, but there is some workaround.
You can create Singleton with application or application context and initialize it in onCreate in your custom application class. But you have to remember that you can't use this context to build views - it is not stylized.
Other way is just pass context as argument.
Sorry for missing code, response from phone :)
try this Create class like this to pass Context and Toast message as parameter like this
public class GlobalFunctions {
public static void simpleMessage(Context context,String message) {
Toast.makeText(Context, message, Toast.LENGTH_LONG).show();
}
}
call this function like this
GlobalFunctions.simpleMessage(YourActivity.this,"your Mesaage");

How to display a dialog from a Library?

I'm writing a custom library, and I ran into a problem. I need to display a dialog to prompt a user to login one time. I can't seem to be able to display an AlertDialog from the Library. I get Unable to add window -- token is not for an application. I am getting the context of the application, by extending a custom library application class. This is the application class in the library:
public class MyCustomApplication extends Application {
private static MyCustomApplication instance;
/**
* Constructor.
*/
public MyCustomApplication () {
instance = this;
}
/**
* Gets the application context.
*
* #return the application context
*/
public static Context getContext() {
return instance;
}
And this is the code in the app that is using the library:
public class MyApplication extends MyCustomApplication {
#Override
public void onCreate(){
super.onCreate();
}
This is the code in the library that attempts to display a dialog:
public static void displayTerminatePopup(String title, String message){
int size = 14;
AlertDialog.Builder aboutBuilder = new AlertDialog.Builder(MyCustomApplication.getContext());
aboutBuilder
.setTitle(title)
.setMessage(message)
.setCancelable(false);
.setPositiveButton("Accept",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
final AlertDialog aboutAlert = aboutBuilder.create();
aboutAlert.show();
TextView textView = (TextView) aboutAlert.findViewById(android.R.id.message);
textView.setTextSize(size);
}
The 'MyCustomApplication.getContext() is where I'm 99% sure the hang up is. I also tried passing a Context directly to the library, and that didn't work, either. Any help on how to show a dialog to allow a user to login via a library would be much appreciated. I've been searching and searching and havn't been able to find anything.
Thanks!

Get current activity from Application.Context - MonoAndroid

I am currently developing an application using Xamarin.Forms that will be available on the Android and iOS platforms. When the application is first loaded on device, I check to see if there is an internet connection available on the device. I want to display a dialog box if an internet connection is not available.
Here is the following snippet of code I am using to check the internet on the Xamarin.Forms.ContentPage
if(App.Connectivity.IsNetworkConnectivityAvailable())
{
App.Notification.DisplayLocalNotifications("No Internet", "You need an internet connection to access certain application content");
}
I am using dependency injection to build the appropriate module for handling dialog boxes for each appropriate environment. The Android is throwing the following exception
Android.Views.WindowManagerBadTokenException: Unable to add window --
token null is not for an application Here is the code for the
DisplayLocalNotification method on the Android:
public void DisplayLocalNotification(string title, string content)
{
AlertDialog.Builder builder = new AlertDialog.Builder(Application.Context)
.SetTitle(title)
.SetMessage(content)
.SetCancelable(true)
.SetPositiveButton("OK", (EventHandler<DialogClickEventArgs>) null);
AlertDialog alert = builder.Create();
alert.Show();
var okBtn = alert.GetButton((int)DialogButtonType.Positive);
okBtn.Click += (sender, args) =>
{
alert.Dismiss();
};
}
After doing some research, I need to get pass the current activity to the AlertDialog.Builder constructor instead of the Application.Context. How do I get the current activity object from the application context when you need to the activity outside of the activity context?
Xamarin.Forms Android platform code should assign the current Activity into Forms.Context property. This is the static Forms class and if you debug it you will see that the Forms.Context is an Activity.
public static class Forms
{
public static Context Context { get; }
public static bool IsInitialized { get; }
public static event EventHandler<ViewInitializedEventArgs> ViewInitialized;
public static void Init(Activity activity, Bundle bundle);
}

Cant pass activity Context

Hello I'm trying to use object from one of my libaries, but I can't pass my corrent context.
The constructor is:
public AmbilWarnaDialog(final Context context, int color, OnAmbilWarnaListener listener)
And in my class I use this for the constructor:
AmbilWarnaDialog dialog = AmbilWarnaDialog(this, initialColor, new OnAmbilWarnaListener()
{
public void onOk(AmbilWarnaDialog dialog, int[] color) {
// color is the color selected by the user.
}
public void onCancel(AmbilWarnaDialog dialog) {
// cancel was selected by the user
}
});
I get this error:
The method AmbilWarnaDialog(Settings, int, new AmbilWarnaDialog.OnAmbilWarnaListener(){}) is undefined for the type Settings
I also tried getApplicationContex() and Settings.this and it's not working.
My imports are:
import yuku.ambilwarna.AmbilWarnaDialog;
import yuku.ambilwarna.AmbilWarnaKotak;
import yuku.ambilwarna.AmbilWarnaDialog.OnAmbilWarnaListener;
You cannot call a constructor directly, to instantiate a class use the new keyword like this:
AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, initialColor, new OnAmbilWarnaListener() { ...
Try this:
Context context;
private methodName(Context context) {
this.context = context;
}
call method in Activity:
methodName(this);
You are calling this method somewhere inside the Settings class (I am assuming Settings doesn't extend Context). You might be doing something like this:
public class MyClass extends Context {
public myMethod(){
new Settings(){
// the keyword this references to the Settings object instance, not MyClass object instance
// to reference Context use MyClass.this
// like Henry says below, make sure you use the new keyword to initialize objects
AmbilWarnaDialog dialog = new AmbilWarnaDialog(MyClass.this, initialColor, new OnAmbilWarnaListener() {...}
}
}
}

Creating AlertDialog with Static Methods?

I've completed most of the game I'm attempting to make and throughout the project I've created one particular Activity which also calls a SurfaceView and a Thread. I put an update() method in each of the 3 classes so they each know where the other ones are everytime something changes. Apparently, the only way to do something like this is using static methods... This is fine until a collision occurs in my SurfaceView and I want to tell the Activity what to do. I can relay the information, but then I cannot find a way to make an AlertDialog.
I understand I cannot call showDialog() from a Static method, but I cannot find a way to make a non-static method to call it with and then call that method from a static one. I've been searching for an answer and I've heard something about instantiating the object but I cannot figure out what that means...
If anyone has a good idea to get me around this, please let me know :)
Here is what I used:
public static void messageDialog(Activity a, String title, String message){
AlertDialog.Builder dialog = new AlertDialog.Builder(a);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setNeutralButton("OK", null);
dialog.create().show();
}
SurfaceView extends View and thus have a getContext() method
To create and show your AlertDialog, you can do the following code inside your SurfaceView
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("title");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog d = builder.create();
d.show();
This might not work as Activity.showDialog(int) if your activity is restarted (the dialog might simply disappear and you will have to handle state yourself).
Hope this helps

Categories

Resources