我试图从普通的Activity中获取BroadcastReceiver类中的EditText中的String。问题是SharedPreferences让我很困惑,这就是我现在设置它的方式。它可以保存字符串,但我无法检索它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
savedLocation = getSharedPreferences("location", MODE_PRIVATE);
mZipCodeET = (EditText)findViewById(R.id.edittext_area);
mZipCodeET.setText(savedLocation.getString("tag", ""));
// @param 2 is default value of the edit text
mZipCodeET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
Time time = new Time(Time.getCurrentTimezone());
time.setToNow();
mLastRefreshTV.setText("Last Refresh: " + time.format("%k:%M:%S"));
String EditTextString = mZipCodeET.getText().toString();
searchByPlaceName(EditTextString);
if(mZipCodeET.getText().length() > 0) {
makeTag(EditTextString);
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(mZipCodeET.getWindowToken(),0);
}
}
return false;
}
});
在那里调用makeTag()方法
private void makeTag(String tag){
String or = savedLocation.getString(tag, null);
SharedPreferences.Editor preferencesEditor = savedLocation.edit();
preferencesEditor.putString("tag",tag); //change this line to this
preferencesEditor.commit();
}
我只是想检索那个字符串并将其分配给我的Broadcast类中的onReceieve()方法中的另一个字符串,如果你能提供帮助的话,并解释一下它会很棒。谢谢。
答案 0 :(得分:0)
在广播接收器的onReceive方法中,接收上下文对象。您可以使用该上下文来获取sharedPreference字符串:
@Override
public void onReceive(Context context,Intent data) {
SharedPreferences shared= context.getSharedPreferences(SHARED_PREFERS_NAME,0);
String tag= shared.getString("tag",null);
}
或者,如果你为SharedPreferences创建了一个util类,那么就传递上下文对象。