Search code examples
androidandroid-activitysharedpreferencesactivity-finish

How i check whether to start an activity or not. android


I'm new to Android. My MainActivity is a Login activity. I want to check if a user is logged in, then starting the activity again should not show MainActivity, it should directly display the Dashboard Activity. I'm checking the login on the basis of value stored in the shared preferences.

sharedPreferences = this.getSharedPreferences("LoginDetail", Context.MODE_PRIVATE);
    String id = sharedPreferences.getString("userId","");
    if(!id.equalsIgnoreCase("") && id.length() > 5)
    {
        Intent i = new Intent(MainActivity.this, StudentSignin.class);
        startActivity(i);
        MainActivity.this.finish();
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

I'm Trying to do something like that in onCreate Method. If user is not logged in he/she must login to continue; Thanks in advance.


Solution

  • Set a splash screen to your app, make it the launcher activity, and decide there which activity should be shown.

    public class Splash extends AppCompatActivity{
    
        public void onCreate...{
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_splash);
            sharedPreferences = this.getSharedPreferences("LoginDetail", Context.MODE_PRIVATE);
            String id = sharedPreferences.getString("userId","");
            if(userLogged(){
                //Go to dashboard
            }else{
                //Go to login screen
            }
        }
    
    
    
    }