How We Can Change Selected Activity
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
public class ReallyEmptyActivity extends AppCompatActivity {
@Override
protected void onCreate(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));
} else if (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.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void uni1onclick(View view) {
SharedPreferences preferences = this.getSharedPreferences("UNIV",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UNIV","uni1");
editor.commit();
startActivity(new Intent(MainActivity.this,Uni1.class));
}
public void uni2onclick(View view) {
SharedPreferences preferences = this.getSharedPreferences("UNIV",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UNIV","uni2");
editor.commit();
startActivity(new Intent(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"