I have a blank-ish Android Project and what I want to do is take the user to a different "page/screen" if it is their first time only.
I know the logic for this but since I'm new to Android, I'm unsure of how to code this.
Below are the steps I believe I need to take in order to accomplish this:
App loads. If Local storage contains setting "FirstTimeUser", then it is not their first time using the app. Show the MainActivity page. If FirstTimeUser setting does not exist, it is their first time using the app (or they have uninstalled and reinstalled it), so instead, show WelcomeActivity page.
After viewing Welcome activity page, create FirstTimeUser setting and set to False.
But how do I code this for an Android app?
Use shared preferences as shown:
//declare as global
SharedPreferences prefs = null;
//and in your onCreate method:
prefs = getSharedPreferences("packageNameHere", MODE_PRIVATE);
if (prefs.getBoolean("firstrun", true)) {
//do stuff here if first run
//make sure to flag the boolean as false
prefs.edit().putBoolean("firstrun", false).commit();
}
else{
//if not first run, do something else
}
There is something called "SharedPreferences" that i believe your looking for.
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
Related
I have a shared preference with no default value defined in the xml because I would like to set the default value programmatically when the main activity is created. The preference in question should either be the device language (if that language is available), otherwise the first available language, where the languages are defined in the appropriate xml as a string array.
I currently have, inside the main activity's onCreate method, the following
SharedPreferences preferences = getSharedPreferences(
getString(R.string.shared_prefs_key),
MODE_PRIVATE
);
String detailLanguage = preferences.getString(
getResources().getString(R.string.detail_display_language),
""
);
if (detailLanguage.isEmpty()) {
String deviceLanguage = Locale.getDefault().getLanguage();
String[] availableLanguages = getResources().getStringArray(R.array.pref_entry_values_detail_display_language);
boolean deviceLanguageSupported = false;
for (String availableLanguage : availableLanguages) {
if (deviceLanguage.equals(availableLanguage)) {
deviceLanguageSupported = true;
break;
}
}
preferences.edit()
.putString(
getResources()
.getString(R.string.detail_display_language),
deviceLanguageSupported ? deviceLanguage : availableLanguages[0]
).commit();
Debugging this code on the first run it enters the above if statement and sets the preference but the preference doesn't show as selected in the preference activity first time around (if I then select it myself, from then onward it appears selected as something).
Am I missing something? I am fairly new to Android. I tried the above based on some other similar SO questions.
PreferenceActivity and PreferenceFragment read preferences from a default preference file. To get access to those preferences you should use PreferenceManager.getDefaultSharedPreferences(context) method.
I am guessing that this is the reason you aren't seeing your changes: you write them to getString(R.string.shared_prefs_key) rather than to the default one.
Try changing your first line to this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
I know there must be douzens of answers to this question out there, but either i cant't find them or I don't understand them.
The Question:
How do I get my app to exactly start as it was left?
F.e. dynamicly added checkBoxes shouldn't dissapear!
There is no "out of the box" way of doing it. You could save the current state of your Activity in some way (More on persistence)
Then you need to be able to rebuild the desired state of the persisted state in your Activity lifecycle
You could save and load with the shared preferences for example:
public void saveState(YourState state) {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
sharedPreferences.edit()
.putString("CustomAtt", state.getCustomAtt())
}
public YourState loadState() {
SharedPreferences sharedPreferences = app.getSharedPreferences(R.string.preference_file_key, Context.MODE_PRIVATE)
String customAtt = sharedPreferences.getString("CustomAtt", "DefaultValue")
return new YoutState(customAtt)
}
And use it like this
#Override
protected void onCreate(Bundle savedInstanceState) {
YourState state = loadState();
// Rebuild your activity based on state
someView.setText(state.getCustomAtt())
}
You can store such values in SharedPreferences.
https://developer.android.com/training/basics/data-storage/shared-preferences.html
It is using key-value approach for saving. So you can save some values and read it from SharedPreferences whenever you want to.
This is the best approach for small data, that can be used on the app launch. So you can quit your app and the data is still present - so can be read on the next app launch.
Or save the condition of your program to a text file, so that the program can "translate" it back into conditions before it stops, or what I do not recommend, it saves every object created with ObjectOutputStream.
I need to start an activity(tutorial) on my first app launch. I figured i could write this in my main but then i realized once the app is closed and start again it would just start the tutorial again.
Boolean first = true;
if(first){
Intent i ......
first = false;
}
so i thought about creating a database or writing a value in a file and saving the Boolean value in that. Is there a easier way for this? thanks in advance
You can use preference for this. You can implement following codes on your onCreate method
SharedPreferences prefs = PreferenceManager.getDefaultPreferences(getApplicationContext());
boolean first = prefs.getBoolean("key_first_launch", true);
if (first)
// show your tutorial
else
// dont show your tutorial
When first tutorial complete, change preference value
SharedPreferences prefs = PreferenceManager.getDefaultPreferences(getApplicationContext());
prefs.edit().putBoolean("key_first_launch", false).commit();
You need to save that information, for instance with SharedPreferences, so that it is persistent and read its value when the application is started.
See:
http://developer.android.com/reference/android/content/SharedPreferences.html
http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html#preferences
I`m trying to add tracking events to my android app using Mixpanel (it simply tracks what actions the user is doing in an application), and I want to add an event called "Application Started".
The question is, where should I track the event of the app starting without having it repeated. Is there a method or a function call in the life cycle that executes when the app first starts and only once ?
Do it in onCreate() of your application class.. it will be done only once when app gets started...
No, application class is different from activities.. For an application, there can be only on application class.. And that you declare in the manifest file.. Typically like this:
public class MyApplication extends Application {
#override
onCreate()
{
// Do your task here..
}
}
You can save it in as a preference value:
SharedPreferences setting = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstStart = setting.getBoolean("firstStart",true);
if(firstStart == true) {
//do work first time
SharedPreferences.Editor edit = setting.edit();
edit.putBoolean("firstStart", false);
edit.commit();
}
I am trying to detect if my app has been run before, by using this code:
(This is in my default Android activity)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Log.w("activity", "first time");
setContentView(R.layout.activity_clean_weather);
} else {
Log.w("activity", "second time");
setContentView(R.layout.activity_clean_weather);
}
}
When I first run the app it says first time, when I run it a second time, first time, and a third, first time....
I am using an actual Android device and I am not using the run button each time. I run the app once with the Eclipse run button, then I close the app and press on its icon on my phone.
Is there something wrong with my code?
savedInstanceState is more for switching between states, like pausing/resuming, that kind of thing. It must always be created by you, also.
What you want in this case is SharedPreferences.
Something like this:
public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if (firstRun) {
Log.w("activity", "first time");
setContentView(R.layout.activity_clean_weather);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.commit(); // Save all changed settings
} else {
Log.w("activity", "second time");
setContentView(R.layout.activity_clean_weather);
}
}
I basically took this code directly from the documentation for Storage Options and applied it to your situation. It's a good concept to learn early.
You may use a self-defined shared preference to archive your goal.
The fact is that savedInstanceState holds persistent data across activities. As such if you restart the app, savedInstanceState will be null across runs. You should either use a Preference or some data base entry to keep track of your first run. I myself use a SharedPreference for this purpose.
savedInstanceState will be null if the app is not already loaded in memory. If you want to detect whether the app has run for the very first time, you have to apply different technique, such as using sharedPrefs / DB to store a property for the first run.
i.e. Check sharedPrefs for property "firstRun"
if exists, then it is not a first run
else it is the first run
set the firstRun property to true