SharedPreferences not keeping value - java

With SharedPreferences, i would like to save a value (that will be later the date of last update) and load it. It works well until i shut down my phone or force close my application. It resets the value.
Here's the code :
public class feedPlayer extends Activity
{
public final static String PARAM_USERDETAILS="userdetails";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadvars();
savevars();
}
public void savevars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
Editor edit = parametres.edit();
edit.clear();
//Global.Maj = "maj"
TextView maj=(TextView) findViewById(R.id.datemaj);
edit.putString("gimli", Global.MAJ);
edit.commit();
maj.setText(Global.MAJ);
}
public void loadvars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
TextView maj=(TextView) findViewById(R.id.datemaj);
String Smaj = parametres.getString("gimli", Global.MAJ);
maj.setText(Smaj);
}
}

Use onCreate() method to load your data and onDestroy() method to save data:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadvars();
}
#Override
protected void onDestroy() {
super.onDestroy();
savevars();
}
You can use too: onResume() with onPause() method but this two method are reserved for process (start process in onResume() method, stop process in onPause() method)

You are calling the savevars() method each time your activity is created. That means for sure every time your application starts.
In this method you are writing always the same value in the preferences:
edit.putString("gimli", Global.MAJ);
edit.commit();

Related

How can I display info from sharedPreferences after the activity or app gets closed?

I have put some information that I want to be displayed even after my app or activity gets closed. I have a function display and if I call it in onCreate() or onStart() my app crashes.
public void display() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
mText1.setText(sharedPref.getString("mText1", ""));
}
Here's how the data gets saved
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
This is the line that does not fit in the picture:
java.lang.RuntimeException: Unable to start activity ComponentInfo{corina_holom.com.medplannerapp/corina_holom.com.medplannerapp.Reminder}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This is my first time programming in java and android studio and I'm having trouble finding tutorials that help. I'm not sure how I should change this or if I should use onStart()
This is the Code from the activity in which I want the info displayed:
public class Reminder extends AppCompatActivity {
public TextView mText1, mText2, mText3;
private EditText addMed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
defineButtons();
}
public void defineButtons() {
findViewById(R.id.mB1).setOnClickListener(buttonClickListener);
findViewById(R.id.mB2).setOnClickListener(buttonClickListener);
//findViewById(R.id.mB3).setOnClickListener(buttonClickListener);
}
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.mB1:
addMed = (EditText) findViewById(R.id.addMed);
mText1 = (TextView) findViewById(R.id.mText1);
mText1.setText(addMed.getText());
savemMed1();
break;
case R.id.mB2:
addMed = (EditText) findViewById(R.id.addMed);
mText2 = (TextView) findViewById(R.id.mText2);
mText2.setText(addMed.getText());
break;
}
}
};
public void savemMed1() {
SharedPreferences sharedPref = getSharedPreferences("MedInfo", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mText1", addMed.getText().toString());
editor.apply();
Toast.makeText(this, "Added", Toast.LENGTH_LONG).show();
}
}
The problem is that by the time you use setText your textview is not initialised. Make sure you do findViewById before you do setText. The best way is to do it first thing in onCreate. And of course make sure that the id is the same as in the layout.

On Preference change listener - after click run twice

I have in my app preference activity with EditTextPreference and I added this, to detect, when the text in edittext is changed. All works, except for that, the code runs always twice... I tryed to add System.out.println("now"); to proove if the code runs twice, and it writes "now" two times...
Here is the code:
SharedPreferences.OnSharedPreferenceChangeListener myPrefListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.admin_activity);
myPrefListner = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
switch(key) {
case "prefAddUser":
EditTextPreference connectionPref = (EditTextPreference) findPreference(key);
String jmeno = connectionPref.getText();
System.out.println("now");
add_user(jmeno); //custom method to add user to MySQL database
Toast.makeText(getApplicationContext(), "add user", Toast.LENGTH_SHORT).show();
connectionPref.setText("");
break;
}
}
};
}
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(myPrefListner);
}
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(myPrefListner);
}
I don't know what to do with this weird problem...
What should I do?
Calling OnSharedPreferenceChangeListener in anonymous class makes it become the target of garbage collection.
As soon as you leave the current scope and can cause unregisterOnSharedPreferenceChangeListener() to be call on a null context.
Implement it in the class scope like this:
public class SettingsActivity extends PreferenceActivity
implements OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType";
...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
Read the next tutorials for further explanation:
1. Good So answer on the subject
2. Official documentation here

Get attributes from SharedPreferences in android

This is my MainActivity.java where I instanciate static SharedPreferences and it's editor:
public static SharedPreferences settings;
public static SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
editor = settings.edit();
Then I make an AsyncTask call to another java class where I try to store a token in onPostExecute method to this SharedPreferences.
#Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
}
This Log.d() method outprints the token value in the console, which is "OK". But then I start an acitivity Next.java where I try to get this token on a screen using this:
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String auth_token_string = MainActivity.settings.getString("auth_token", "Nothing");
text = (TextView) findViewById(R.id.logintxt);
text.setText(auth_token_string);
And the result on the screen is the default String "Nothing".
What am I doing wrong here? ...and is this the right way to use SharedPreferences? I got this idea here in this topic.
EDIT:
Code from AuthorizeActivity.java where I call the asyncTask:
public void getToken(String code){
AsyncTask<String, Void, String> tsk = new Api().execute(code);
Intent i = new Intent(this.getBaseContext(), Next.class);
dialog.dismiss();
startActivity(i);
}
Your settings variable is static, it's initialised in onCreate method of MainActivity when you access settings in Next.java it's not initialised yet.
You have access to SharedPreferences in Next.java (it's shared).
EDIT :
add a update method in MainActivity :
public void update() {
Intent i = new Intent(this.getBaseContext(), Next.class);
startActivity(i);
}
and your postExecute should look like this :
#Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
((MainActivity) context).update();
}
Do not use the settings from MainActivity, create a new SharedPrefs instance and call getString method.
Edit: I've created an example of how this should be handled on GitHub
Firstly, I would advise that you don't make your members static; they don't need to be static.
On your Next.class (Perhaps you should rename this, it's not clear what it does), you just need to get a handle on the shared preferences again with your new context:
PreferenceManager.getDefaultSharedPreferences(this);
Please note, there's a difference between getDefaultSharedPreferences and getSharedPreferences - use whichever you think it most appropriate.

How call method from second activitty and return value

I have two activity, first on activity "LoginActivity",and second activity "student_ activity".
Please till me how call method "call" from second activity and return value bool to first activity for know user if id and password correct or not correct.
First activity get id and password from "edittext" then send id and password to method in second activity for sure from data from server.
code first activity is :
public class LoginActivity extends Activity{
EditText EdtId;
EditText EdtPassword;
Button btn1;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
EdtId=(EditText)findViewById(R.id.IdStudent);
EdtPassword=(EditText)findViewById(R.id.PasswordStudent);
btn1=(Button)findViewById(R.id.btnLogin);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createLoginSession(Integer.parseInt(EdtId.getText().toString()),EdtPassword.getText().toString());
//here call second activity for sure from data
Intent intent = new Intent(LoginActivity.this,tofi.android.Student_Activity.class);
startActivity(intent);
finish();
startActivity(new Intent(LoginActivity.this,com.jcxavier.widget.test.BadgeButtonTestActivity.class));
}
});
}
//this method store data in SharedPreferences for get this data in second activity
public void createLoginSession(int id, String password){
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("id", id);
editor.putString("password", password);
editor.commit();
}
}
code second activity is:
public class Student_Activity {
SharedPreferences prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.program_student);
NewsLoader call = new NewsLoader();
call.execute(this, true);
}
private Context context;
private boolean pullFromServer = false;
class NewsLoader extends AsyncTask<Object, Void, List<student>> {
private Context context;
private boolean pullFromServer = false;
protected List<student> doInBackground(Object... params) {
context = (Context) params[0];
pullFromServer = (Boolean) params[1];
dataSource.open();
if (pullFromServer) {
//get attribute from SharedPreferences
int id = prefs.getInt("id", 24);
String password = prefs.getString("password","wce");
// studentHandler class for sure password content method call for send to server and //return value if correct or not correct and return value type bool.
bool s;
s = StudentHandler.getInstance().call(context,id,password);
}
}
}
1. Call startActivityForResult() (documentation) and override onActivityResult() (documentation) in the first activity.
2. In the second activity perform whatever validation you need to do (this could also be done in the first activity by passing the data via an Intent) and call setResult(int resultCode, Intent data) (documentation) and then finish(); from the second activity.
If using startActivityForResult() is not feasible for your situation, then you can simply use setResult() and startActivity(), pass any data you need via an Intent, and validate it in onActivityResult().
I just skimmed over this, but here's an example of it in action.

How to Change the Text of a button using EditText on Android

I am trying to use an EditText one one Activity to change the text of a button on another. I know I have to go through the SharedPreferences, and although this is where I am stuck.
Activity with the Button:
protected void onResume() {
super.onResume();
class1.setText(this.getButtonText());
}
public String getButtonText()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String buttonText = prefs.getString("ButtonText", "Default button text"); // I am not sure how to get the button text here. This is what someone was trying to have me do?
return buttonText;
}
This is my Activity that has the EditText and the button to go back to the activity with the button:
public class EditClass1 extends Activity implements OnClickListener{
Button class1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editclass1);
SettingButtons();
class1.setOnClickListener(this);
}
private void SettingButtons() {
// TODO Auto-generated method stub
class1 = (Button) findViewById(R.id.edittoclass1);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.edittoclass1:
startActivity(new Intent("com.clayton.calendar.TOCLASS"));
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("ButtonText", // This is not working
((TextView)findViewById(R.id.edittoclass1)).getText().toString());
editor.commit();
}
}
Try this:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
EditText text = (EditText)findViewById(R.id.Setclass);
String text2 = text;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("ButtonText", // This is not working
((TextView)findViewById(R.id.edittoclass1)).getText().toString());
editor.commit();
}
Ignoring the shares preferences for a moment, why not just have a public static String variable in the class containing the button.
public static String buttonText = "somthing";
When in the class containing the edit text you can call in an event handler which listens for changes to the edit text or an event handler that is fired when a button is pressed.
ButtonActivity.buttonText = text.getText();
Then in the onResume() method of the activity containing the button
button.setText(buttonText);
Try this it might be a simpler way of doing what you want. Remember when declaring the buttonText variable make sure you remember to use the static keyword. Without it you will need a direct reference to the object, with the static keyword, you can just refer to the required class. However, being static button Text will be the same for all instances of the button containing activity. If you only ever intend on having one instance of the activity this is the solution for you. If not then you have to get a little more creative.

Categories

Resources