Why is dialog.show() causing my app to crash? - java

I've been trying to get a dialog message to work on android and the app always crash when it reaches "dialog.show();"
public class Logic extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.setTitle("Alarm");
dialogBuilder.setMessage(messageActivity.getMes());
dialogBuilder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
}
Here is my logcat:
FATAL EXCEPTION: main
Process: it226.myapplicationit226androidapp, PID: 19598
java.lang.RuntimeException: Unable to start receiver it226.myapplicationit226androidapp.Logic: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2732)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at it226.myapplicationit226androidapp.Logic.onReceive(Logic.java:65)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2725)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)

You can't create dialog from receiver.
Creating dialogs is allowed only from UI components (which have looper).
You could start transparent activity with dialog, which would be the same for user.

You can't create a dialog using the context of a BroadcastReceiver, you has two options to solve this problem:
first one is to create a regular Activity which has only the size of the dialog as a shown part and the full remaining is transparent:
Intent newIntent = new Intent(context, Displayer.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
second one is to hold your Activity context and then use it in creating the dialog, but at this method you have to make sure what is the activity that is currently open:
// in your activity onCreate
ctx = YourActivity.this; // let's suppose ctx is static and general var
////////////////////////////////////////////////
// in the BroadcastReceiver
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(YourActivity.ctx);

Related

Hi! I am new to android app development. I tried to create a simple counter but after build getting error "Unable to instantiate activity"

public abstract class MainActivity extends AppCompatActivity {
Button decrement;
Button increment;
TextView counter_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Log.i("tag", "onCreate: Created Successfully");
increment=findViewById(R.id.inc_btn);
decrement=findViewById(R.id.dec_btn);
counter_view=findViewById(R.id.counter);
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cnt_text=counter_view.getText().toString();
int cnt_no= Integer.parseInt(cnt_text);
cnt_no=cnt_no+1;
counter_view.setText(cnt_no+"");
}
});
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String cnt_text=counter_view.getText().toString();
int cnt_no=Integer.parseInt(cnt_text);
cnt_no=cnt_no-1;
counter_view.setText(cnt_no+"");
}
});
}
Error:
2021-02-10 00:29:06.870 16714-16714/? E/Zygote: v2
2021-02-10 00:29:06.871 16714-16714/? E/Zygote: accessInfo : 0
2021-02-10 00:29:07.017 16714-16714/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.counter_app, PID: 16714
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.counter_app/com.example.counter_app.MainActivity}: java.lang.InstantiationException: java.lang.Class<com.example.counter_app.MainActivity> cannot be instantiated
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2849)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.counter_app.MainActivity> cannot be instantiated
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1086)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2839)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 
I suppose this is your first screen/activity/class that is displayed on launch i.e it is your launcher activity. If yes,
the launcher activity cannot be abstract. Because when an app is launched from the home screen on an Android device, the Android OS creates an instance of the activity in the application you have declared to be the launcher activity. And abstract classes can not be instantiated, they can only be sub-classed.
Please remove the word abstract before your class name.
add to your manifest file this line
<activity android:name="your.package.name.MainActivity"/>

I cant use alertdialog builder in android activity and has runtime error

when the app wants to use this and click the button the run time error occurs and I dont know how to fic this , and this code used in fragment and now I nedd to use this in activity and I think its the problem
post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkPermissionREAD_EXTERNAL_STORAGE(this);
CharSequence items[] = {"گرفتن تصویر از دوربین","گرفتن ویدیو از دوربین",
"انتخاب تصویر از گالری","انتخاب ویدیو از گالری"};
AlertDialog.Builder ab = new AlertDialog.Builder(NewPost.this);
ab.setTitle("انتخاب از :");
ab.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
switch (position)
{
case 0 :
take_pic_from_camera();
break;
case 1 :
take_video_from_camera();
break;
case 2 :
pick_pic_from_gallery();
break;
case 3 :
pick_video_from_gallery();
break;
}
}
});
ab.create().show();
}
});
and my error is :
09-18 07:33:07.618 8846-8846/com.irprogram.ted E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.irprogram.ted, PID: 8846
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:190)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2094)
at android.content.res.Resources.getLayout(Resources.java:1111)
at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:880)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:857)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:899)
at com.irprogram.ted.NewPost$2.onClick(NewPost.java:165)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
You called setItems method before showing it. Just try to make a change in your code so that you call ab.create().show(); before ab.setItems().
The exception may be because it can't set the OnClickListeneter before making it visible in the activity.
Hope it helps.

WindowLeaked issue

I am having a big problem with WindowLeaked:
E/WindowManager: android.view.WindowLeaked: Activity CrearGrupo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3702bf39 V.E..... R....... 0,0-960,883} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at es.uva.tel.gco.CrearGrupo$2.onClick(CrearGrupo.java:175)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here the code:
final Dialog dialog2 = new Dialog(activity, R.style.dialog);
tituloDialogo=res.getString(R.string.crearGrupoDiálogo);
dialog2.setTitle(tituloDialogo +" "+listaAsignaturas.get(pos));
dialog2.setContentView(R.layout.prefijo_grupo);
if (control == 0){
//listNotebooks(pos);
Intent intent=new Intent(getApplicationContext(),MostrarCrearGrupos.class);
intent.putExtra("asignatura",listaAsignaturas.get(pos));
intent.putExtra("prefijo",prefGrupo.getText().toString());
intent.putExtra("nombreLibreta",notebookName);
startActivity(intent);
}
}
});
dialog2.show();
Dialog is a normal window with 2 inputs that let you enter one name and 1 prefix but when I try to show another dialog the app crash.
I already look for a solution and try to solve it with:
#Override
public void onDestroy() {
super.onDestroy();
if (dialog2 != null) {
dialog2.dismiss();
dialog2 = null;
}
}
#Override
protected void onPause(){
super.onPause();
if (dialog2 != null) {
dialog2.dismiss();
dialog2 = null;
}
}
#Override
protected void onStop(){
super.onStop();
if (dialog2 != null) {
dialog2.dismiss();
dialog2 = null;
}
}
But it doesnt work. Any ideas.
Thx for your answers. :)
In you case, you are try to call dialog2.show() after starting the new activity. Remove that and your code will work.
Here is the main reason why Leaked windows error occurs:
We know that every Activity Android has an WindowManager window manager, likewise, is built on top of a Activity dialog box, PopupWindow also has the corresponding WindowManager window manager. Because the dialog box, the PopupWindown from the Activity and should not exist alone, So when a Dialog or a PopupWindow is displayed when we go to finish () carrying the Dialog (or PopupWindow) Activity, Window Leaked exception will be thrown., Because the Dialog (or PopupWindow) WindowManager have who can not affiliated., So the window manager it has leaked.
Android.view.WindowLeaked usually occur in the display of Activity and Dialog.
Create Activity in a Dialog, and if you turn off Dialog first and then close the Activity is normal, if you shut down the Activity first and then close the Dialog will error the error android.view.WindowLeaked.
Analysis the reason is: Dialog is created based on Activity: new ProgressDialog (this); this is Activity. Activtity finish first, then Dialog will have no attachment, so will report android.view.WindowLeaked.

RuntimeException on populating Action bar to sub activities [duplicate]

This question already has answers here:
getActionBar() returns null
(25 answers)
Closed 6 years ago.
Iam new to android/coding/Java, please go easy on me if mistakes
Iam trying to reproduce same Action bar for the sub activities of my Main Activity (LoginActivity)
here is my LoginActivity
public class LoginActivity extends AppCompatActivity {
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
actionBar = getActionBar();// ActionBar Customisations
actionBar.setTitle("Klok Innovations");
actionBar.setLogo(R.drawable.collection_report);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
The app crashes when i open it ... Here is the logcat
07-04 17:24:15.005 7636-7636/online.klok.mobpos E/AndroidRuntime: FATAL EXCEPTION: main
Process: online.klok.mobpos, PID: 7636
Theme: themes:{}
java.lang.RuntimeException: Unable to start activity ComponentInfo{online.klok.mobpos/online.klok.mobpos.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at online.klok.mobpos.LoginActivity.onCreate(LoginActivity.java:28)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2510) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5461) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Also how can I create bar at the bottom of the screen and appear in all my sub activities?
this is why because your actionbar getting null pointer exeption:
try like this
assert actionbar != null;
if(actionbar != null){
**write your code here**
}
now its never be null..
you are using appCompateActivity so use getSupportActionBar. add this lines in your every subActivity in onCreate method.
assert getSupportActionBar() != null;
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Your Title Here");
that commented line is for back button at upper left corner.. if you want it then uncomment it. and write some line in manifest to do some back button action.
<activity android:name=".yourSubActivityName">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".whichActivityYouWantToGo" />
</activity>
if you are in mainActivity and want to exit app using dialog.. here is the code.
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
// Create the AlertDialog object and return it
builder.create();
builder.show();
}
Use
getSupportActionBar();
instead of
getActionBar();

Adding a class to the manifest in Android

I ran into this problem just now, scratching my head on how to tackle this problem.
Basically, I have MainActivity, and a lot of classes in my app, such as RootUtils, LegalProsecution, CameraSilencer, etc, etc. MainActivity is the only activity in this app, and the rest is just classes for executing code, showing dialogs, etc.
The particular class I have problem with is LegalProsecution.java, which is responsible for opening a dialog on first launch and show the users legal stuff. However, the stack trace points to line 48, which is simply dialog.show();
Here is the full stack trace:
05-01 19:01:08.075 21777-21777/ideaman924.camerasilencer E/AndroidRuntime: FATAL EXCEPTION: main
Process: ideaman924.camerasilencer, PID: 21777
Theme: themes:{}
java.lang.RuntimeException: Unable to start activity ComponentInfo{ideaman924.camerasilencer/ideaman924.camerasilencer.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:340)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:309)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:273)
at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:80)
at android.support.v7.app.AlertController.installContent(AlertController.java:214)
at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:256)
at android.app.Dialog.dispatchOnCreate(Dialog.java:394)
at android.app.Dialog.show(Dialog.java:295)
at ideaman924.camerasilencer.LegalProsecution.warningShow(LegalProsecution.java:48)
at ideaman924.camerasilencer.MainActivity.onCreate(MainActivity.java:20)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1347) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5458) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Anybody know what's the problem? Thanks.
EDIT: Here is LegalProsecution.java, which handles dialog creation:
package ideaman924.camerasilencer;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
public class LegalProsecution {
Context context = MyApp.getContext();
AppPreference appprefs = AppPreference.getInstance(context);
public void warningShow()
{
if(appprefs.loadSettings() == 1);
else
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MyApp.getContext());
builder1.setTitle(context.getResources().getString(R.string.warning));
builder1.setMessage(context.getResources().getString(R.string.warning_description));
builder1.setCancelable(true);
builder1.setPositiveButton(
context.getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Got promise from user, now setting first_run to 1
appprefs.storeSettings(1);
dialog.cancel();
}
}
);
builder1.setNegativeButton(
context.getResources().getString(R.string.no),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Okay, cool, bye! No CS for you!
dialog.cancel();
((Activity)context).finish();
System.exit(0);
}
}
);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
}
And here is MyApp.java, which I used as a workaround to solve the stupid context issue:
package ideaman924.camerasilencer;
import android.app.Application;
import android.content.Context;
public class MyApp extends Application
{
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance.getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Don't use
MyApp.getContext();
Create a constructor, and assign a context like
public LegalProsecution(Context context){
this.context = context;
}
Then when you create an instance, Create like this
LegalProsecution lp = new LegalProsecution(MyActivity.this);
Then don't forget to create alert dialog using the context you just assigned to
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
I think the activity you are trying to apply the dialog theme to is extending ActionBarActivity. Try to extends AppCompat instead.
Verify that your app theme is set to AppCompat android:theme="#style/Theme.AppCompat.light
cause Dialog require it.
If that's true, this is probably due to the inheritance of your main class wich set the theme to an other one.

Categories

Resources