Search code examples
xamarinsqlite-net-pcl

How to query user information based on its username in Xamarin


I am trying to get the user gender and display it on my login page, so I can pass it to the next page after login.

I am using textchange event to see if the username exists or not. This is my code:


        private void EntryLoginUsername_TextChanged(object sender, TextChangedEventArgs e)
        {
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Userdatabase.db");
            var db = new SQLiteConnection(dbpath);
            RegUserTable _userstable = new RegUserTable();

            if (!string.IsNullOrWhiteSpace(EntryLoginUsername.Text))
            {
                if (IsTableExists("RegUserTable") == true)
                {
                    var checkquery = db.Table<RegUserTable>().Where(a => a.Username == EntryLoginUsername.Text).FirstOrDefault();

                    if (checkquery != null)
                    {
                        // ani i insert ang tts function  
                        var gendercheck = db.Query<RegUserTable>("SELECT Gender FROM RegUserTable WHERE Username = ?", EntryLoginUsername.Text);

                        if (gendercheck != null)
                        {
                            GenderIdentifier.Text = gendercheck.ToString(); ;
                        }

                        else
                        {
                            GenderIdentifier.Text = "nooooo";
                        }
                    }

                    else
                    {
                        GenderIdentifier.Text = "nooo";
                    }
                }
            }

            else
            {
                GenderIdentifier.Text = "no";
            }
        }

When I run my app, it doesn't give me an error, but this is the output if the username exists in my database:

enter image description here

The output there should be "Male" or "Female".


Solution

  • Based on your code snippet, I guess you have the Gender field in your RegUserTable. Hence it is not required to query twice to get the user and again for gender.

    Note: You will get all the information of the user if he is available in your table in the first query. So you can directly access the gender of the user from that object itself.

    Check below code. This will work for you

     var checkquery = db.Table<RegUserTable>().Where(a => a.Username == EntryLoginUsername.Text).FirstOrDefault();
     if(checkquery !=null)
     {
       var userGender= checkquery.Gender;
       GenderIdentifier.Text = userGender;
     }