Android sharedpreferences - android

I've been following this tutorial and i am stuck.
public class Main extends Activity {
SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
firstRunPreferences();
if(getFirstRun())
{
Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
setRunned();
}
else
{
Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
}
}
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
public void firstRunPreferences() {
Context mContext = Main.this.getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
}
}`
Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".
Thanks

I am assuming you are using the Emulator to run your app. Are you closing the emulator between runs?
Check if you have the "Wipe User Data" checkbox ticked in the Target tab of your Debug run configuration in Eclipse.

SharedPreferences are not cleaned by uninstall.
If you want something cleaned after reinstall, put a field in your database.
Stéphane

I'm not sure but I think SharedPreferences are removed when uninstalling, but not when updating an app.

Related

Android Studio Start Up App Tips And Hints

I've looked around and I'm trying to see if Android Studio has any sort of function for when first term use of the app it shows some messages to help people.
I was thinking of using simple text boxes when on first create off the app/ first launch it would show the tips until they click on each object or item.
I know how to do the click and view just not sure the function to use for when they start the app?
You detect the first launch of your app for instance by loading (and defaulting) a boolean value from your app's preferences.
In your MainActivity
private boolean firstStart = true;
#Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = mContext.getSharedPreferences("APP", Context.MODE_PRIVATE);
firstStart = prefs.getBoolean("firstStart", true);
if (firstStart) {
// do your stuff on first start here
// like set "showWizard" or any other flag to true so
// your controls can behave in "firstStart" mode
// Don't forget to save, that it is now no longer the first start...
firstStart = false;
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
}
Maybe try adding them into this:
#Override
public void onCreate() {
super.onCreate();
//put your lines in here
}

How to implement permanent splash screen and 1 time tutorial both in one app [duplicate]

This question already has answers here:
Determine if Android app is being used for the first time
(15 answers)
Closed 6 years ago.
I am new to android development and and I want to setup some of application's attributes based on Application first run after installation. Is there any way to find that the application is running for the first time and then to setup its first run attributes?
The following is an example of using SharedPreferences to achieve a 'first run' check.
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)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
When the code runs prefs.getBoolean(...) if there isn't a boolean saved in SharedPreferences with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the line prefs.edit().putBoolean("firstrun", false).commit(); will have been executed and therefore prefs.getBoolean("firstrun", true) will actually return false as it overrides the default true provided as the second parameter.
The accepted answer doesn't differentiate between a first run and subsequent upgrades. Just setting a boolean in shared preferences will only tell you if it is the first run after the app is first installed. Later if you want to upgrade your app and make some changes on the first run of that upgrade, you won't be able to use that boolean any more because shared preferences are saved across upgrades.
This method uses shared preferences to save the version code rather than a boolean.
import com.yourpackage.BuildConfig;
...
private void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
// Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
// Get saved version code
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = prefs.getInt(PREF_VERSION_CODE_KEY, DOESNT_EXIST);
// Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
// This is just a normal run
return;
} else if (savedVersionCode == DOESNT_EXIST) {
// TODO This is a new install (or the user cleared the shared preferences)
} else if (currentVersionCode > savedVersionCode) {
// TODO This is an upgrade
}
// Update the shared preferences with the current version code
prefs.edit().putInt(PREF_VERSION_CODE_KEY, currentVersionCode).apply();
}
You would probably call this method from onCreate in your main activity so that it is checked every time your app starts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
}
private void checkFirstRun() {
// ...
}
}
If you needed to, you could adjust the code to do specific things depending on what version the user previously had installed.
Idea came from this answer. These also helpful:
How can you get the Manifest Version number from the App's (Layout) XML variables?
User versionName value of AndroidManifest.xml in code
If you are having trouble getting the version code, see the following Q&A:
How to get the build/version number of your Android application?
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Util {
// ===========================================================
//
// ===========================================================
private static final String INSTALLATION = "INSTALLATION";
public synchronized static boolean isFirstLaunch(Context context) {
String sID = null;
boolean launchFlag = false;
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
launchFlag = true;
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return launchFlag;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
> Usage (in class extending android.app.Activity)
Util.isFirstLaunch(this);
There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor or using a database.
If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.
Regards,
Stephane
I'm not sure it's good way to check it. What about case when user uses button "clear data" from settings? SharedPreferences will be cleared and you catch "first run" again. And it's a problem. I guess it's better idea to use InstallReferrerReceiver.
Just check for some preference with default value indicating that it's a first run. So if you get default value, do your initialization and set this preference to different value to indicate that the app is initialized already.
The following is an example of using SharedPreferences to achieve a 'forWhat' check.
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
if (preferences.getBoolean(forWhat, true)) {
preferencesEditor.putBoolean(forWhat, false).commit();
return true;
} else {
return false;
}
}
There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings!
a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.
This might help you
public class FirstActivity extends Activity {
SharedPreferences sharedPreferences = null;
Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
}
#Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("firstRun", true)) {
//You can perform anything over here. This will call only first time
editor = sharedPreferences.edit();
editor.putBoolean("firstRun", false)
editor.commit();
}
}
}
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
}
}

Run code on first OnCreate only

I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}

Variables In PreferenceActivity

In my android application i want to make a feedback dialog that will show the second time the application is started.
How can i do this ?
Can i do it by variables in a PreferenceActivity. If the a variable in the preference activity is edit by feks ++; will this be the result of the variable next time the app is started ?
Edit:
I dont get any of the suggested answers to work, can i create a text file on the ext or internal store the first time the app is started and check if the file exists ?
Use SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences mSharedPrefs;
private static final String PREF_LAUNCH_COUNTER = "launch_counter";
private int mLaunchCount = 0;
#Override
public void onCreate(Bundle savedState) {
mSharedPrefs = getPreferences(Context.MODE_PRIVATE);
if (savedState != null) {
mLaunchCount = savedState.getInt(PREF_LAUNCH_COUNTER, 1);
} else {
mLaunchCount = mSharedPrefs.getInt(PREF_LAUNCH_COUNTER, 1);
if(mLaunchCount > 1) {
//code to handle when the app was launched after the first time.
} else {
//code for when the app was launched for the first time..
}
mSharedPrefs.edit().putInt(PREF_LAUNCH_COUNTER, mLaunchCount++);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(PREF_LAUNCH_COUNTER, mLaunchCount);
}
}
No, variables do not persist through activity restarts, because the entire object is garbage collected and recreated.
You can use SharedPreferences to store data that must be persisted between application launches.
It's kinda of a barbarian solution, but it did not have Eclipse or and Android phone close to me.
You can do something like that I think :
protected boolean isSecondLaunchTime() {
SharedPreferences settings = getPreferences(MODE_PRIVATE);
int time = settings.getInt("launchTimes", 1);
if(time==1 || time>2) return false;
settings.edit().putString("launchTimes", ++time);
settings.edit().commit();
if(time==2) return true;
else return false;
}
Good luck !

Android sharedpreferences force closes

I am trying to use sharedpreferences in a PreferenceActivity, but unfortunately it force closes. Part of it:
public class EditPreferences extends PreferenceActivity {
String ListPreference;
boolean CheckboxPreference;
SharedPreferences mprefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("true"))
{
Toast.makeText(getApplicationContext(), "CB: " + "true", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor edit = mprefs.edit();
edit.putString("cbstate", "true");
edit.commit();
}
else
{
Toast.makeText(getApplicationContext(), "CB: " + "false", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor edit = mprefs.edit(); //this line force closes
edit.putString("cbstate", "false");
edit.commit();
}
return true;
}
});
What is wrong with the code?
Thanks,
B
It doesn't look like mprefs is ever assigned a value (unless it's happening somewhere else)
You should look at the log to see the stack crawl of the exception, which tells you why your code is crashing.
I am not adding this as a question for clarification, because the fact that a stack crawl is not included in the question is a strong indication that you haven't actually looked at it, and if that is the case then the answer to your question and most likely solution to your problem is to go look at that and see why it says you are crashing.

Categories

Resources