Using shared preferences in between activities

前端 未结 3 1305
天涯浪人
天涯浪人 2021-02-04 21:57

I am trying to share a shared preference in between two activities of my project, but for some reason I am not able to pass the data.

I have Activity A which reads the s

相关标签:
3条回答
  • 2021-02-04 22:26

    You can do simpler - in any activity:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    

    You will have the same prefs this way from anywhere.

    http://developer.android.com/reference/android/preference/PreferenceManager.html#getDefaultSharedPreferences(android.content.Context)

    0 讨论(0)
  • 2021-02-04 22:34

    To read shared datas in the second activity , change the mode :

    from MODE_WORLD_WRITEABLE to MODE_WORLD_READABLE

     SharedPreferences sharedPref = getSharedPreferences("myPrefs",Context.MODE_WORLD_READABLE);
      String theme=sharedPref.getString("theme","blue");
    
    0 讨论(0)
  • 2021-02-04 22:36
    // try this way
    1. define SharedPreferences variable in SmartApplication class  also define read and write method SharedPreferences
    
    private SharedPreferences sharedPreferences;
    
     @Override
     public void onCreate() {
            super.onCreate();
    
     sharedPreferences = getSharedPreferences("yourAppName", MODE_PRIVATE);
    
     } 
    
    public void writeSharedPreferences(String key, String value) {
            SharedPreferences.Editor editor = readSharedPreferences().edit();
            editor.putString(key, value);
            editor.commit();
    }
    // write Shared Preferences 
    public void writeSharedPreferences(String key, boolean value) {
            SharedPreferences.Editor editor = readSharedPreferences().edit();
            editor.putBoolean(key, value);
            editor.commit();
    }
    // write Shared Preferences 
    public void writeSharedPreferences(String key, float value) {
            SharedPreferences.Editor editor = readSharedPreferences().edit();
            editor.putFloat(key, value);
            editor.commit();
    }
    
    public void writeSharedPreferences(String key, int value) {
            SharedPreferences.Editor editor = readSharedPreferences().edit();
            editor.putInt(key, value);
            editor.commit();
    }
    
    // write Shared Preferences 
    public void writeSharedPreferences(String key, long value) {
            SharedPreferences.Editor editor = readSharedPreferences().edit();
            editor.putLong(key, value);
            editor.commit();
    }
    
    // get Shared Preferences 
    public SharedPreferences readSharedPreferences() {
            return sharedPreferences;
    }
    
    0 讨论(0)
提交回复
热议问题