Search code examples
androidbuttonpreferencesadapter

How can i get my Preferences in a other class than the main (Android)?


My main class look like this:

public class Soundboard extends Activity 
{ 
    SharedPreferences preferences;

 @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 


     // Initialize preferences
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

}

private void loadButtonText() {
        startPlayerBtn.setText(preferences.getString("buttontext1", "n/a"));

}

This i workning but I have change my code a litte bit with a ButtonAdapter (extra class) but cant find my Preferences there. I you look att the link I have an array that look like this in ButtonAdapter.java:

 public String[] filesnames = {
             "Text button 1",
            "Text button 2",  
            "Text button 3"
            };

How can I but my settings into the array? Something like this that is not working:

     public String[] filesnames = {
            preferences.getString("buttontext1", "n/a",
            preferences.getString("buttontext2", "n/a",  
            preferences.getString("buttontext3", "n/a"
            };

Please help me, I am really stuck.


Solution

  • Change your constructor to look like this:

    public ButtonAdapter(Context c) {  
        preferences = PreferenceManager.getDefaultSharedPreferences(c);
        filenames = new String[] {
            preferences.getString("buttontext1", "n/a"),
            preferences.getString("buttontext2", "n/a")
        }
    }
    

    And then change how you're declaring the filenames array at the end of the class to look like this:

    public String[] filenames;