Save and retrieve Wrong Value From Json Object Items to IShared Preference in Xamarin.Android (Always Returns Logout Value)

Viewed 84

I am developing a login application which save username and password using Shared Preferences in Xamarin Android (C#). Firstly, I get the username and password value from web service and then I check the value. If in my local db (sqlite) doesn't have the value so, I update the data with the newest one from web service. After that, I store the user ID by using my custom sqlite function to get the user ID with username and password.

So far, I can parse the Json Object from my web service and assign them into variables. But, I found something strange that, my parsed json object item can't be saved in my shared preferences. I've been 3 days searching and researching from internet but, I didn't find anything. I almost give up, guys. Would you like to help me? I would appreciate the helps.

Here what I did to my app.

I made utilities folder which save my essentials class. I made LoginSession class which save property of user now.

in my main activity

private void MyBtnLogin(object aSender, System.EventArgs e)
        {
            try
            {
                System.Net.Http.HttpClient client= new System.Net.Http.HttpClient();
                System.Threading.Tasks.Task.Run(async () =>
                {

                    string response = await _httpClient.GetStringAsync($"http://yourjson.com/{fix_email_value}");
                    JObject parsedObject = JObject.Parse(response);

                    int userID = parsedObject .Value<int>("ID");
                    string userEmail = _parsedResponseObject.Value<string>("Email");
                    string userPassword = _parsedResponseObject.Value<string>("Password");

                    List<User> lists= User.GetUserList(userID);
                    User updatedvalue= (from a in lists where a.Email == userEmail && a.Password == userPassword select a).FirstOrDefault();

                    if (updatedvalue== null)
                    {
                        updatedvalue= new User();
                        updatedvalue.ID = userID;
                        updatedvalue.Email = userEmail;
                        updatedvalue.Password = userPassword;
                        updatedvalue.StoreOrChange();

                        RunOnUiThread(() =>
                        {
                            SharedPref.UserIDNow= userID;
                            LoginSession.UserNow= User.GetID(userID); 
                        });
                    } }
                });
                StartActivity(typeof(NextPage));
                Finish();
            }

and I retrieve the value in the next activity using SharedPref.UserIDNow to retrieve the user ID. I put the SharedPref.UserIDNow inside my static function to get current User ID

What am i missing? Everytime when I launch and login, after login the app closed like log out! and the value returns -22. Btw, -22 is a default value of my shared preference. I think it must be the ID of the User. Please help me :(

1 Answers

I test with your code , it works with no problem .

Some suggestions to troubleshoot .

  1. Debug your code (add breakpoint) to check if SharedPref.UserIDNow= userID; has been executed , and also remove RunOnUiThread method ,you don't need to wrap code into it unless UI elements gets changed .

  2. Use default SharedPreferences ,change preference as

    private static ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
    
  3. Use Commit instead of Apply method on ISharedPreferencesEditor,Apply is asynchronous method which means if you read value too early ,you would get default value at that time .

Related