I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.
My code looks like this below, but it will not run
public class MainActivity extends AppCompatActivity {
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
editor.putBoolean("toggleState1", toggle1.isChecked());
editor.commit();
}
private void loadPreference (Context context)
{
SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};
Thanks for the help!
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
should be INSIDE onCreate(), make it the last statement.
Also, it's easier to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Alright I have the answer for future reference. My original attempt did not use shared preferences properly. You must create a "key" and a "name" for the shared preference object. Then call it in code as follows:
public class MainActivity extends AppCompatActivity {
private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle1.setChecked(GetState());
toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
SaveState(isChecked);
}
});
}
private void SaveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
editor.commit();
}
public boolean GetState() {
return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}
}
Related
I am trying to Persist a switch button but when i leave the activity its not persisting the value.I am setting the shared preferences on the setUpBooleanDefectsSwitch function what am i missing?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpBooleanDefectsSwitch()
SharedPreferences prefs = getSharedPreferences("booleanDefects",Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener listener;
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("boolDefects")){
boolean boolDefectsSwitch = sharedPreferences.getBoolean("boolDefects",false);
System.out.println("Boolean Defects Changed");
System.out.println(boolDefectsSwitch);
booleanDefectsSwitch.setChecked(boolDefectsSwitch);
}
}
};
}
private void setUpBooleanDefectsSwitch(){
booleanDefectsSwitch = (Switch) findViewById(R.id.booleanDefects);
final SharedPreferences booleanDefectsPrefs = getSharedPreferences("booleanDefects",Context.MODE_PRIVATE);
booleanDefectsSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = booleanDefectsPrefs.edit();
editor.putBoolean("boolDefects",isChecked);
editor.commit();
}
});
}
You are looking for global reference of SharedPreferences.
try to Replace
SharedPreferences prefs = getSharedPreferences("booleanDefects", Context.MODE_PRIVATE);
SharedPreferences.OnSharedPreferenceChangeListener listener;
listener = new
with
SharedPreferences prefs = getSharedPreferences("booleanDefects", Context.MODE_PRIVATE);
prefs.registerOnSharedPreferenceChangeListener(new
or just add this at the end after the listener
prefs.registerOnSharedPreferenceChangeListener(listener);
I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.
Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Am making my first android application with the help of Udacity's tutorial(Weather App).
For setting activity, I have one text box,which holds the location value.
For example say, Texas.
But when am changing that to any other value,it's not reflecting the same in the app. Though,the value in that text box is getting changed.
In the app's SettingActivity I have following code,
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
But as of today addPreferencesFromResource is deprecated,so am not really sure how to proceed in this regard. What do I change it with?
My goal is to change the value in Location's text and when I go on my mainActivity,the weather data should reflect the changed location's data.
Thanks.
Edit:
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
private void updateWeather()
{
FetchWeatherTask weatherTask = new FetchWeatherTask();
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(getActivity());
String location=prefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
weatherTask.execute(location);
}
#Override
public void onStart()
{
super.onStart();
updateWeather();
}
Above is the code through which I update the value.
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
setupActionBar();
}
Above is the code from settingActivity. But as I said, addPreferencesFromResource is deprecated. So this part of code is not really working.
Create a separate class as below to handle all the prefs related operations, storing and restoring...
public class MyPrefs {
Context context;
SharedPreferences systemPrefs;
SharedPreferences.Editor editor;
static MyPrefs prefs;
public static final String DEFAULT_LOCATION = "DEFAULT_LOCATION";
public static final String SOME_DEFAULT_LOCATION = "London";
public static MyPrefs getInstance(Context context){
if(prefs == null){
prefs = new MyPrefs(context);
}
return prefs;
}
private MyPrefs(Context context) {
this.context = context;
this.systemPrefs = context.getSharedPreferences(Constants.USER_PREFS, Activity.MODE_PRIVATE);
this.editor = systemPrefs.edit();
}
public String getDefaultLocation(){
return systemPrefs.getString(DEFAULT_LOCATION, SOME_DEFAULT_LOCATION);
}
public void setDefaultLocation(String newLocation){
editor.putString(DEFAULT_LOCATION, newLocation);
editor.commit();
}
public void clear() {
editor.clear();
editor.commit();
}
}
And to use this in any activity class...
MyPrefs myPrefs = MyPrefs.getInstance(this);
//To get the location stored in prefs
String locationFromPrefs = myPrefs.getDefaultLocation();
//To store the location in prefs
myPrefs.setDefaultLocation("New York");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
How to store the array of String in SharedPreferences? And please give me an example code for storing array few names and retrieve it in another activity. Thanks in advance
Let me try and help you
First of all set up these class variables in the Activities you want to use SharedPreferences
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
Then to store the string values like this
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");
editor.commit(); // to persist the values between activities
and the finally to access the sharedPreferences in another activity use this
mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);
hope this helps you a lil bit.
first activity.
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putString("str"+i, name[i]);
editor.commit();
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
second activity
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
Log.d("aa", preferences.getString("str"+i, " "));
}
}
});
}
}
using set of strings
public class MainActivity extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
private String[] name = {"aa", "bb", "cc"};
Set<String> values = new HashSet<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
preferences=getSharedPreferences("testarray", MODE_PRIVATE);
for(int i=0;i<3;i++)
{
values.add(name[i]);
}
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<3;i++)
{
SharedPreferences.Editor editor=preferences.edit();
editor.putStringSet("str", values);
editor.commit();
}
startActivity(new Intent(MainActivity.this,Secondact.class));
}
});
}
}
public class Secondact extends ActionBarActivity {
private Button button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
preferences = getSharedPreferences("testarray", MODE_PRIVATE);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Set<String> values = preferences.getStringSet("str", null);
String[] name = values.toArray(new String[values.size()]);
for (int i = 0; i < values.size(); i++) {
Log.d("aa", name[i]);
}
}
});
}
}
Arrays are not supported. However you can store a Set.
SharedPreferences prefs = parent.getContext().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Set<String> values = new HashSet<String>();
values.add("value 1");
values.add("value 2");
prefs.edit().putStringSet("myKey", values).commit();
By using this code I want to change font of a textview, but the program doesn't work.
What I should do?
public class MainActivity extends Activity {
SharedPreferences shared = getSharedPreferences("Prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
public String fonts = shared.getString("fonts", "BHOMA.ttf");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setFace();
}
protected void setFace()
{
TextView txt1 = (TextView)findViewById(R.id.textView1);
Typeface face = Typeface.createFromAsset(getAssets(), "font/"+fonts+"");
txt1.setTypeface(face);
}
}
and in prefs.class
public class Prefs extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String fonts = prefs.getString("fonts", "Tahoma.ttf");
Boolean b = prefs.getBoolean("FIRSTRUN", true);
}
}