app crashes when create alertDialog with a null context - java

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.

Related

AdMob ads not showing from a function

I have made an android app using Android Studio and I have implemented Google AdMob into it.
However, when it comes to showing ads, whenever I try to show it from a function, it does not show.
Here is the function:
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.jodastudios.universalskyremote", Context.MODE_PRIVATE);
int clicks = sharedPreferences.getInt("clicks", 0);
sharedPreferences.edit().putInt("clicks", 0);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
Whenever I show the ads on the OnCreate method, they show.
Here is the code:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.jodastudios.universalskyremote", Context.MODE_PRIVATE);
int clicks = sharedPreferences.getInt("clicks", 0);
sharedPreferences.edit().putInt("clicks", 0);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
},9000);
I don't know why the ads are not showing from a function: does anybody know how to fix this?
Second code is delayed for 9 sec and that's enough time for the ad to load.
Function cannot display ad that has not been loaded!
You have to set AdListener and show add from onAdLoaded method or create callback to show from activity...
...or call your function from onAdLoaded(){
InterstitialAd interstitialAd = new InterstitialAd(context);
interstitialAd.setAdUnitId(adIdent);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
interstitialAd.show();
//TODO or create callback to show from activity
if (adCallback != null) {
adCallback.onAdLoaded();
}
}
.....................
.....................
}
and
interstitialAd.loadAd(new AdRequest.Builder().build());

Click "Exit" button of Google Navigation notification from my application

I want to "click" the "Exit Navigation" button that appear in the Google Navigation notification from my android application code.
Google Navigation notification:
I know that there is a way to do it because I can do it using a Tasker task, but I don't know how to do it using code from my application.
I have a NotificationListenerService and I can retrieve the text of the notification when onNotificationPosted is received with the following code:
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification notification = sbn.getNotification();
if (!pack.equals("com.google.android.apps.maps")) return;
RemoteViews views = notification.bigContentView;
if (views == null) views = notification.contentView;
if (views == null) return null;
int viewid=0;
List<String> text = new ArrayList<String>();
try
{
Field fieldActions = views.getClass().getDeclaredField("mActions");
fieldActions.setAccessible(true);
#SuppressWarnings("unchecked")
ArrayList<Parcelable> actions = (ArrayList<Parcelable>) fieldActions.get(views);
for (Parcelable p : actions)
{
Parcel parcel = Parcel.obtain();
p.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
int tag = parcel.readInt();
if (tag != 2) continue;
viewid=parcel.readInt();
String methodName = parcel.readString();
if (methodName == null) continue;
else{
if (methodName.equals("setText"))
{
parcel.readInt();
String t = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel).toString().trim();
text.add(t);
Log.w(TAG,"viewID: "+viewid+"setText: "+t);
}
}
parcel.recycle();
}
} catch (Exception e)
{
Log.e(TAG, e.toString());
}
return text;
}
But I didn't find a way to retrieve the actions ("buttons") of the notification.
Thanks!
It's quite simple. Just get the Action Buttons from that notification like this.
Notification notification = sbn.getNotification();
Notification.Action[] actions = notification.actions;
And because this notification has only one action button, you simply do:
actions[0].actionIntent.send();
AFTER you checked that's a Google Maps notification. You did this here:
if (!pack.equals("com.google.android.apps.maps")) return;
So complete code should look like this:
Notification notification = sbn.getNotification();
Notification.Action[] actions = notification.actions;
if (!pack.equals("com.google.android.apps.maps")) return;
actions[0].actionIntent.send();
Should work. Hope I can help you :)

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();
}
}
}

How to stop progressbar spinning after connection has been lost in Android

When I pressed back button on the mobile phone after that I switch off the wifi or mobile data network.
Progress bar spinning does not get stop and back button does not work.
protected void onRefreshingStateChanged(boolean refreshing) {
super.onRefreshingStateChanged(refreshing);
if (!refreshing){
if (mProgressDialog != null && isBackPressed){
mProgressDialog.hide();
mProgressDialog = null;
this.setResult(RESULT_OK, getIntent());
finish();
}
}else{
if (mProgressDialog == null && isBackPressed){
mProgressDialog = ProgressDialog.show(this, "Fetching Data",
"Please wait while we are updating records ...", true);
}
}
}
try to set cancelable property of progressbar.
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setCancelable(true);

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

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();

Categories

Resources