SharedPreferences from different activity

后端 未结 2 1700
星月不相逢
星月不相逢 2020-12-23 17:38

I load from activity A the SharedPreferences in following way:

private void SavePreferences(String key, String value){
    SharedPreferences sharedPreference         


        
相关标签:
2条回答
  • 2020-12-23 18:09

    use getApplicationContext() instead of this in both Activities as:

    In activity A the SharedPreferences in following way:

     private void SavePreferences(String key, String value){
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, value);
            editor.commit();
            Intent sd=new Intent(this,Secongtess.class);
            startActivity(sd);
           }
    

    and in Activity B get Value as:

     private void LoadPreferences(){   
           SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
         String  data = sharedPreferences.getString("name", "08:00") ;
         Toast.makeText(this,data, Toast.LENGTH_LONG).show();
       }
    

    because as doc says:

    getDefaultSharedPreferences(Context context) :

    Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

    0 讨论(0)
  • 2020-12-23 18:19

    To store values in shared preferences:

    SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this);
      SharedPreferences.Editor editor=preferences.edit();
      editor.putString("Name","Harneet");
      editor.commit();
    

    To retrieve values from shared preferences:

    SharedPreferences preferences==PreferenceManager.getDefaultSharedPreferences(this);
      String name=preferences.getString("Name","");
      if(!name.equalsIgnoreCase(""))
      {
        name=name+"  Sethi";  /* Edit the value here*/
      }
    

    To edit data from sharedpreference

    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
     editor.putString("text", mSaved.getText().toString());
     editor.putInt("selection-start", mSaved.getSelectionStart());
     editor.putInt("selection-end", mSaved.getSelectionEnd());
     editor.commit();
    

    To retrieve data from shared preference

    SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
    String restoredText = prefs.getString("text", null);
    if (restoredText != null) 
    {
      //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
      int selectionStart = prefs.getInt("selection-start", -1);
      int selectionEnd = prefs.getInt("selection-end", -1);
      /*if (selectionStart != -1 && selectionEnd != -1)
      {
         mSaved.setSelection(selectionStart, selectionEnd);
      }*/
    }
    
    0 讨论(0)
提交回复
热议问题