Shared preference with session timeout using countdowntimer - android

I want to using startcountdown timer method to change preference value but its not worked.
private void startCountdownTimer(final String judul){
countDownTimer = new CountDownTimer(120000, 1000) {
public void onTick(long millisUntilFinished) {
SharedPreferences pref = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("click"+judul, "1");
}
public void onFinish() {
SharedPreferences pref = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("click"+judul, "0");
}
}.start();
}
can i use method ontick and onfinish to change preference like that ?? I want to make session timeout in android actually. so Im using countdown timer to manipulate it.

Use like this is more easy
SharedPreferences pref = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
pref.edit().putString("click"+judul, "1").commit();

Related

SharedPreferences should remember the content of the TextView when it returns to MainActivity

I have a situation where there is a TextView in MainActivity with some textual content. However, when I go from MainActivity to SecondActivity and return to MainActivity again, the text contained in TextView is lost. I tried to solve this with the help of SharedPreferences and I wrote the code. SharedPreferences does not save when I return from SecondActivity. I really do not see where I am making a problem in this code and I ask your help.
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String textstorage = sharedPreferences.getString("TEXT", "");
mytext.setText(textstorage);
}
You should call LoadPreferences() in onResume() because onCreate() won't be called when you return back from Second Activity
#Override
protected void onResume() {
super.onResume();
LoadPreferences();
}
you need to give name to your preference try below code:SharedPreferences.Editor editor = getSharedPreferences(PREF_NAME, PRIVATE_MODE).edit()
editor.putString(key, value);
editor.apply();
editor.commit(); // you can omit this, i use this one
and to get it back SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE);
String textstorage = sharedPreferences.getString(key, "default value"); // default value will be alternate value if you string is not found
mytext.setText(textstorage);

Why unknown variable error trying to save app data?

I'm trying to save a high score in my app by using SharedPreferences. Everything works fine except for line 16 "score". I'm not sure the best way to fix this issue. Any help is appreciated.
public class MainActivity extends Activity implements OnClickListener {
TextView textView1;
EditText editText1;
Button button1;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
String score = (Integer.toString(counter));
textView1 = (TextView)findViewById(R.id.textView1);
editText1 = (EditText)findViewById(R.id.editText1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);}
public void onClick(View v) {
if (v == button1){
counter++;
editText1.setText(Integer.toString(counter));
}
}
}
It looks like this example: Write to Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Are you really adding an int? What is the error?
You are not initialising the score var. Try this:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", counter);
editor.commit();
BUT, this is wrong since you will only write the value 0 on each activity create call. Put the above code in a method so that you can call it at appropriate times.

Logout clear SharedPreferences

I have a login page that saves username and password to SharedPreferences. I have another Activity class that includes a logout button. I want to clear SharedPreferences when I click the logout button. The problem is that I don't get the SharedPreferences from this class. How can I get the SharedPreferences?
LoginPage
public class MainActivity extends Activity {
public SharedPreferences.Editor loginPrefsEditor;
public SharedPreferences loginPreferences;
private Boolean saveLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.et_Username);
pass = (EditText) findViewById(R.id.et_Password);
login = (Button) findViewById(R.id.bt_Login);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
name.setText(loginPreferences.getString("username", ""));
pass.setText(loginPreferences.getString("password", ""));
}
login.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
name1 = name.getText().toString();
pass1 = pass.getText().toString();
//new Thread (new Task()).start();
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", name1);
loginPrefsEditor.putString("password", pass1);
loginPrefsEditor.commit();
new myAsyncTask().execute();
}
});
}
Logout Button in AnotherActivity
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
Try this !
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
finish();
});
I think you have a trouble in understanding Shared preferences in android .
According to official documentation
To get a SharedPreferences object for your application, use one of two
methods:
getSharedPreferences() - Use this if you need multiple preferences
files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for
your Activity. Because this will be the only preferences file for your
Activity, you don't supply a name.
You should have a Context for using both the above methods .
Also Shared preferences are stored asa key value pair , so clearing should mean that you set the values to some empty string.
For more details , and better explanation you can read here http://developer.android.com/guide/topics/data/data-storage.html#pref
and http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
Hope this will help.
Cheers!
It as Simple. Like you save your data in SharedPrefernce
SharedPreferences sp = getSharedPreferences("MYKEY",0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("username" , username);
editor.putString("password" , password);
Now you can retrieve as in any class of your app like,
SharedPreferences sp = getSharedPreferences("MYKEY",0);
String uname = sp.getString("username");
String pwd = sp.getString("password");
And for clear your username and password
editor.clear();
editor.commit();
or
editor.remove("username");
editor.remove("password");
editor.commit();
Why not write a SharedPreference utility class. This can be accessed from both the activities.
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
In Kotlin you can use this code to clear the sharedpreference data
private val sharedPref = "sharedpreference"
val sharedPreferences: SharedPreferences = context.getSharedPreferences(sharedPref, Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.clear()
editor.apply()
SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
finish();

usea savePreferences in dynamically layout -android

I'm making an app that contains a dynamically layout and it generates textView's in run time, I need that when I close the application all the textView has been added, don't erase; I think I can do that whit savePreferences(), but What parameters I have to use?
private void savePreferences(What parameter here, What parameter here) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.commit();
}
Thank you
Shared Preferences should work. Try this...
public class sample extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
// THIS IS WHERE YOU STORE THE TEXTVIEW DATA
// THERE ARE MANY ' editor.put...(...) ' methods
// ie. editor.putInt(...) , editor.putString(...)
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}

Storing and Retrieving Values from SharedPreferences on Activity state changes

Basically I have a list and I need to remember the offset and load the offset value every time the Activity is restored unless the Activity completely destroyed.
//Inside onCreate
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Offset = settings.getInt("TheOffset", 0);
//End onCreate
#Override
protected void onPause() {
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
}
#Override
protected void onDestroy() {
super.onDestroy();
//settings.getInt("TheOffset", 0);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", 0);
}
onPause() will always be called before your activity is placed in the background and/or destroyed, so you do not have to save state in onStop() and onDestroy() as well.
For the state to be preserved in SharedPreferences, you need to add editor.commit() after writing the value. Otherwise it won't be stored. Like this:
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", Offset);
editor.commit();
You can read more here: http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState
You will only need to save your offset in onResume() and set it to 0 when the activity is going to be destroyed, which you can tell by using isFinishing() in onPause(), like the following:
protected void onPause() {
if(isFinishing()) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("TheOffset", 0);
editor.commit();
}
}
...but I still have no idea what you intend to achieve.

Categories

Resources