如何在非Activity类中使用SharedPreferences?我尝试创建一个通用的Preferences实用程序类,并导入android.content.Context
,但Eclipse仍然不允许我使用getSharedPreferences()
。
如何在非Activity类中使用SharedPreferences?我尝试创建一个通用的Preferences实用程序类,并导入android.content.Context
,但Eclipse仍然不允许我使用getSharedPreferences()
。
SharedPreferences与上下文(Context)相关联,只能通过Context引用。
你可以将Context作为参数传递给你的类,例如在构造函数中。
在你的Activity中,可以这样做:
MyClass myClass = new MyClass(this);
我找到的解决方法是:
1-在MainActivity类中创建一个静态变量来存储上下文(即在项目中获取任何上下文之前始终启动):
public static Context contextOfApplication;
2-在该类的一个重要方法中(例如onCreate、构造函数等),使用getApplicationContext方法初始化此变量:
public void onCreate() {
contextOfApplication = getApplicationContext();
}
3-在同一个类中创建一个“getter”方法来获取这个变量(它也必须是静态的):
3-在同一类中创建一个"getter"方法以获取该变量(它也必须是静态的):
public static Context getContextOfApplication(){
return contextOfApplication;
}
4-在非活动类中通过静态调用created方法来获取上下文:
Context applicationContext = MyActivityClass.getContextOfApplication();
使用PreferenceManager类获取SharedPreferences变量:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
希望能对您有所帮助。
public static Context contextOfApplication;
是公共的和静态的,你不需要使用 getContextOfApplication()
方法来访问它。在第4步中,你只需要写成 MyActivityClass.contextOfApplication
就可以了。 - PrashanDAppPreferences.kt
文件中,并按照代码中概述的4个TODO步骤进行操作。import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.SharedPreferences
import androidx.core.content.edit
object AppPreferences {
private var sharedPreferences: SharedPreferences? = null
// TODO step 1: call `AppPreferences.setup(applicationContext)` in your MainActivity's `onCreate` method
fun setup(context: Context) {
// TODO step 2: set your app name here
sharedPreferences = context.getSharedPreferences("<YOUR_APP_NAME>.sharedprefs", MODE_PRIVATE)
}
// TODO step 4: replace these example attributes with your stored values
var heightInCentimeters: Int?
get() = Key.HEIGHT.getInt()
set(value) = Key.HEIGHT.setInt(value)
var birthdayInMilliseconds: Long?
get() = Key.BIRTHDAY.getLong()
set(value) = Key.BIRTHDAY.setLong(value)
private enum class Key {
HEIGHT, BIRTHDAY; // TODO step 3: replace these cases with your stored values keys
fun getBoolean(): Boolean? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getBoolean(name, false) else null
fun getFloat(): Float? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getFloat(name, 0f) else null
fun getInt(): Int? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getInt(name, 0) else null
fun getLong(): Long? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getLong(name, 0) else null
fun getString(): String? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getString(name, "") else null
fun setBoolean(value: Boolean?) = value?.let { sharedPreferences!!.edit { putBoolean(name, value) } } ?: remove()
fun setFloat(value: Float?) = value?.let { sharedPreferences!!.edit { putFloat(name, value) } } ?: remove()
fun setInt(value: Int?) = value?.let { sharedPreferences!!.edit { putInt(name, value) } } ?: remove()
fun setLong(value: Long?) = value?.let { sharedPreferences!!.edit { putLong(name, value) } } ?: remove()
fun setString(value: String?) = value?.let { sharedPreferences!!.edit { putString(name, value) } } ?: remove()
fun remove() = sharedPreferences!!.edit { remove(name) }
}
}
val heightInCentimeters: Int? = AppPreferences.heightInCentimeters
val heightOrDefault: Int = AppPreferences.heightInCentimeters ?: 170
为SharedPreferences设置一个值同样很容易:
AppPreferences.heightInCentimeters = 160 // sets a new value
使用静态方法在没有上下文对象的情况下使用 SharedPreference 的解释可以在这里找到:这里
OnCreate 之前在 MainActivity 中
public static SharedPreferences preferences;
preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
public class PreferenceHelper {
final public static String KEY_DEMO_NAME = "Demo Name";
public static void setName(String value) {
MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
}
public static String getName() {
return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
}
}
SharedPreferences prefs = getDefaultSharedPreferences(this);
但它不起作用。 - Jake WilsonPreferenceManager.getDefaultSharedPreferences(applicationContext);
。 - Dan S companion object {
lateinit var sharedPreferences: SharedPreferences
}
override fun onCreate(savedInstanceState: Bundle?) {
sharedPreferences = applicationContext.getSharedPreferences(
SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE
)
val myClass = MyClass(this)
class MyClass(context: Context) {
val context: Context = context
}
context.getSharedPreferences(...)
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Atiar Talukdar on 6/5/2017.
*/
public class TemporaryStorageSharedPreference {
protected final static int DEFAULT = 0;
int temp = 0;
public int readSharedPreference(Context context, String spName,String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
return temp = sharedPreferences.getInt(key,DEFAULT);
}
public void writeSharedPreference(Context context,String ammount,String spName,String key ){
SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, DEFAULT);
editor.commit();
}
}
创建SharedPreferences类
/**
* @param mContext
* @param key
* @param value
*/
public static void savePreferences(Context mContext, String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value).apply();
}
/**
* @param context
* @param keyValue
* @return
*/
public static String getPreferences(Context context, String keyValue) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString(keyValue, "");
}
/**
* @param mContext
*/
public static void removeAllSharedPreferences(Context mContext) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear().apply();
}
context
。if (context != null) {
SharedPreferences sharedPrefs = context.getSharedPreferences("YOUR.PACKAGE.NAME", MODE_PRIVATE);
}
context.getSharedPreferences();
来访问它了。 - Jake Wilson