Skip to content Skip to sidebar Skip to footer

How We Can Change Selected Activity

The app is a University APP, My application contains two buttons in mainactivity(calicutuniversity and mguniversity ), if we click on a button then it goes to the corresponding ac

Solution 1:

Add an Activity before your MainActivty.java that will check the SharedPreferences to load to the activity you want. I added an activity called ReallyEmptyActivity

here's the ReallyEmptyActivity.java

publicclassReallyEmptyActivityextendsAppCompatActivity {

    @Override
    protectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_really_empty);

        SharedPreferences preferences = this.getSharedPreferences("UNIV", MODE_PRIVATE);

        String uni = preferences.getString("UNIV", "0");
        Log.d("LOAD", uni);

        if (uni.equals("0")) {
            startActivity(new Intent(ReallyEmptyActivity.this, MainActivity.class));
        } elseif (uni.equals("uni1")) {
            startActivity(new Intent(ReallyEmptyActivity.this, Uni1.class));
        } else {
            startActivity(new Intent(ReallyEmptyActivity.this, Uni2.class));
        }

        finish();

    }
}

This will act as your director to the specific activity as upon the user. Your mainactivity.java will be the main screen where the user selects the university.

publicclassMainActivityextendsAppCompatActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    publicvoiduni1onclick(View view) {
        SharedPreferencespreferences=this.getSharedPreferences("UNIV",MODE_PRIVATE);
        SharedPreferences.Editoreditor= preferences.edit();

        editor.putString("UNIV","uni1");
        editor.commit();
        startActivity(newIntent(MainActivity.this,Uni1.class));
    }

    publicvoiduni2onclick(View view) {

        SharedPreferencespreferences=this.getSharedPreferences("UNIV",MODE_PRIVATE);
        SharedPreferences.Editoreditor= preferences.edit();
        editor.putString("UNIV","uni2");
        editor.commit();

        startActivity(newIntent(MainActivity.this,Uni1.class));
    }
}

when the user clicks the back button it'll take him back to the MainActivty where they can select the University again and when the app is re-run, the corresponding activity will be shown as the SharedPreference is getting overwritten.

Solution 2:

When the user is opening the app for the first time check the value of the Shared Preferences and it should take the default value if it does then open the MainActivity.

Else go to that particular activity.

And whenever the user chooses something from the MainActivity then just edit the contents of the Shared Preferences.

Post a Comment for "How We Can Change Selected Activity"