When my android app starts there will be a prompt that asks user whether to upgrade to newer version or not.I used an alertbox to display it.I have two buttons in it, "Upgrade" and "No thanks".Then I added a checkbox to it.And the label for that check box is "Dont ask me again". When user click on that checkbox,that should be remembered and the prompt shouldnt asked again.Can anyone suggest me a solution to achieve this?
The Best option you can go for is of SharedPreference. You can Save the in Internal Database.
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
int currentVersion = info.versionCode;
// version name here for display in the about box later.
this.sVersionName = info.versionName;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt("Key", 0);
if (currentVersion > lastVersion) {
prefs.edit().putInt("key",currentVersion).commit();
Intent intent = new Intent(this, StartUp.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
// Your Code goes here if you want to Display it Only Once.
return true;
}
EDIT
SavePreferences("MEMORY1","Your String Here");
private void SavePreferences(String key, String value) {
SharedPreferences settings = getSharedPreferences(pref, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences() {
SharedPreferences settings = getSharedPreferences(Settings.pref, 0);
String sDefault_Card = settings.getString("MEMORY1", "");
}
Use SharedPreferences and save / retrieve boolean value to indicate checked / uncheked state
You could use SharedPreferences to store user's selection:
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean showPrompt = preferences.getBoolean("Show_Prompt", true);
Related
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 have 27 characters that I want a player to unlock by beating scores, e.g. if his score is greater than 200 he unlocks character #1. I have a hard time trying to do that.
I have a class for characters that contains its number, the score required to unlock it, and a boolean to check if he is unlocked. But when it comes down to saving, I can't do that.
The main game loop is in file GameScreen. It has a value points counting the score.
When GameState changes to PlayerDead I want to check if any new character has been unlocked, and whether the high score has been beaten to save points.
Please help, I'm struggling with it for over a week and I can't find a good tutorial for SharedPrefs because all of them apply to GUI based activity that saves the name and surname you entered.
if you need sharedPrefs I can help you.
I can give some some example code.
or you can send your code and error if you get one, we update it.
but sharedPrefs is a good idea for that ? if user goes to application settings and clears data of your app, all data will be lost.
why dont you try create a sqlite databade, save it into assets directory and use it?
It's actually pretty simple, you use SharedPreferences to store key-value pairs. You can either call
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
From the GameScreen and then define a constant:
public static final String KEY_SCORE = "score";
To use as the key for the saving.
In order to actually save, you need an Editor:
SharedPreferences.Editor mEditor = mPrefs.edit();
//save data now, mPlayerScore is the score you keep track of
//if it's another type call putString(), etc
mEditor.putInt(KEY_SCORE, mPlayerScore);
//if that is the only thing you want for noe
//close and commit
mEditor.commit();
And in order to retrieve the saved score, during your onCreate() you can do:
public void getUserProgress() {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//no need for an editor when retrieving
mPlayerScore = mPrefs.getInt(KEY_SCORE, 0);
//second value passed was the default score
//if no score was found
}
In order to check for new character s being unlocked, you can call the following code after every game:
private void checkForUserUnlocks() {
if (mPlayerScore >= MyUnlockableCharacter.SCORE_NEEDED_TO_UNLOCK)
MyUnlockableCharacter.isUnlocked = true;
//and same for other unlockabld characters
}
There are other ways to access SharedPreferences, let me know if you need more info.
Use the below code to store and retrieve Score from SharedPreference.
public static void saveScore(Context context, int score){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("SCORE", value);
editor.commit();
}
public static int loadScore(Context context){
SharedPreferences sharedPreferences = context.getSharedPreferences("YOUR_PACKAGE_NAME", Context.MODE_PRIVATE);
int score = sharedPreferences.getInt("SCORE", 0);
return score;
}
Read Sample;
public int Read() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
int mCounter = mSharedPrefs.getInt("Counter", 0);
return mCounter;
}
Write Sample;
public void Write() {
SharedPreferences mSharedPrefs = getSharedPreferences("FileName",
MODE_PRIVATE);
SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();
mPrefsEditor.putInt("Counter", 15);
mPrefsEditor.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 am developing an android application in which i have to do the following thing
At the start of the app, first thing it should do is ask user to enter name and then through a welcome screen with that name.
Then When the app is used next time it should just give welcome screen (should not ask for name again)
I have created the code for the above.
I have used shared preference saved
My code is
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
String strSavedMem2 = sharedPreferences.getString("MEM2", "");
textSavedMem1.setText(strSavedMem1);
textSavedMem2.setText(strSavedMem2);
}
}
But how to check whetehr user is already registered?
Thanks
Tushar
But how to check whetehr user is already registered?
When user starts application first time that time you will check if any preference value exists for name key.
Following snippet will help you
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String namePrefrence = sharedPreferences.getString("uname", "");
if (namePrefrence.length() == 0) {
//User not registered!!
Show dialog where user will enter username
} else {
//User is registered!!
just show welcome screen
}
Well to use SharedPrefernces.. use this::
first declare it...
public static final String PREFS_NAME = "PrefernceNAme";
public static final String PREFS_ITEM = "PrefItemStored";
to get values from it, use:::
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
mode = preferences.getString(PREFS_ITEM, "PrefItemStored");
and to add values in SharedPrefernces, use::
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(PREFS_ITEM, value)
.commit();
I am trying to make a popup dialog that only shows after the app's first run that will alert users of the new changes in the app. So I have a dialog popup like this:
new AlertDialog.Builder(this).setTitle("First Run").setMessage("This only pops up once").setNeutralButton("OK", null).show();
Once they dismiss it, it won't come back until the next update or they reinstall the app.
How can I set the dialog code above to run only once?
Use SharedPreferences to store the isFirstRun value, and check in your launching activity against that value.
If the value is set, then no need to display the dialog. If else, display the dialog and save the isFirstRun flag in SharedPreferences.
Example:
public void checkFirstRun() {
boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun){
// Place your dialog code here to display the dialog
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("isFirstRun", false)
.apply();
}
}
While the general idea of the other answers is sound, you should keep in the shared preferences not a boolean, but a timestamp of when was the last time the first run had happened, or the last app version for which it happened.
The reason for this is you'd likely want to have the first run dialog run also whenthe app was upgraded. If you keep only a boolean, on app upgrade, the value will still be true, so there's no way for your code code to know if it should run it again or not.
Like this you can make a difference between a new install and a update.
String StoredVersionname = "";
String VersionName;
AlertDialog LoginDialog;
AlertDialog UpdateDialog;
AlertDialog FirstRunDialog;
SharedPreferences prefs;
public static String getVersionName(Context context, Class cls) {
try {
ComponentName comp = new ComponentName(context, cls);
PackageInfo pinfo = context.getPackageManager().getPackageInfo(
comp.getPackageName(), 0);
return "Version: " + pinfo.versionName;
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return null;
}
}
public void CheckFirstRun() {
VersionName = MyActivity.getVersionName(this, MyActivity.class);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
StoredVersionname = (prefs.getString("versionname", null));
if (StoredVersionname == null || StoredVersionname.length() == 0){
FirstRunDialog = new FirstRunDialog(this);
FirstRunDialog.show();
}else if (StoredVersionname != VersionName) {
UpdateDialog = new UpdateDialog(this);
UpdateDialog.show();
}
prefs.edit().putString("versionname", VersionName).commit();
}
I use this to display a help dialog on first run. I don't want this to show after an update. That is better suited for a changelog.
private void doFirstRun() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
showDialog(DIALOG_HELP);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
There is no actual question, but I assume you want to know how to achieve the intended effect. If that's the case, then use a SharedPreference object to get a boolean 'first run' which defaults to true, and set it to false just after the first run.
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
doFirstRun();
private void doFirstRun() {
SharedPreferences settings = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
I used this code to ensure that its the first time someone runs the application. The loginPrefsEditor is cleared from data because i have a "Remember Me" Button which stores the data to the sd card. Hope it helps !