I want that when the users install my application and launch it for the first time try areshown " features of the application " but then that screen can neverbe accessed by the user. It should never display again on the same device,ever. It's just like, Showing an Initial Screen on first launch and no initial screen on subsequent launches. Any idea or example as to how can that be done.
Use SharedPreferences to set a flag. Define a key, and in your onCreate(), check if it's set or not. If it's not, display the window and write the key to preferences.
private static final String FIRST_LAUNCH = "first_launch";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
//Assume true if the key does not yet exist
if (prefs.getBoolean(FIRST_LAUNCH, true)) {
//Display window
} else {
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(FIRST_LAUNCH, false);
edit.commit();
}
Related
In my app I was using for more than 1 year "Shared preferences" to store some boolean values (if the user has seen the intro page for example). Now I added one more setting (if the user has seen the help page!) and all the settings stopped working...
I tried changing "commit" to "apply" with no luck. How could by just adding one more shared preference to make it stop working? Is there any properties limit?
My code:
public SharedPreferences getSettings() {
SharedPreferences settings = getSharedPreferences(AppConstants.PREFS_NAME, 0);
return settings;
}
old Activity for Intro:
private void saveUserHasSeenIntro() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, true);
editor.commit();
}
where intro boolean is being read:
Boolean hasShownIntroSteps = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS, false);
if ( !hasShownIntroSteps ) {
// show intro
} else {
New activity for help:
private void saveUserHasSeenHelp() {
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
}
where the "help" boolean is read:
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
if ( !hasSeenHelp ) {
// show help activity
} else {
Your methods are fine and they should work perfectly. Check a couple of things just in case:
Ensure you don't call clear() or remove() method of the SharedPreferences editor after saving your prefs by mistake.
Ensure the constants AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS and AppConstants.SETTING_BOOLEAN_HAS_SHOWN_INTRO_STEPS have different values as the former could overlap the second by mistake.
Just add a breakpoint after setting the new pref and read the value to check if it's set just after it.
SharedPreferences.Editor editor = getSettings().edit();
editor.putBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, true);
editor.commit();
Boolean hasSeenHelp = getSettings().getBoolean(AppConstants.SETTING_BOOLEAN_HAS_SHOWN_HELP_STEPS, false);
In some extreme cases you could even implement SharedPreferences.OnSharedPreferenceChangeListener to see where your SharedPreferences are being changed to avoid unwanted pref sets.
It can be a Memory Limitation on your SharedPreferences file and usually this comes with an OutOfMemoryException. I guess if something like that would happen you would probably seen it in your code, unless you are not reading/writing in another Thread. How big is your SharedPreferences file in numbers of key - value pair ?
In my app, i am starting a service in Mainactivity. I show a reminder popup everytime the app is opened. But, I only want to show the pop up 1 time.
How to store the pop up's count accros multiple app launches?
boolean mboolean = false;
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
mboolean = settings.getBoolean("FIRST_RUN", false);
if (!mboolean) {
// do the thing for the first time
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("FIRST_RUN", true);
editor.commit();
} else {
// other time your app loads
}
This code will show something only once, untill you dont reinstall app or clear app data
EXPLANATION:
OK, I'll explain it to you. SharedPreferences are like a private space of your application in which you can store primitive data (strings,int,boolean...) that will be saved untill you dont delete application. My code above works like this, you have one boolean which is false when you start the application, and you will show your popup ONLY if the boolean is false --> if (!mboolean). Once you showed your pop up, you put the boolean value to true in sharedPreferences, and system will next time check there, see that it is true and wont show the pop up again untill you reinstall the application or clear the application data from application manager.
put this code when you push popup.
pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (!pref.getBoolean("popupfirst", false)) {
Editor editPref = pref.edit();
editPref.putBoolean("popupfirst", true);
editPref.commit();
}
when your app first start and you push popup then its add true in to Preference else it can't do anything.
Store it in the SharedPreferences.
E.g. to save it in your shared preferences, when showing the popup:
// Get the shared preferences
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Edit the shared preferences
Editor editor = prefs.edit();
// Save '1' in a key named: 'alert_count'
editor.putInt("alert_count", 1);
// Commit the changes
editor.commit();
And afterwards, when you launch the app, you can extract it again, to check how many times it was launched before:
// Get the shared preferences
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Get the value of the integer stored with key: 'alert_count'
int timesLaunched = prefs.getInt("alert_count", 0); // 0 is the default value
if(timesLaunched <= 0){
// Pop up has not been launched before
} else {
// Pop up has been launched 'timesLaunched' times
}
Ideally, when you save the number of times launched in the SharedPreferences, you can first extract it, and than increment the current value.. Like so:
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Get the current value of how many times you launched the popup
int timesLaunched = prefs.getInt("alert_count", 0); // 0 is the default value
Editor editor = prefs.edit();
editor.putInt("alert_count", timesLaunched++);
editor.commit();
I've been trying to create a user profile section for my app where the user enters his information (Name, DoB, height, weight etc) and clicks submit. After this he's taken to the main menu of the app.
The problem I have is that if I close the app and run it again, this will obviously result in the app displaying the user profile section again and asks the user to enter his information.
I've been trying to look for a way in which the app saves the information that the user enters and remembers it. So for example when the user first uses the app, he gets the user profile section and enters his information. When the user closes the app and opens it again it should take him straight away to the main menu.
I know I could achieve this slightly with Preferences, but I'd rather use a normal layout(LinearLayout) so that it gives me more options such as TextView etc.
Is there a way where I could achieve this using just LinearLayout instead of Preferences?
I've also been looking at creating custom Preferences, but none of the things I found was particularly useful.
Thanks in advance.
Use SharedPreferences.
Check the application for First Run and display layout which you want to enter user's profile.
After store boolean flag for first Run in shared Preference which will prevent your Profile Screen to display again.
Look at Check if application is on its first run
Update:
Put this FirstRun() code in your onCreate() of Main Activity.
private void FirstRun()
{
SharedPreferences settings = this.getSharedPreferences(MainActivity.PREFS_NAME, 0);
boolean firstrun = settings.getBoolean("firstrun", true);
if (firstrun)
{
// Checks to see if we've ran the application b4
SharedPreferences.Editor e = settings.edit();
e.putBoolean("firstrun", false);
e.commit();
// Display User Profile Screen
}
}
use sharedPreference to store information by this way..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("userid", "success");
editor.commit();
and to get the value from it use below code..
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref2.getString("userid", null);
or try to use SqliteDatabase or may be Application Class..this will store the information as you want.
#Override
public boolean saveUserData(UserModel userModel, Context context) {
email = userModel.getEmail();
firstName = userModel.getFirstName();
lastName = userModel.getLastName();
twitterId = userModel.getTwitterId();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor setUserDataPreference = userData.edit();
setUserDataPreference.putString(EMAIL, email);
setUserDataPreference.putString(FIRST_NAME, firstName);
setUserDataPreference.putString(LAST_NAME, lastName);
setUserDataPreference.putString(TWITTER_ID, twitterId);
setUserDataPreference.commit();
return true;
}
#Override
public UserModel getUserData(Context context) {
UserModel userModel = new UserModel();
SharedPreferences userData = context.getSharedPreferences(APP_NAME,
Context.MODE_PRIVATE);
email = userData.getString(EMAIL, "");
firstName = userData.getString(FIRST_NAME, "");
lastName = userData.getString(LAST_NAME, "");
twitterId = userData.getString(TWITTER_ID, "");
userModel.setEmail(email);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
userModel.setTwitterId(twitterId);
return userModel;
}
I created a MainActivity in which the user has a few app options, displayed in a grid menu, which access subsequent specific activities. However, when the application starts, I use an AlertDialog for the user to enter login details, inflated just after the grid layout definition.
The problem is, each time I select an item in the grid menu (and, consequently, a new activity), the AlertDialog pops-up again. How can I avoid this?
Moreover, I have an uploading service which should start with the beginning of the MainActivity (or after the login, perhaps), but should not be restarted each time a new activity is called. I assume this problem is related to the previous one, although I have managed to temporarily solve it by using a startService button via an OptionsMenu. This is no permanent solution.
Thank you in advance.
EDIT: I tried to use getSharedPreferences as follows:
private SharedPreferences prefs;
private String prefName = "MyPref";
int hasLoggedIn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mm_gridmenu);
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
hasLoggedIn = prefs.getInt("hasLoggedIn", 0);
if (hasLoggedIn == 0) {
showDialog(SHOW_DIALOG);
prefs = getSharedPreferences(prefName , MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("hasLoggedIn", 1);
editor.commit();
}
However, this way the hasLoggedIn value is saved as 1 and the dialog never pops-up again. I tried setting the back button to fix that, but this seems to prevent the app from being minimized. Is there a way to add that action to the button? (Which I would duplicate on the Home button as well)
#Override
public void onBackPressed() {
prefs = getSharedPreferences(prefName , MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("hasLoggedIn", 0);
editor.commit();
Log.i("hasLoggedIn", hasLoggedIn + "");
return;
}
Moreover, I believe this action will affect subsequent activities (setting the alertDialog back on). Which should be a valid alternative to this?
Basically you need to keep track of your applications states, you have a few options to do this. One simple way would be to use a SharedPreferences to store a boolean variable called something like hasLoggedIn after the user logs in you set this value to true. Each time your main activity launches simply check the value of hasLoggedIn if its is set to false require the user log in again. If it is already true don't show the log in dialog
You can try this:
Add a boolean flag in your MainActivity:
private boolean dialogFlag = true;
in the onCreate/onResume method:
if(dialogFlag) {
createDialog();
dialogFlag = false;
}
If you want to pop up just once the app is installed, you can save this flag into a property file. And read it first whenever the app is getting started.
i need to save a simple field to configurate my APP, cause this, i wont use a database (it's only a field...), i need to save true or false value for this field on a file, and everytimes a section of my app wanna check if it is true they have to check this textfile, and not to open a connexion to a database
i need to save the config for ever... i mean that when i exit from my app, and for example, i shut down my android device, when i start my device again and start my app, the config have to be saved
is this possible? how can i do it? i can't find any information about that
EDIT: i have problems with the first answer... this code is on my oncreate method:
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
if (settings.getBoolean("showMeCheckBox", true))
showMeCheckBox.setChecked(true);
else
showMeCheckBox.setChecked(false);
applyButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if (showMeCheckBox.isChecked()) {
configEditor.putBoolean("showMeCheckBox", true);
} else {
configEditor.putBoolean("showMeCheckBox", false);
}
}
});
ok, but this doesn't works... allways is selected... always true, like the default value... doesn't matter if i checked or unchecked it.... :S
i suggest not to use a textfile but the Preference Editor.
static SharedPreferences settings;
static SharedPreferences.Editor editor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
editor = settings.edit();
//store value
editor.putString("Preference_name_1", "1");
//get value
//eill return "0" if preference not exists, else return stored value
String val = settings.getString("Preference_name_1", "0");
Edit: you have to initialize the configEditor and after setting a value, you have to commit
editor = settings.edit();
editor.putBoolean("name",true);
editor.commit();