Ahmed Mujtaba
Ahmed Mujtaba

Reputation: 2248

Saved Preference not getting retrieved

I have a video downloader class in my project that downloads videos from the given url and saves preference as true upon download completion. I check the preference if it's true in another class to fetch the video for playback from it's path. The downloader first checks if the file is downloaded like this:

string isVideoDownloaded = Utils.readPreferences(ctx, video.getUrl(), "false");
            bool isVideoAvailable = Boolean.Parse(isVideoDownloaded);

When the download is completed, the following code is executed.

                    activity.RunOnUiThread(() =>
                 {
                     Utils.savePreferences(ctx, video.getUrl(), "true");
                 });

The preference is saved in the following manner:

        public static void savePreferences(Context activity, string key, string defaultValue)
    {
        ISharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(activity.ApplicationContext);
        ISharedPreferencesEditor editor = sp.Edit();
        editor.Clear();
        editor.PutString(key, defaultValue);
        editor.Commit();
    }

Before playing back the video, the preference is checked in the following method:

private bool isVideoDownloaded(Video video)
    {

        string isVideoDownloaded = Utils.readPreferences(context, video.getUrl(), "false");
        bool isVideoAvailable = Boolean.Parse(isVideoDownloaded);
        if (isVideoAvailable)
        {
            //If video is downloaded then hide its progress
            hideProgressSpinner(video);
            return true;
        }

        showProgressSpinner(video);
        return false;
    }

But the preference is always returned as false. I'm using the same context for the payback I am for the download. This code worked the first time I wrote it but now every time it returns false. I'm a beginner with android so I'm having a hard time figuring out what I'm doing wrong here and how I can fix it.

What can I do to make it work? Any help is appreciated.

Upvotes: 0

Views: 51

Answers (1)

Mina Fawzy
Mina Fawzy

Reputation: 21452

in savePerference method remove editor.Clear()

public static void savePreferences(Context activity, string key, string defaultValue)
    {
        ISharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(activity.ApplicationContext);
        ISharedPreferencesEditor editor = sp.Edit();
        // editor.Clear(); comment this line of code
        editor.PutString(key, defaultValue);
        editor.Commit(); 
    }

Upvotes: 1

Related Questions