Search code examples
androidsharedpreferencespreferencespreferenceactivity

Create multiple preferences android


I´m getting desperate when trying to create my second preference Activity of my App. I have previously implemented a SharedPreferences, which works pretty good, but now I am trying to create a second preference activity to work on a specific Activity, but I cannot make it work properly. What it is basically happening is that, no matter which color I select, it always giving me the "default value" = 1, as if the preference file that it is checking would not exist. Here is my code of the preferenceActivity:

public class PreferenciasGrafica extends PreferenceActivity {


@Override protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      addPreferencesFromResource(R.xml.preferencias_grafica);

   }

public void onBackPressed(){
    //Preferencias
             //PreferenceManager.getDefaultSharedPreferences(this);//Carga archivo preferencias
            SharedPreferences appPrefs2 =this.getPreferences(MODE_PRIVATE);
            int colore=Integer.parseInt(appPrefs2.getString("color","1"));//Pasa a samples las prefer. elegidas
            //startActivity(new Intent(this, Main.class));
            switch(colore){
            case 1:
                colore=Color.RED;
            break;
            case 2:
                colore=Color.BLUE;
            break;
            case 3:
                colore=Color.GREEN;
            break;
            }
            Grafica grafica=new Grafica(colore);
            //grafica.color=color;

            startActivity(new Intent(this, Grafica.class));

            finish();

  }
}

This is the xml of the preference file:

    <PreferenceScreen 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:key="preferencias_principal" > 

  <ListPreference 
   android:key="color" 
   android:title="Color de la gráfica" 
   android:summary="Selecciona el color a del gráfico" 
   android:entries="@array/colores"
   android:entryValues="@array/valores" 
   android:defaultValue="0"/> 

  </PreferenceScreen>

And this is the array file:

 <resources>
  <string-array name="colores"> 
     <item>Rojo</item> 
     <item>Azul</item> 
     <item>Verde</item>
  </string-array>
  <string-array name="valores"> 
     <item>1</item> 
     <item>2</item> 
     <item>3</item>
   </string-array>
</resources>

Does anybody know what a I doing wrong here? I´m getting totally wasted with this!

EDIT: Problem solved!! just change it and make it like this:

SharedPreferences appPrefs2 =PreferenceManager.getDefaultSharedPreferences(this);


Solution

  • Try using

      PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    

    When you're acquiring the SharedPreferences.