我使用SharedPreferences pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
保存配置并将其加载到类扩展服务中。
但是当我尝试获取config的值时出现错误,错误如:
无法实例化服务kr.co.composer.callrecord.recorder.CallRecordService:java.lang.NullPointerException
在线:
SharedPreferences
在布局final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
中,我保存了一个EditText:
Configuration
在另一个类中,我希望通过以下代码获取此值:
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
serverUrl.setText(prefs.getString("autoSave", ""));
serverUrl.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
}
@Override
public void afterTextChanged(Editable s)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
});
答案 0 :(得分:1)
你不能在onCreate()之前调用getApplicationContext()。相反,你可以这样做:
public class CallRecordService extends Service {
@Override
public void onCreate() {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
serverURL = sp.getString("autoSave", "");
}
}
答案 1 :(得分:1)
<强>不强>
public class CallRecordService extends Service {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Call this in your onCreate() section .
@Override
public void onCreate() {
serverURL =(mSharedPreference.getString("autoSave", ""));
}
}
<强>不要强>
public class CallRecordService extends Service {
final SharedPreferences mSharedPreference=
@Override
public void onCreate() {
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // You can pass context here
serverURL =(mSharedPreference.getString("autoSave", ""));
}
}