Execute a piece of code once - android

I am currently developing an app that requires the data to be fetched from server and stored in my local data base.To ensure that the piece of code runs only once I am doing the following thing.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean dialogShown = settings.getBoolean("dialogShown", false);
if (!dialogShown) {
//Asyntask executed here
if (haveNetworkConnection()) {
new xyz().execute();
} else {
Toast.makeText(getApplicationContext(), "Sorry... No Internet Connection", Toast.LENGTH_LONG).show();
}
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dialogShown", true);
editor.apply();
}
Above I am setting the shared preference so that it gets executed only once.Now the Problem is in case if there is no internet connection the shared preference will be executed and the data will not be loaded how can I overcome this situation.Any help Appreciated

Now the Problem is in case if there is no internet connection the
shared preference will be executed and the data will not be loaded how
can I overcome this situation.
Instead of updating value when dialogShown is false, update value in SharedPreferences when Network connection is available otherwise make it false:
if (haveNetworkConnection()) {
new xyz().execute();
// update value in SharedPreferences for dialogShown to true
} else {
// update value in SharedPreferences for dialogShown to false
}
Or use onPostExecute method of xyz class for updating flag value when all operation is successful

You can check for the network connection first.
if (haveConnection()){
if(!dialogShown){
new xyz().execute
dialogShown = true;
}else
//already done
}
}
The above code should check for a connection first then check for a dialogShown variable being false. The con of this approach is the constant pinging of the connection to check if it exists. Depending on how you are using the enclosing method this might cause a design decision review. You can always use onPostExecution() instead.

Related

Reverting an android preference's value when a statement in another thread fails

I have settings in my app that I allow the user to manipulate using a PreferenceScreen with Preferences. However, I want to store the settings on a server so that the settings can persist over multiple devices. I have the following code that lets me do this:
private void updateSettingOnPrefChange(final Preference pref, final Setting setting) {
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, final Object newValue) {
try {
setting.update(newValue, new Callback<Boolean>() {
#Override
public void call(Boolean succeeded) {
if (!succeeded) {
Toast.makeText(getActivity(), "Setting failed to update. Please try again.", Toast.LENGTH_LONG).show();
//here I need to revert the value of the Preference without again calling the onChangeListener
}
}
}, getActivity());
} catch (Exception ex) {
if (BuildConfig.DEBUG)
ex.printStackTrace();
Toast.makeText(getActivity(), "Setting failed to update. Please try again.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
}
As you can see in the code the request is being run on a different thread using a custom Callback class to clean up based on the result of the call. The issue is the code will have already return true on the main thread.
How can I revert the value of the Preference in the callback function (preferably without also calling the onPrefChangeListener function so I don't get infinite recursion)?
Use the OnPreferenceClickListener instead of OnPreferenceChangeListener to listen for user taps on the setting field and then make your rpc request accordingly. If you have to update the value (in the case of a server failure) you can change the setting without firing the click listener and having the infinite loop.
https://developer.android.com/reference/android/preference/Preference.html#setOnPreferenceClickListener(android.preference.Preference.OnPreferenceClickListener)

SharedPreferences return same value even after editing

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.

Create a function that fires only once after app is installed on phone

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....

Android SharedPreferences Force Close on commit in Froyo

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.

Android: Update Dialog with share preferences

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.

Categories

Resources