skip to Main Content

I have notification details in SharedPreferences as List<Notifications>.  I want to get the length of the list in real-time and update the UI.

Here is the code that I tried:

Future countNotifications() async {
    final prefs = await SharedPreferences.getInstance();
    final notificationsString = prefs.getString('notifications');

    List<Notifications>? notifications;

    // Decode the JSON string if it exists
    if (notificationsString != null) {
      notifications = (jsonDecode(notificationsString) as List)
          .map((e) => Notifications.fromJson(e))
          .toList();
    }

    return notifications!.length;
  }

I know this function does not give real-time data. How to make it receive data in real-time.

4

Answers


  1. Please stop reconstructing the instance of SharedPreferences all over your code. Initialize it once:

    late final SharedPreferences prefs;
    main() async {
      prefs = await SharedPreferences.getInstance();
      // rest of main, including runApp
    }
    

    And now every get is synchronous:

    final notificationsString = prefs.getString('notifications');
    

    It’s the "set" actions that are still async. But get is sync!

    Login or Signup to reply.
  2. Certainly! To fetch SharedPreferences values in real-time in Android, you can use LiveData. Here’s a concise example:

    import android.content.Context;
    import android.content.SharedPreferences;
    import androidx.lifecycle.LiveData;
    import androidx.lifecycle.MutableLiveData;
    
    public class PreferenceManager {
    
        private SharedPreferences sharedPreferences;
        private MutableLiveData<String> liveData;
    
        public PreferenceManager(Context context) {
            sharedPreferences = context.getSharedPreferences("your_pref_name", Context.MODE_PRIVATE);
            liveData = new MutableLiveData<>();
            liveData.setValue(getStoredValue());
        }
    
        public LiveData<String> getLiveData() {
            return liveData;
        }
    
        public void setValue(String value) {
            sharedPreferences.edit().putString("your_key", value).apply();
            liveData.setValue(value);
        }
    
        private String getStoredValue() {
            return sharedPreferences.getString("your_key", "default_value");
        }
    }
    

    And in your activity or fragment:

    import androidx.lifecycle.Observer;
    
    // Inside your activity or fragment
    preferenceManager.getLiveData().observe(this, new Observer<String>() {
        @Override
        public void onChanged(String value) {
            // React to real-time changes
        }
    });
    
    // To set a new value and trigger the observer
    preferenceManager.setValue("new_value");
    

    This example uses a PreferenceManager class with LiveData to observe and react to changes in SharedPreferences values in real-time.

    Login or Signup to reply.
  3. There is no live-update in shared_preferences. So there are several way to achieve what you want.

    1. You can use one of the packages, which provide such functionality: streaming_shared_preferences or rx_shared_preferences. Both are streamed wrappers for classic shared preferences.

    2. You can write your own wrapper for shared preference, which will notify on each change in your shared prefs (like in the packages above). The main idea is to create notification of changes when you save value and then to listen to the changes (you can see examples in the source code of the above packages).

    3. You can use some other solution, which has streams/live-update like hive instead of shared preferences to store your data locally.

    Login or Signup to reply.
  4. Certainly! To fetch SharedPreferences values in real-time in Android, use SharedPreferences.OnSharedPreferenceChangeListener. Here’s a concise example:

    import android.content.SharedPreferences;
    import android.os.Bundle;
    import androidx.appcompat.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
    
        private SharedPreferences sharedPreferences;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            sharedPreferences = getSharedPreferences("your_pref_name", Context.MODE_PRIVATE);
            sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    
            String value = sharedPreferences.getString("your_key", "default_value");
        }
    
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals("your_key")) {
                String updatedValue = sharedPreferences.getString(key, "default_value");
                // Handle the updated value in real-time
            }
        }
    
        @Override
        protected void onDestroy() {
            sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
            super.onDestroy();
        }
    }
    

    Replace "your_pref_name" with your SharedPreferences file name and "your_key" with the key you want to observe. This example captures changes in real-time through the onSharedPreferenceChanged method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search