Iam not able to store values in shared prefernces.As soon as the activity is closed the no value remains saved. On starting the activity again the ids used to store and fetch data have null values.
Heres is my code.i am not attaching the layout as they will be of no significance.
As I am new to android.There might be some simple thing i a missing.Please help
public class enter_db extends AppCompatActivity
{
String field;
EditText usrtext,idtxt,bananatxt,coconuttxt,timbertxt,bambootxt,goldtxt,garage1txt,garage2txt,garage3txt,garage4txt,garage5txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_entry);
usrtext=(EditText)findViewById(R.id.username);
idtxt=(EditText)findViewById(R.id.UserID);
bananatxt=(EditText)findViewById(R.id.banana_count);
coconuttxt=(EditText)findViewById(R.id.coconut_count);
bambootxt=(EditText)findViewById(R.id.banana_count);
timbertxt=(EditText)findViewById(R.id.Timber_count);
goldtxt=(EditText)findViewById(R.id.gold_count);
garage1txt=(EditText)findViewById(R.id.garage_1);
garage2txt=(EditText)findViewById(R.id.garage_2);
garage3txt=(EditText)findViewById(R.id.garage_3);
garage4txt=(EditText)findViewById(R.id.garage_4);
garage5txt=(EditText)findViewById(R.id.garage_5);
SharedPreferences pref=getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
if(pref.getString("Username",null)!="")
{
field=pref.getString("Username",null);
usrtext.setHint("Username"+field);
}
if(pref.getString("UserID",null)!=null)
{
field=pref.getString("UserID",null);
idtxt.setHint("UserID: "+field);
}
if(pref.getString("Banana",null)!=null)
{
field=pref.getString("Banana",null);
bananatxt.setHint("Banana: "+field);
}
if(pref.getString("Coconut",null)!=null)
{
field=pref.getString("Coconut",null);
coconuttxt.setHint("Cococnut: "+field);
}
if(pref.getString("Timber",null)!=null)
{
field=pref.getString("Timber",null);
timbertxt.setHint("Timber: "+field);
}
if(pref.getString("Bamboo",null)!=null)
{
field=pref.getString("Bamboo",null);
bambootxt.setHint("Bamboo"+field);
}
if(pref.getString("Gold",null)!=null)
{
field=pref.getString("Gold",null);
goldtxt.setHint("Gold: "+field);
}
if(pref.getString("Garage1",null)!=null)
{
field=pref.getString("Garage1",null);
garage1txt.setHint("Garage1 :"+field);
}
if(pref.getString("Garage2",null)!=null)
{
field=pref.getString("Garage2",null);
garage2txt.setHint("Garage2 :"+field);
}
if(pref.getString("Garage3",null)!=null)
{
field=pref.getString("Garage3",null);
garage3txt.setHint("Garage3 :"+field);
}
if(pref.getString("Garage4",null)!=null)
{
field=pref.getString("Garage4",null);
garage4txt.setHint("Garage4 :"+field);
}
if(pref.getString("Garage5",null)!=null)
{
field=pref.getString("Garage5",null);
garage5txt.setHint("Garage5 :"+field);
}
editor.putString("Username",usrtext.getText().toString());
editor.putString("UserID",idtxt.getText().toString());
editor.putString("Banana",bananatxt.getText().toString());
editor.putString("Coconut",coconuttxt.getText().toString());
editor.putString("Timber",timbertxt.getText().toString());
editor.putString("Bamboo",bambootxt.getText().toString());
editor.putString("Gold",goldtxt.getText().toString());
editor.putString("Garage1",garage1txt.getText().toString());
editor.putString("Garage2",garage2txt.getText().toString());
editor.putString("Garage3",garage3txt.getText().toString());
editor.putString("Garage4",garage4txt.getText().toString());
editor.putString("Garage5",garage5txt.getText().toString());
ImageButton ok=(ImageButton)findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v)
{
editor.apply();
Intent i=new Intent(getApplicationContext(),Garage.class);
startActivity(i);
}
});
}
}
U missed the apply() / commit() to save chanegs.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply(); // editor.commit()
apply() is faster and async while commit() is synchronous.
Save value in shared preferences:
SharedPreferences settings =getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor. putBoolean(key, value);
editor.commit();
get value from shared preferences:
SharedPreferences settings = getSharedPreferences("AppName", 0);
String value=settings.getString(key, "");
boolean value=settings.getBoolean(key,false);
As in above code you are not saving value of edit text in shared preference on button click,try this way
ok.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v)
{
editor.putString("Username",usrtext.getText().toString());
editor.putString("UserID",idtxt.getText().toString());
editor.putString("Banana",bananatxt.getText().toString());
editor.putString("Coconut",coconuttxt.getText().toString());
editor.putString("Timber",timbertxt.getText().toString());
editor.putString("Bamboo",bambootxt.getText().toString());
editor.putString("Gold",goldtxt.getText().toString());
editor.putString("Garage1",garage1txt.getText().toString());
editor.putString("Garage2",garage2txt.getText().toString());
editor.putString("Garage3",garage3txt.getText().toString());
editor.putString("Garage4",garage4txt.getText().toString());
editor.putString("Garage5",garage5txt.getText().toString());
editor.apply();
Intent i=new Intent(getApplicationContext(),Garage.class);
startActivity(i);
}
});
editor.putString("Garage5",garage5txt.getText().toString());
editor.commit();
Related
I have an issue where I am trying to change the foreground of a Button upon a click event. The foreground only changes after the first click.
public void muteSoundClick(View view){
playSound = preferences.getBoolean("playSound", true);
if (playSound) {
view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
editor.putBoolean("playSound", false);
editor.apply();
}
else {
view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
editor.putBoolean("playSound", true);
editor.apply();
}
}
I retrieve a variable from the android SharedPrefernces, which i use to determine which foreground to use.
First you need to check playsound at the start of the activity so that the button itself would get what you are saving the first time so you need something like this :
playSound = preferences.getBoolean("playSound", true);
if(playSound)
button.setForeground(getDrawable(R.drawable.foreground_padding_mute));
else
button.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
Then you can handle the clicks using the same method you have posted in your question
here is a sample example activity to sum it up :
public class SimpleActivity extends AppCompatActivity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
boolean playSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor= PreferenceManager.getDefaultSharedPreferences(this).edit();
Button button = findViewById(YourButtonID);
playSound = preferences.getBoolean("playSound", true);
if(playSound)
button.setForeground(getDrawable(R.drawable.foreground_padding_mute));
else
button.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
}
public void muteSoundClick(View view){
playSound = preferences.getBoolean("playSound", true);
if (playSound) {
view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
editor.putBoolean("playSound", false);
editor.apply();
}
else {
view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
editor.putBoolean("playSound", true);
editor.apply();
}
}
}
It's seems that you aren't really editing the preferences. Like this.
SharedPreferences.Editor editor;
public void muteSoundClick(View view){
playSound = preferences.getBoolean("playSound", true);
if (playSound) {
editor = sharedPreferences.edit();
view.setForeground(getDrawable(R.drawable.foreground_padding_unmute));
editor.putBoolean("playSound", false);
editor.commit();
}
else {
view.setForeground(getDrawable(R.drawable.foreground_padding_mute));
editor.putBoolean("playSound", true);
editor.apply();
}
}
I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}
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();
I have a listview populated from the database, and a checkbox for each row. Using putExtras to pass values to a TextView to another Activity. Now when you restart the app I want to display in TextView the last value selected with checkboxes. I need SharedPreferences or is there a method? Thanks
Save your checkbox in preference as below:
//method to load the sharedpreferences.
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);
String name = sharedPreferences.getString("storedName", "YourName");
if (checkBoxValue) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
textview.setText(name);
}
//store boolean value of checkbox in sharedpreferences.
private void savePreferences(String key, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
//store the string sharedpreference.
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
savePreferences("CheckBox_Value", checkBox.isChecked());
savePreferences("storedName", textview.getText().toString());
}
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.