简体   繁体   中英

Using a SharedPreferences class in Android?

I made a SharedPreferences class so that the rest of my Activitys could use on line to get preferences.

 public class SPAdapter extends Activity {

    public final String preferenceSettings = "STORAGE";

        // Default value if row does not exist in preference
     public static final String rowExistence = "Row did not exist";

public String prefGet(String preferenceName, String rowId) {
    SharedPreferences preferenceObject = getSharedPreferences(preferenceName, MODE_PRIVATE);
    String value = preferenceObject.getString(rowId, rowExistence);
    return value;
}

I use this method like so:

    public class Splash extends Activity {

     private SPAdapter spObject;
     public String rowNumber(0);
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.splash);

         spObject.prefGet(spObject.preferenceSettings,
            rowNumber);
}

However, whenever I try to use this method, the application crashes showing an error about context. Can anybody give me a hand getting this to work?

The problem with this approach is that you extend SPAdapter from Activity and don't initialize it properly, it doesn't have a proper Context set, so it can't get a SharedPreferences instance from the framework through it. But anyways, this is not the way you should do things in Android, you're not the one who instantiates new Activity objects, it's supposed to be the framework's job. Here's 2 ways to get this working:

  • Extend your Splash activity from SPAdapter.

  • Don't extend SPAdapter from Activity, just pass a reference for a Context object and get the SharedPreferences instance using that. Something like this:

    public class SPAdapter { public final String preferenceSettings = "STORAGE";

     // Default value if row does not exist in preference public static final String rowExistence = "Row did not exist"; private Context ctx; public SPAdapter(Context ctx){ this.ctx = ctx; } public String prefGet(String preferenceName, String rowId) { SharedPreferences preferenceObject = ctx.getSharedPreferences( preferenceName, Context.MODE_PRIVATE); String value = preferenceObject.getString(rowId, rowExistence); return value; } 

    }

Use it like this:

public class FsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SPAdapter sa = new SPAdapter(getApplicationContext());
        sa.prefGet("", "");
    }
}

The first solution seems a bit better imo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM