Run AsyncTask only once when application starts for the first time - android

I want to run AsyncTask in android only once when application starts for the first time.
I tried to put Shared preference in onCreate but it didn't work. Any other ideas ?
SharedPreferences prefscrt = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefscrt.getBoolean("firstTime", false)) {
Log.d("DownloadManager", "Installing First Time");
new Task().execute(); //THIS WON'T WORK
SharedPreferences.Editor editor = prefscrt.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Thanks in advance
Madz

Try this code :
SharedPreferences prefs = getSharedPreferences("firstTime", MODE_PRIVATE);
registartion = prefs.getBoolean("firstTime", false);
and now put your if condition

1.First check the value is null or not if null then sharedpref use and save them..
2.But in second time again check if they have already sharedpref run your code .
private Boolean firstTime = null;
SharedPreferences mPreferences = this.getSharedPreferences("first_time", Context.MODE_PRIVATE);
firstTime = mPreferences.getBoolean("firstTime", true);
private boolean isFirstTime() {
if(firstTime == null) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putBoolean("firstTime", false);
editor.commit();
new Task().execute();
if (firstTime!=null) {
}
}
return firstTime;
}

Related

Run certain operations only when the app is first installed

Let us presume that we have a function defined this way:
public class MyClass {
public static void RunFirstTime() {
//...
}
}
The very first time I install the app, I want to run RunFirstTime() but then any other time I run the app, that function should not run.
Is there a built-in way to do this?
Just use SharedPreferences and store a boolean variable when you are done with first run.
To be more clear, the code should be something like this:
public static void RunFirstTime() {
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
boolean firstRun = sPref.getBoolean("firstRun", true);
if(firstRun){
//Do something here
....
//Save firstRun = false in order to not repeat next time
Editor prefEdit = sPref.edit();
prefEdit.putBoolean("firstRun", false);
prefEdit.commit();
}
}
Try code like this:
public boolean isFirstRun() {
SharedPreferences sPref;
sPref = getPreferences(MODE_PRIVATE);
boolean isFirstRun = sPref.getBoolean("FirstRun", true);
Editor ed = sPref.edit();
ed.putBoolean("FirstRun", false);
ed.commit();
return isFirstRun;
}

Using shared preferences (Android)

I am trying to save some data in shared preferences on Android and as the following page says (http://developer.android.com/guide/topics/data/data-storage.html#pref), I should write some code like the code shown bellow inside onCreate() method:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tablet);
//Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
The problem is that the last line:
setSilent(silent);
gives an error shown as:
The method setSilent(boolean) is undefined for the type MainActivity
What should I do to solve this?
Thank you!
To save a value in using sharedpreferences:
SharedPreferences pref = this.getSharedPreferences("Test",0);
Editor editor = pref.edit();
editor.putString("VALUE", value);
editor.commit();
And get it like that:
SharedPreferences prfs = getSharedPreferences("Test", Context.MODE_PRIVATE);
String v= prfs.getString("VALUE", "");
Remove the following line:
setSilent(silent);
The value you need has already been stored in the variable silent. The above line was presumably included to demonstrate what you can do with the variable
To get stored value using SharedPreference
private String getOnPreference() {
String prefName = null;
try {
SharedPreferences myPrefs2 = this.getSharedPreferences("myPrefs",
MODE_PRIVATE);
prefName = myPrefs2.getString("key",value);
} catch (Exception e) {
LOG.error("Get error in shared preference", e);
}
return prefName;
}
To set value using Shared preference
private void setOnPreference(String value) {
try {
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("key", value);
prefsEditor.commit();
} catch (Exception e) {
LOG.error("Set error in shared preference", e);
}
}
Simply use the above functions to get and set any data using shared preference

User authentication should be only once

I am developing an android application which should authenticate user only once in his mobile after installing the app. It should not ask the details for the second time. For this I have used shared preferences by setting a Boolean value. But it,s not working. Is there any suggestions here.. thanks friends !! My code is here
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("Register", true);
editor.commit();
use it this way :
in your onCreate() use :
if (isFirstTime()) {
// do what you want to do only once
}
to call the below :
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
Your approach of using SharedPreference is correct.Put the below coad snippet in your oncreate() method of the Activity.
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
register = prefs.getBoolean("Register",false);
if(!register)
{
//register user
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("Register", register);
editor.commit();
}
else{
//continue with the rest
}
the first time :
settings.edit().putBoolean("Register", true).commit();
and in onCreate you do the test
if(!settings.getBoolean("Register",false))
//it isn't the first time
So the full code :
SharedPreferences settings = getSharedPreferences("settings", 0);
if(!settings.getBoolean("Register",false)){
//it isn't the first time
}
else{
settings.edit().putBoolean("Register", true).commit();
}

Delete data from shared preferences in android

I am trying to delete the data from shared preferences. But I cant do that. To track that the data is removed or not, I am using this code:
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(share_pref_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(share_pref_file);
editor.clear();
editor.commit();
getApplicationContext().getSharedPreferences(share_pref_file, 0).edit().clear().commit();
String strJson = prefs.getString("jsondata","");
if(strJson != null)
{
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
But in logcat window it is showing me "cccccccccccccccccccccccccccc" value every time.
So can anyone help me out that how to remove/delete the data from shared preferences so that if I click on 'logout' button it will remove all the stored data? Thanks in advance.
An empty string is still a string (and String("") != null will return true). Try this instead:
if(!strJson.equals(""))
This assumes the empty string will never be a valid input in your SharedPreferences in the first place.
Try this one inside the button click event to clear the SharedPreferences values.
Editor editor = getSharedPreferences("MyPref", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Try editor.clear(); followed by a editor.commit();
Here is one example that I've used:
Preference clearPref = (Preference) findPreference("MyPref");
btnLogout.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
Toast.makeText(getBaseContext(), "All data cleared!", Toast.LENGTH_SHORT).show();
return true;
}
});
Either change this:
String strJson = prefs.getString("jsondata", "");
To:
String strJson = prefs.getString("jsondata", null);
And then check:
if(strJson != null) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
Or keep it as it is and check it like this:
if(strJson.equals("")) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
settings.edit().clear().commit();
is a one line code I am using, works perfectly
It is my solution:
You can put null instead of your favorite data in shareprefrences
getApplicationContext();
SharedPreferences.Editor pref = (Editor) getSharedPreferences("data", MODE_PRIVATE).edit();
pref.putString("admin_no", null);
pref.commit();

Can't access SharedPreferences from my Service

What I'm trying to do
Hello Guys.
I got a Service which, set's a boolean to true or to false whenever the service is started or stopped (started = true / stopped = false) in the SharedPreference. Now when I try to get the Boolean out there in my Activity, it allways dosn't find it. How can I solve this... Here's the Code for you Guys.
Code
Methode in my Service:
private void setStarted(boolean started) {
// SharedPreferences casten
mPrefs = this.getSharedPreferences(LOG_TAG, MODE_PRIVATE);
// Boolean in SharedPreferences hinzufügen
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear().apply();
editor.putBoolean(PREF_STARTED, started).commit();
editor.commit();
//mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
Log.d(LOG_TAG, "Variabel " + mPrefs.getBoolean(PREF_STARTED, false));
}
In my Activity
// mPrefs caten
mPrefs = this.getSharedPreferences(GPSService.LOG_TAG, MODE_PRIVATE);
// boolean holen ob service gestartet oder nicht
run = mPrefs.getBoolean(GPSService.PREF_STARTED, false);
How do I get the boolean out of there? It allways returns me the default value I had to give in the getBoolean Methode.
Thanks for your help in advance
safari
Here is some code that I'm successfully using in one of my apps. It is used in various parts of the app, e.g. both from activities and services:
void putValue(Context context, String pref, boolean value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(pref, value);
editor.commit();
}
boolean getValue(Context context, String value, boolean defaultValue) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
return settings.getBoolean(value, defaultValue);
}
Try using getDefaultSharedPreferences(Context context) method of PreferenceManager in both your services and your activities.
private void setStarted(boolean started) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
Log.d(LOG_TAG, "Variabel " + mPrefs.getBoolean(PREF_STARTED, false));
}
In your Activity
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
run = mPrefs.getBoolean(GPSService.PREF_STARTED, false);
Also make sure you :
Never call .clear() on editor.
You use PreferenceManager.getDefaultSharedPreferences(this) everywhere.
Just build your prefs object the same way you would as part of your activity. The only difference is pulling your application's context in.
SharedPreferences prefs = _ getApplicationContext().getSharedPreferences("com.example.appname", Activity.MODE_PRIVATE);
Boolean tmpBool = prefs.getBoolean("PREF_NAME", null);

Categories

Resources