javaandroiddialoglaunchandroid-application-class

How to display custom dialog on application launch?


Sometimes I want to display a dialog when the app launches. For that purpose I created a custom dialog named LoginDialog and I am using an Application class java. However, I am having trouble showing this dialog. For one I cannot call getsupportfragmentmanager() or anything alike. Plus, the code replies that loginDialog has no show method which I thought was a standard operation of the AppCompatDialogFragment class. Any tips on how to solve this problem are appreciated!

The code:

public class ApplicationClass extends Application {
    
@Override
    public void onCreate() {
        super.onCreate();

        SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
        SharedPreferences.Editor sEditor = sharedPreferences.edit();
        if (sharedPreferences.getInt("EmailVer", 0) == 5) {
            showDialog();
        }
        Log.i("Abertura", "onCreate fired");
    }
    private void showDialog() {
        LoginDialog loginDialog = new LoginDialog();
        loginDialog.show(get);
    }
}

Solution

  • Maybe try to show a dialog in the Activity class? You can load SharedPreferences and check if You want to show a dialog in the Application class but show a dialog in Activity. It will look like this:

    ApplicationClass:

    import android.app.Application;
    import android.util.Log;
    
    public class ApplicationClass extends Application
    {
        private boolean showDialog;
    
        public boolean getShowDialog()
        {
            return showDialog;
        }
    
        @Override
        public void onCreate()
        {
            super.onCreate();
            Log.i("MyTag", "onCreate Application");
    
            // check if You want dialog. Main logic here
            showDialog = true;
        }
    }
    

    MainActivity:

    import android.app.AlertDialog;
    import android.os.Bundle;
    import android.util.Log;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity
    {
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            if (((ApplicationClass) getApplication()).getShowDialog()) //get application and show dialog if `showDialog` is true
            {
                Log.i("MyTag", "Show dialog");
                new AlertDialog.Builder(this)
                        .setTitle("Title")
                        .setMessage("Message")
                        .show();
            }
            else
            {
                Log.i("MyTag", "Do not show dialog");
            }
        }
    }