I have two activities named One_Activity and two_activity.
After allowing the user to make a selection I want to allow the app to decide which activity to display - even if we exit from the program and return.
For instance we should always launch two_activity as the default if we selected it.
How can I implement this?
To extend on JoelFernandes suggestion, which is a correct solution, your launch activity will need to check SharedPreferences as follows
public class MainActivity extends Activity {
public static final int MODE_LAUNCH_A = 0;
public static final int MODE_LAUNCH_B = 1;
public static final String PREF_LAUNCH_MODE = "PREF_LAUNCH_MODE";
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent target;
switch(prefs.getInteger(PREF_LAUNCH_MODE, 0)) {
case MODE_LAUNCH_A:
target = new Intent(this, AlphaActivity,class);
break;
case MODE_LAUNCH_B:
target = new Intent(this, BravoActivity,class);
break;
}
startActivity(target);
}
}
In the Activity where you select the Activity to use as the Main Activity you need to save the preference like follows:
private void saveSelection(int selection) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().setInteger(MainActivity.PREF_LAUNCH_MODE, selection).commit; //(or .apply() instead of commit)
}
// call the above method like
saveSelection(MainActivity.MODE_LAUNCH_A);
In the manifest you should also set NoHistory on MainActivity to stop it making a mess when you press the back button.
You can set a flag and save it in SharedPreferences. When you reopen the app, access the flag and depending on its value, you can show the desired activity as your main activity.
Related
I am trying to find best way to show textview we have clicked on first and second activity, in third one.
Like i have three activities AccountFrom, AccountTo and transferDetails.
I want to know that on what accounttype user has clicked so that i can show in third activity.
1. on AccountFrom Activity
Intent intent = new Intent(AccountFrom.this, AccountTo.class);
**intent.putExtra("accounttype","accountTypeVariable");**
startActivity(intent);
2. Receive intent on AccountTo Activity
Intent intent = getIntent();
if (intent != null)
{
String accountTypeValue = intent.getStringExtra("accounttype")
}
Consider using a view model.
You create the view model in the first Activity and then it is accessible in all activities that you open from it.
Here is simple workflow:
Create view model class that extends ViewModel and has the values you need to keep around
public class MyViewModel extends ViewModel {
private String value1 = "";
private boolean isValue2 = false;
// ...
}
In the first activity create your view model class member
private MyViewModel viewModel;
In the OnCreate you can get the view model like this:
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
You can do it also in the activities that are launched from this activity - they will share the same view model object. You can set the values in the activities and access them in other activities from the same 'launch-chain'.
When the initial activity (your first one) gets destroyed then the view model also does.
PS. using view model is also good when you need to handle screen orientation changes.
Save the text from TextView on sharedPreferences when it is clicked. Then read it on your third activity.
Call this on your first activity where the user chooses the account type.
void saveText(String stringFromTextView)
{
SharedPreferences sharedpreferences = getSharedPreferences("account", Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("account_type", stringFromTextView);
editor.commit();
}
And on your third activity, call this on onCreate() to get the account type.
String getAccountType()
{
SharedPreferences sharedpreferences = this.getSharedPreferences("account", Context.MODE_PRIVATE);
String accountType = sharedpreferences.getString("account_type", null);
return accountType;
}
I'm writing an app with 8 different Activities that are all interconnected(accessible from one another). I'm wondering how I can have the app always reopen from a full close (not just home button click but from closing the background activity) with the same screen it was exited from.
For example, from my Splash Screen I navigate to a home screen. From that home screen I navigate to the Settings. Now, I click the multi-tab viewer and close all apps. How can I have Settings(or wherever I had left off) become the launching activity when the app is reopened?
Thanks in advance!
You can use SharedPreferences to store the class name of the latest Activity. Later, when relaunch, you can redirect to it from the Splash Screen.
You can do that simply by using SharedPreferences. When you launch an activity, it changes it's last activity value in SharedPreferences to point at that activity.
When you close the app and then reopen it, your Main/Launcher activity (Which may be your Splash Screen) then checks for this value and launches the activity according to this value which represents the last activity the app was on.
Here is the code that would fit the Main/Launcher activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String lastActivity = getDefaults("LAST_ACTIVITY", MainActivity.this);
Intent intentLastActivity;
// use an if statement to find out which activity it is
if(!lastActivity.equals("") || !lastActivity.equals(null)){
if(lastActivity.equals("home")){
intentLastActivity = new Intent(MainActivity.this, HomeActivity.class);
}else if(lastActivity.equals("settings")){
intentLastActivity = new Intent(MainActivity.this, SettingsActivity.class);
// add more else-if statements for the other activities.
}
startActivity(intentLastActivity); // launch the last activity
finish(); // finish/close the current activity.
}
}
public static void setDefaults(String key, String value, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
Once that code is placed in your Main/Launcher activity. You can then set this last activity value in SharedPreferences in other activities when they are launched.
Code placed in the other activities (in the onCreate method):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// we are at the settings activity. Change last activity value to settings
MainActivity.setDefaults("LAST_ACTIVITY","settings",this);
}
Luckily the methods to change the last activity are accessible in other activities.
If you're able to implement this well in your app. It should work as you want it to.
HOPE THIS HELPS!
Ok, so the thing is that i'm trying to get my android application to have a settings activity for the user to be able to change some of the application's features (language, theme, ...). My problem comes when trying to get the app to react to the change on the value of one of those preferences. For instance the theme one; my idea would be to have a "Switch preference". When it would be on, the app's theme would be Material.Light and when off, Material. For this I though to have some "onValueChanged" method that would react when the switch changed its position. The problem here is that I'm unable to properly get an instance of the SwitchPreference in my SettingsActivity, both because the "findPreference(key)" method is deprecated and I don't really know how to make it take the value of the needed key.
There is any way to do this, or should I change the way of thinking for this problem?
Instead of setting the theme in onValue change listener, you can also do like below:
1) Create ThemeUtils class and do switch case for theme selection and set a theme for activity. I created own style, you can select your stlye name here
public class ThemeUtils {
public final static int THEME_Professional = 1;
public final static int THEME_Default = 2;
public static void onActivityCreateSetTheme(Activity activity, int sTheme) {
switch (sTheme)
{
default:
case THEME_Professional:
activity.setTheme(R.style.ProfessionalTheme);
break;
case THEME_Default:
activity.setTheme(R.style.DefaultTheme);
break;
}
}
}
2)In onCreate method of Activity, call setTheme method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme();
}
3)Gets user selected theme
private void setTheme() {
int themeInt = getThemeValue();
ThemeUtils.onActivityCreateSetTheme(this, themeInt);
}
4) After getting the style id, you can call ThemeUtils class method onActivityCreateSetTheme
private int getThemeValue() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext());
Boolean isGrid = pref.getBoolean(getString(R.string.grid_switch), false);
if (isGrid) {
return 2;
} else {
return 1;
}
}
Hope this option helps you !!!
Please read carefully because it is a little bit complicated!
I have a service that call many functions every 5 second. Now I want to call one specific fucntion in those functions just 1 time only. So I make this to check if that function has called before.
private void checkFirstLaunchApp() {
final String HAS_RUN_BEFORE = "hasRunBefore";
final String HAS_RUN = "hasRun";
SharedPreferences runCheck = getSharedPreferences(HAS_RUN_BEFORE, 0);
Boolean hasRun = runCheck.getBoolean(HAS_RUN, false);
if (!hasRun) {
SharedPreferences settings = getSharedPreferences(HAS_RUN_BEFORE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(HAS_RUN, true); //set to has run
edit.apply(); //apply
//do that function
functionIWant();
}
} else {
//do nothing
}
}
But the problem is if I close my app and reopen it,that function will not be called anymore. What I want is when I reopen my app, that function will be called 1 time again.Please show me how can I do that?
you have to reset HAS_RUN to false inside onStart() of your launcher activity.
Alternate
Extend Application class and create global variable:
public class MyApplication extends Application{
public boolean hasRun;
public void onCreate (){
hasRun=false;
}
}
Get instance of MyApplication
MyApplication app=(MyApplication)getApplication();
if(!app.hasRun){
app.hasRun=true;
// do your stuff
}
Handle it in the onResume method
Use global variable instead of SharedPreferences
A field variable is fine, sharedpreferences is not suitable for this case.
private boolean mIsCalled;
...
private void functionIWant() {
if (mIsCalled) return;
mIsCalled = ture;
// your function body
}
Set SharedPreference to false in onStop() method :
SharedPreferences settings = getSharedPreferences(HAS_RUN_BEFORE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(HAS_RUN, true); //set to has run
edit.apply(); //apply
Call your method in onResume() method :
checkFirstLaunchApp()
i'm saving the users login information to SharedPreferences, so he only has to configure his login data once.
This is my onBackPressed method in my Preferences.class (extends PreferenceActivity):
#Override
public void onBackPressed() {
//Login again
Intent intent = new Intent(Preferences.this, LoginActivity.class);
startActivity(intent);
}
What I need is a if-condition which checks, if the preferences changed or not.:
If the user opens the Preferences Activity (edit: from any View(!)), and does not change anything and clicks the backbutton -> just go back to last state.
If the preferences changed: call LoginActivity.
Couldnt find a solution yet and the LoginActivity gets called whenever i hit the backbutton.
Thanks in advance,
Marley
To determine if there was a change in SharedPreferences you have to assign a OnSharedPreferenceChangeListener to your SharedPreferences object like this:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
in this case I'm doing it in my Application class that's implementing:
public class YambaAppObj extends Application implements OnSharedPreferenceChangeListener
Then you will have to override:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
//this method will be called when preferences are changed.
//do here what you want to record the change
Log.d(TAG , "onSharedPreferenceChanged for:" + key);
}
and then you could check this record in your onBackPressed() method of your Preferences Activity and act accordingly.
You can use OnSharedPreferenceChangeListener or (depending on what you really meany by changed) you can try utilising onSharedPreferenceChanged() like:
protected Boolean mPrefsChanged = false;
#Override
public void onSharedPreferenceChanged( SharedPreferences sharedPreferences,
String key ) {
mPrefsChanged = true;
}
of course it's far from perfect, but at least you got more options