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
Related
I am trying to log installs of my app using Firebase with this simple code below:
firebaseAnalytics.logEvent("foo", bundle);
However, I am not sure where to put this code. Does any one know of an "onInstall" method in the Application class?
Or is there another, easier way to log installs with Firebase?
Thank you!
You could determine if the user launches the application for the first time, and log that event.
public class MyActivity extends Activity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
firebaseAnalytics.logEvent("foo", bundle);
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
Code referenced from this SO answer.
There's another answer in that same SO question that explained how to differentiate between first run and subsequent upgrades, I'll just link that SO answer here for your reference.
The cleanest method would be to have a remote server that holds a unique ID for each user.
Also, you could theoretically write a file directly on the device. But then, you'd need to get the write permission and it's most definitely not a good idea to create and leave a file on the device.
P.S - To answer the actual question, No, Android doesn't have an onInstall method.
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 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
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();
}