Android : application crashes with BadTokenException Error (trying to show AlertDialog) - java

I simply want to print an alert on the screen if there is no connection.
Here is what I did in my class that extends Activity.
if(isOnline()) {
// do stuff..
} else {
Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("No connection.");
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
Then I tried to launch it with Debug, and got the following error :
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

use
Builder builder = new AlertDialog.Builder(Your_Current_Activity.this);
instead of
Builder builder = new AlertDialog.Builder(getApplicationContext());
because you will need to pass Current Activity Context to show AlertDialog instead of Application Context

Replace the line
Builder builder = new AlertDialog.Builder(getApplicationContext());
with
Builder builder = new AlertDialog.Builder(YourActivityName.this);
Since you may need an Activity Context instead of Application Context.
Hope it helps.

try to use classname.this other than getApplicationContext() this some time cause issues
if(isOnline()) {
// do stuff..
} else {
Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("No connection.");
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}

Use yourActivityName.this instead of getApplicationContext();

Related

I get Unresolved reference: dismiss when i try to dismiss the alert dialog android

When i try to call dismiss() on my messageBoxBuilder but i get Unresolved reference: dismiss , i tried to call it on messageBoxView and to change setCancelable() to true but same thing happened.
fun create_Alert_Dialog(){
//Alert dialog builder
val messageBoxView = LayoutInflater.from(this).inflate(R.layout.layout_dialog,null)
//Alert dialog builder
val messageBoxBuilder = AlertDialog.Builder(this).setView(messageBoxView)
//Setting undissmissable
messageBoxBuilder.setCancelable(false)
//Show
messageBoxBuilder.create().show()
bt4 = messageBoxView.findViewById(R.id.bt4)
bt4.setOnClickListener {
Lose()
messageBoxBuilder.dismiss()
}
}
Try to rewrite your code like this
fun create_Alert_Dialog(){
//Alert dialog builder
val messageBoxView = LayoutInflater.from(this).inflate(R.layout.layout_dialog,null)
//Alert dialog builder
val messageBoxBuilder = AlertDialog.Builder(this)
.setView(messageBoxView)
//Setting undissmissable
.setCancelable(false)
//Show
.create().apply {
messageBoxView.findViewById(R.id.bt4).setOnClickListener {
Lose()
this.dismiss()
}
show()
}
}

How to fix 'Calling startActivity() from outside of an Activity context requires ...' error in java

I trie to open CustomTabsIntent from a Card i tried doing from an intent but i have the next error
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
This is the code of my app:
I expected to open a customtabinetnt with the url from de url, but th actual output is error
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
I changed the code for this:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.addDefaultShareMenuItem();
builder.setToolbarColor((R.color.colorPrimary));
builder.setShowTitle(true);
CustomTabsIntent customTabsIntent = builder.build();
CustomTabsHelper.addKeepAliveExtra(v.getContext(), customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
CustomTabsHelper.openCustomTab(v.getContext(),customTabsIntent,Uri.parse(url),new WebViewFallback());
}
} );
This is the correct code for made running the CustomTabsIntent from a viewholder.itemview

How to create a Shortcut on the Home Screen in Android 8?

I will create shortcut on Home screen in android 8 and used ShortcutManager it's creating shortcut in Context Menu and user should manually drag shortcut on Home Screen while in lower Android 8 automatically created on Home Screen
my code is:
ShortcutManager sM = (ShortcutManager) getSystemService(SHORTCUT_SERVICE);
Intent intent1 = new Intent(getApplicationContext(), MasterActivity.class);
intent1.setAction(Intent.ACTION_VIEW);
ShortcutInfo shortcut1 = new ShortcutInfo.Builder(this, "shortcut1")
.setIntent(intent1)
.setLongLabel("Ayande")
.setShortLabel("This is the Ayandeh")
.setDisabledMessage("Login to open this")
.setIcon(Icon.createWithResource(this, R.drawable.ayandeh))
.build();
sM.addDynamicShortcuts(Arrays.asList(shortcut1));
result:
but result I want create shortcut Automatically:
Figured it out. Use ShortcutManager.requestPinShortcut. But be aware that that method will open a dialog asking the user whether to add the shortcut to the home screen or not. Unfortunately for me this dialog was opening behind other activities, and so was never visible!
You Can Use This Method
private void createShortcut() {
ShortcutManager shortcutManager = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
shortcutManager = mContext.getSystemService(ShortcutManager.class);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (shortcutManager != null) {
if (shortcutManager.isRequestPinShortcutSupported()) {
ShortcutInfo shortcut = new ShortcutInfo.Builder(mContext, uniqueid)
.setShortLabel("Demo")
.setLongLabel("Open the Android Document")
.setIcon(Icon.createWithResource(mContext, R.drawable.andi))
.setIntent(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://stackoverflow.com")))
.build();
shortcutManager.requestPinShortcut(shortcut, null);
} else
Toast.makeText(mContext, "Pinned shortcuts are not supported!", Toast.LENGTH_SHORT).show();
}
}
}

app crashes when create alertDialog with a null context

I'm a new android developer, suffering from a problem recently.
The background is that i need to show an AlertDialog when a back-end asyncTask finished. However the activity may be GC'd after a long time asyncTask, so that the context tobe input param of AlertDialog is null.Is there any workaround to solve this problem.
I use this function to show dialog:
public static Dialog showDialog(
Context ctx, int themeId, String title, String message,
int okStrId, android.content.DialogInterface.OnClickListener okListener,
int cancelStrId, android.content.DialogInterface.OnClickListener cancelListener) {
if (ctx != null) {
AlertDialog.Builder builder;
if (themeId > 0)
builder = new AlertDialog.Builder(new ContextThemeWrapper(ctx, themeId));
else
builder = new AlertDialog.Builder(ctx);
if (title != null)
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(ctx.getString((okStrId < 0) ? R.string.ok : okStrId),
(okListener != null) ? okListener : sDefaultDialogListener);
if (cancelListener != null)
builder.setNegativeButton(ctx.getString((cancelStrId < 0) ? R.string.cancel : cancelStrId), cancelListener);
else {
builder.setCancelable(false);
}
AlertDialog ad = builder.create();
ad.show();
return ad;
}else {
Context context = SuccessFactorsApp.getAppContext();
DialogActivity.launchActivity(ctx,themeId,title,message,okStrId,okListener,cancelStrId,cancelListener);
return new AlertDialog.Builder(context).create();
}
}
I tried to use an Activity to simulate the dialog but not sure how to deal with the DialogInterface.OnClickListener.
Add this to your code:
if(!((Activity) context).isFinishing())
{
//show dialog
}
While running asyntask and doing background activity gets killed and Garbage collected..Hence on completion of task you cannot show a dialog without activity.You can try either
1.By adding below permission showing your dialog .Add this permission to manifest
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
And while showing dialog add this line of code before dialog.show()
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
2.On finsihing of the task launch the wanted activity and open application
3.Use Toast instead of dialog.

AlertDialog is giving an "undefined" error

My code is:
View.OnClickListener menuHandle = new View.OnClickListener() {
public void onClick(View v) {
//inflate menu
final String [] items = new String[] {"Rate This App", "Quit"};
final Integer[] icons = new Integer[] {R.drawable.star, R.drawable.quit};
ListAdapter adapter = new ArrayAdapterWithIcon(MainActivity.this, items, icons);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item ) {
//Toast.makeText(MainActivity.this, "Item Selected: " + item, Toast.LENGTH_SHORT).show();
switch (item) {
case 0:
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent.setData(Uri.parse("market://details?id=com.test.testing"));
if (MyStartActivity(intent) == false) {
//Market (Google play) app seems not installed, let's try to open a web browser
intent.setData(Uri.parse("https://play.google.com/store/apps/details?com.test.testing"));
if (MyStartActivity(intent) == false) {
//Well if this also fails, we have run out of options, inform the user.
//let the user know nothing was successful
}
}
break;
case 1:
finish();
break;
default:
//do nothing
}
}
});
AlertDialog alert = builder.create();
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alert.getWindow().setGravity(Gravity.BOTTOM);
alert.show();
}
};
I get the following error:
The constructor AlertDialog.Builder(MainActivity, int) is undefined
What do I have to modify to get rid of the error?
Note: My MainActivity class extends Activity and DialogSlideAnim as been initialized in the res/values/styles.xml file
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim) will work only on API level 11 and above.
If you are targeting all the platforms then use following.
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim))
try
new AlertDialog.Builder(v.getContext(), R.style.DialogSlideAnim)
instead of
new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim)
I think its because the AlertDialog.Builder is inside a inner class(menuHandle.setOnClickListener), try changing to: new AlertDialog.Builder(TheNameOfYourClass.this,R.style.DialogSlideAnim);
Like this way :
public void onClick(View v) {
new AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.DialogSlideAnim);
^^^
....
}
Try to set the Style in your AlertDialog as below:
new AlertDialog.Builder(
new ContextThemeWrapper(MainActivity.this, R.style.DialogSlideAnim)

Categories

Resources