Why unknown variable error trying to save app data? - android

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.

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);

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 data in shared preferences not working

I am working on android shared preferences. My requirement is when app opens, an edittextbox with submit button will
come. When submit button is clicked it will move to second page. Here, after closing the app and if I open again then
the second page should open directly. I am using auto login functionality. So for that I used shared preferences concept. But my code is not working. When I
am opening the app again it is displaying the first page only.
Please help me with this issue.
My Code:
Page1:
private SharedPreferences mPreferences;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.edt);
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
}
public void submit(View v)
{
userphnnumber = edt.getText().toString().trim();
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("UserName", userphnnumber);
editor.commit();
}
Page2:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
mPreferences = getSharedPreferences("CurrentUser", 0);
myVal = mPreferences.getString("UserName", null);
System.out.println("the myval" + myVal);
}
Inside onCreate of the first 'page', do this.
mPreferences = getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
String myVal = mPreferences.getString("UserName", null);
if(myVal != null) {
startActivity(new Intent(this, SecondPage.class));
}
Inside the submit function, do this.
String userphnnumber = edt.getText().toString().trim();
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("UserName", userphnnumber);
editor.commit();
Hope this helps.

Shared preferences not working correctly

I'm trying to store some strings in a shared preference file and then retrieve them in another activity, except it doesn't seem to be working. Any guidance as to where im going wrong would be much appreciated. Many thanks.
public void save(View view) {
SavePreferences("name", nameS);
SavePreferences("current", currentS);
SavePreferences("goal", goalS);
SavePreferences("CurrentBmi", cBmiS);
SavePreferences("goalBmi", gBmiS);
Toast.makeText(this, "profile Saved", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public class Progress extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
String test = sharedPreferences.getString("name", "");
String test2 = sharedPreferences.getString("current", "");
TextView testy = (TextView) findViewById(R.id.textView1);
testy.setText(test);
TextView testz = (TextView) findViewById(R.id.test2);
testz.setText(test2);
}
With the code you have you are limiting the access of sharedpreferences to activity(context) level.
Values saved in activity Activity MainActivity will not be available in activity Progress since you are using getPreferences(MODE_PRIVATE);
Change this to
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
or
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
getPreferences:
public SharedPreferences getPreferences (int mode)
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

Categories

Resources