How save state of preferenceActivity on Android - android

I'm trying to develop an application that has a PreferenceActivity two CheckBoxPreference and MainActivity . I want that when you selections and some of them go out to MainActivity , saved, and again she selected only see you 've selected first. I tried all things but nothing work. Help me!!
My code:
public class Preferencias extends PreferenceActivity implements OnPreferenceChangeListener{
Boolean bmusica=true,bvibracion=true;
SharedPreferences prefs;
CheckBoxPreference chMusica,chVibr;
SharedPreferences.Editor gg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencias);
if(savedInstanceState!=null){
chMusica.setChecked(savedInstanceState.getBoolean("estadoMusica"));
bmusica=savedInstanceState.getBoolean("valorMusica");
chVibr.setChecked(savedInstanceState.getBoolean("estadoVibracion"));
bvibracion=savedInstanceState.getBoolean("valorVibr");
}else{
prefs =this.getPreferenceManager().getSharedPreferences();
gg= prefs.edit();
chMusica = (CheckBoxPreference) findPreference("musica");
chVibr = (CheckBoxPreference) findPreference("vibracion");
chMusica.setChecked(true);
chVibr.setChecked(true);
}
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
if(chMusica.isChecked()){
gg.putBoolean("musica", true);
bmusica=true;
}else{
gg.putBoolean("musica", false);
bmusica=false;
}
if(chVibr.isChecked()){
gg.putBoolean("vibracion", true);
bvibracion=true;
}else{
gg.putBoolean("vibracion", false);
bvibracion=false;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("estadoMusica", chMusica.isChecked());
outState.putBoolean("valorMusica", bmusica);
outState.putBoolean("estadoVibracion", chVibr.isChecked());
outState.putBoolean("valorVibr", bvibracion);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
chMusica.setChecked(state.getBoolean("estadoMusica"));
chVibr.setChecked(state.getBoolean("estadoVibracion"));
bmusica=state.getBoolean("valorMusica");
bvibracion=state.getBoolean("valorVibr");
}
And my MainActivity:
public class MainActivity extends Activity {
Button jugar, preferencias, acercade, maximo, salir;
Vibrator v;
Boolean isVibrar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_land);
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
jugar = (Button) findViewById(R.id.botonJugar);
preferencias = (Button) findViewById(R.id.botonOpciones);
acercade = (Button) findViewById(R.id.botonAcercaDe);
maximo = (Button) findViewById(R.id.botonPuntuaciones);
salir = (Button) findViewById(R.id.botonSalir);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
isVibrar = sharedPref.getBoolean("vibracion", true);
public void preferencias(View view) {
if (isVibrar==true) {
v.vibrate(200);
}
Intent i = new Intent(MainActivity.this, Preferencias.class);
startActivity(i);
}

Related

registerOnSharedPreferenceChangeListener not working

I'm trying to update my app background color by changing the preferences but the method onSharedPreferenceChanged is never reached. The preferences are changed successfully, but I the listener doesn't work properly:
MainActivity:
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView mRecyclerView;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, MyPreferenceActivity.class);
startActivity(intent);
return true;
case R.id.action_favorite:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("color")) {
String color = sharedPreferences.getString("color", "3");
int colorId = Integer.valueOf(color);
// Alterar background
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) (findViewById(android.R.id.content))).getChildAt(0);
if (colorId == 1) {
viewGroup.setBackgroundColor(Color.WHITE);
} else if (colorId == 2) {
viewGroup.setBackgroundColor(Color.YELLOW);
} else if (colorId == 3) {
viewGroup.setBackgroundColor(Color.RED);
}
}
}
}
MyPreferenceActivity:
public class MyPreferenceActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
The method onSharedPreferenceChanged is never called, the only way I got it to work was implement the method OnSharedPreferenceChangeListener directly inside the onResume, but sometimes it works fine, sometimes it doesn't and the method is not reached.
The Shared preference registerOnSharedPreferenceChangeListener is valid only when MainActivity is in foreground else that will be unregistered in onPause.
When you are creating a PreferenceActivity named MyPreferenceActivity, the onPause() of MainActivity is called, where the listener is getting unregistered.
One work around could be, unregister from the listener onStop() instead onPause() in MainActivity.
MainActivity.java
#Override
public void onStart() {
super.onStart();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}

Get value of a checkbox in another fragment

I would like to get the value of my checkbox that is in my confiFragment and get that value in MainActivity .
The configFragment is related to the confiActivity.
I tried this method but i get a null ; can someone help me please?
This is my fragment:
public class configFragment extends android.support.v4.app.Fragment {
CheckBox check;
configActivity cmt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.config_layout, container, false);
check = (CheckBox) rootView.findViewById(R.id.checkbox1);
TextView text1=(TextView) rootView.findViewById(R.id.text1);
text1.setText("hello ");
cmt=(configActivity) getActivity();
check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(check.isChecked()){
Log.d("status","checked");
//check.setChecked(true);
cmt.checking=true;
}else{
Log.d("status","not checked");
//check.setChecked(false);
cmt.checking=false;
}
}
});
//cmt.checking=load();
// check();
return rootView;
}
#Override
public void onPause() {
super.onPause();
save(check.isChecked());
}
#Override
public void onResume() {
super.onResume();
check.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
public boolean load() {
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", check.isChecked());
}
}
and this is the activity of this fragment:
public class configActivity extends SingleFragmentActivity {
public Boolean checking;
#Override
protected Fragment createFragment()
{
return new configFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configFragment cf=new configFragment();
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
checking=sharedPreferences.getBoolean("check", cf.check.isChecked());
}
}
and this is my main activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView hello=(TextView) findViewById(R.id.hello);
Button but1=(Button) findViewById(R.id.button1);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,configActivity.class);
startActivity(i);
}
});
hello.setText("Hello world");
configActivity config=new configActivity();
Log.d("status of checking",config.checking.toString());
if(config.checking=true){
Log.d("checked","true");
}else{
Log.d("not checked","false");
}
}
You using a wrong way to create communication between fragment to activity.
The correct way to communicate between your activity and fragments is using interfaces.
Define an interface in your configFragment and then implement that in your activity.
And do what ever you want.
Refer this
And if you want to pass this is to your main activity set a Result to main activity from your configActivity. Refer this one for starting activity for result
And also go through this link. Ho to use fragment

Save the state of a ToggleButton using SharedPreferences

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

How to store the array of string in shared preferences? [closed]

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

How use SharedPreferences to change the font

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

Categories

Resources