2014-09-02 56 views
0

我試圖從正常Activity的BroadcastReceiver類的EditText中獲取一個字符串。 SharedPreferences讓我感到困惑,這就是我現在設置的方式。它的作用是保存字符串和全部,但我無法檢索它。在BroadcastReceiver類中檢索字符串SharedPreference

@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(); 
} 

我只是想檢索字符串,如果你把它分配給我的onReceieve()方法中的另一串在我的廣播類可以提供幫助,並解釋說那會很棒。謝謝。

回答

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然後通過有上下文對象。