This code seems to work fine on everything except when I emulate it on Froyo. I don't have an actual device running Froyo, so I can't test it on an actual device, but it FC's when it get's to the commit. I even have the code in a try block, so I would think that it should catch an exception instead of force closing.
private void getPrefs() {
boolean dockRespond;
boolean carDockRespond;
boolean silenceRinger;
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
dockRespond = prefs.getBoolean("dockRespond", true);
carDockRespond = prefs.getBoolean("carDockRespond", true);
silenceRinger = prefs.getBoolean("silenceRinger", false);
Intent startDock = new Intent(this, DockService.class);
if(dockRespond)
{
//start dock listener service
startService(startDock);
}
else
{
//stop dock listener service
stopService(startDock);
}
try
{
editor.putBoolean(DOCKRESPONSEGLOBAL, dockRespond);
editor.putBoolean(CARDOCKRESPONSEGLOBAL, carDockRespond);
editor.putBoolean(SILENCERINGER, silenceRinger);
editor.commit();
}
catch (Exception e)
{
Log.d("Exception caught: ", e.getMessage());
}
}
All of the constants (in all caps) are defined above in the constants area, and as I said before, the code seems to work on any OS version except Froyo. In froyo it FC's on the "editor.commit();" line.
Any suggestions?
I dont see anywhere in your code where you define what editor is? The first line of code that has editor in it is
editor = settings.edit();
but you never define what 'editor' is
I figured it out. What was happening was that I was putting myself into an endless loop. I had to:
settings.unregisterOnSharedPreferenceChangeListener(prefsListener);
make my changes, then
settings.registerOnSharedPreferenceChangeListener(prefsListener);
Not sure why that only created an issue in Froyo. Google must have made a change in the OS to prevent this in future versions.
Related
I changed shared preferences value but it still returns old one. What am I missing?
This code executed when the user clicks on the item in RecyclerView. So on the first click, I get message " this true" as expected. But on second click I also get " this true", but expect "this false".
SharedPreferences prefs = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
boolean value = prefs.getBoolean(KEY_PREF, true);
if (value) {
Log.v(LOG_TAG, "this true");
Log.v(LOG_TAG, "editing value..");
SharedPreferences.Editor prefs = context.getSharedPreferences(MY_PREF, MODE_PRIVATE).edit();
prefs.putBoolean(KEY_PREF, new_value);
prefs.apply();
} else {
Log.v(LOG_TAG, "this false");
}
All you store is true, always, so there's no way to show this false as it never gonna happen. In fact, your code will not compile as new_value is never declared not assigned.
PS: there's no sense to call getSharedPreferences() second time. You got it already in prefs prior entering your if() block.
The call prefs.apply is asynchronously. You may not see the immediate change. Instead you could use prefs.commit which is synchronously.
I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....
This might seem a little weird!!
But I was wondering if I could add some help on my app .which comes when You first open your app and when you touch the screen it vanishes(Only comes in first run).
The problem is I didn't even know what is this thing called I tried a search on google but I'm nowhere near it.
It will be very helpful if anyone can provide some info about that(what is it called ,How to add it in your App)
Thanks !!
Check my answer for some thing on first setup.
Put this on first time run.
shPref = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences.Editor pref_editor = shPref.edit();
pref_editor.putBoolean("first_time", false);
pref_editor.commit();
Check it like this:
shPref = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
boolean isFirstRun = myPrefs.getBoolean("first_run",false);
if(isFirstRun){
txtViewHelp.setVisibility(View.VISIBLE);
//logic of making it invisible on touch outside
}
else
txtViewHelp.setVisibility(View.GONE);
Hope this helps.
Try this!
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted){
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
**// when the application is previously opened
//Show your help Test**
}
else
{
**// when the application is opened very First Time**
Intent intent = new Intent(MainActivity.this, Home_Module.class);
MainActivity.this.startActivity(intent);
}
This will Help You.
It stores your application status that it is previously opened or not?
I'm trying to set up a dialog that will popup after the users updates or installs the application for the first time. I can't figure out how to exactly do this. Currently I have tried to use the package manager to get the users version and compare it to see if its the most recent. I'm uncertain if this will work as its hard to test for something that relies on a package update. Here is my code:
public void firstrun() {
String version = "";
String currenver = "3.9";
// update function
try {
PackageInfo manager = getPackageManager().getPackageInfo(
getPackageName(), 0);
version = manager.versionName;
} catch (NameNotFoundException e) {
// Handle exception
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString(version, version).commit();
boolean firstrun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("firstrun", true);
if (version.matches(currenver)) {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", false).commit();
} else {
// Save the state
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("firstrun", true).commit();
}
if (firstrun == true) {
new AlertDialog.Builder(this)
.setTitle("Welcome!")
.setIcon(R.drawable.icondialog)
.setMessage("UpdateText")
.setNeutralButton("OK", null).show();
}
}
I think you are on the right track, there are many solutions here and here that may give you ideas.
In addition you could create a database table that contains a flag to prompt or not. By default it would be set to a value to prompt, and then once the user launches and acknowledges the dialog you could change the flag. Then in your onUpgrade() method of your SQLiteOpenHelper you could flip the flag again, and thus your application would prompt on installation of a new version.
My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun preference to true on every app update?
Here is the relevant code:
/**
* get if this is the first run
*
* #return returns true, if this is the first run
*/
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}
/**
* store the first run
*/
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
SharedPreferences mPrefs;
/**
* setting up preferences storage
*/
public void firstRunPreferences() {
Context mContext = this.getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
}
public void setStatus(String statustext) {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putString("status", statustext);
edit.commit();
}
}
In my app, I save in my shared preferences the version code of the app. At every startup, I check to see if the saved version code is lower than my current version code. If it is, I show a "what's new" dialog.
Give this code a whirl - I use it in my main activity's onCreate:
PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
if ( prefs.getLong( "lastRunVersionCode", 0) < pInfo.versionCode ) {
// TODO: Handle your first-run situation here
Editor editor = prefs.edit();
editor.putLong("lastRunVersionCode", pInfo.versionCode);
editor.commit();
}
} catch (NameNotFoundException e) {
// TODO Something pretty serious went wrong if you got here...
e.printStackTrace();
}
prefs is a private SharedPreferences object. This works if it's truly the first run, and for upgrades. At the end of the first-run code, the editor.putLong updates your shared preferences with the current version code of your app so the next run doesn't trigger your first-run code.
This also benefits from the fact that your version code must increase for the app to be seen as an upgrade by the market, so you don't need to remember to change a separate value to detect the first-run.
You could mimic what's done on the database side, with version numbers. Instead of having just a firstRun variable, have a couple with firstRun and versionNumber, and put a static version number field in your app, that you increment at each release. This way, you'll be able to check if the app has been updated, and do your operation on each update.
I'm create class for this; download in https://gist.github.com/2509913
Example Use:
long versionInstalled = App.getVersionInstalled(this);
long current_v = App.getVersion(this);
if( versionInstalled != current_v ){
Log.w("TAG", "Veresion not valid");
}
Run this in the MainActivity's OnCreate
public void onUpdateFirstRun () {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
PackageInfo pInfo;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
Log.d("VersionCode", pInfo.versionCode + " ");
if (prefs.getLong(LAST_RUN_VERSION_CODE_KEY, 0) < pInfo.versionCode) {
if (!isInitializedInSP(KEY)) {
editor.putString(KEY, "");
}
//Finalize and Save
editor.putLong(LAST_RUN_VERSION_CODE_KEY, pInfo.versionCode);
editor.apply();
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
Use method to check if you had already initialized it in previous version
public static boolean isInitializedInSP (String key) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContex());
Object o = mPrefs.getAll().get(key);
if (o != null) {
return true;
}
else {
return false;
}
}