0

I've implemented what I think is a pretty vanilla usage of Realm:

public class MyObj : RealmObject
{
   [PrimaryKey]
   public string Key { get; set; }
   public bool Value { get; set; }
}

then, in my app:

using(Realm r = Realm.GetInstance()) {
    var c1 = r.All<MyObj>().Count();
}

which returns zero, as expected.

Then I add an object:

using(Realm r = Realm.GetInstance()) {
    r.Write(() =>
    {
       var obj = new MyObj() { Key = "test", Value = true };
       r.Add(obj);
    });
}

then reopen it and get the count:

using(r = Realm.GetInstance()) {
    var c2 = r.All<MyObj>().Count();
}

and c2 is one, as expected. So far, so good.

But when I close my app, and restart, c1 (the initial count) is zero, not one.
Any idea why?

dlchambers
  • 3,511
  • 3
  • 29
  • 34

2 Answers2

0

Sorry,we couldn't see the other code of your app.

But you can refer to an article by entering key words Xamarin.Forms - Working With Realm Database in your browser. It works properly even after restarting the app.

You can also check the full sample here.

The main code is:

public partial class MainPage : ContentPage
    {
        List<OptionItems> optionItems = new List<OptionItems>();
        Student editStudent;
        public MainPage()
        {
            InitializeComponent();
            imgBanner.Source = ImageSource.FromResource("XamarinFormsRelam.images.banner.png");
            var realmDB = Realm.GetInstance();
            List<Student> studentList = realmDB.All<Student>().ToList();
            listStudent.ItemsSource=studentList;
        }

        private void btnAdd_Clicked(object sender, EventArgs e)
        {
            var realmDB = Realm.GetInstance();
            var students= realmDB.All<Student>().ToList();
            var maxStudentId = 0;
            if (students.Count!=0)
                 maxStudentId = students.Max(s=>s.StudentID);
            Student student = new Student()
            {
                StudentID = maxStudentId + 1,
                StudentName = txtStudentName.Text
            };
            realmDB.Write(() =>
            {
                realmDB.Add(student);
            });
            txtStudentName.Text = string.Empty;
            List<Student> studentList = realmDB.All<Student>().ToList();
            listStudent.ItemsSource = studentList;
        }
        private async void listOptions_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var realmDB = Realm.GetInstance();
            OptionItems selectedItem = optionList.SelectedItem as OptionItems;
            if (selectedItem != null)
            {
                switch (selectedItem.OptionText)
                {
                    case "Edit":
                        popupOptionView.IsVisible = false;
                        popupEditView.IsVisible = true;
                        editStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
                        txtEditStudentName.Text = editStudent.StudentName;
                        break;

                    case "Delete":
                        var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
                        using (var db = realmDB.BeginWrite())
                        {
                            realmDB.Remove(removeStudent);
                            db.Commit();
                        }
                        await DisplayAlert("Success", "Student Deleted", "OK");
                        popupOptionView.IsVisible = false;
                        List<Student> studentList = realmDB.All<Student>().ToList();
                        listStudent.ItemsSource = studentList;
                        break;

                    default:
                        popupOptionView.IsVisible = false;
                        break;
                }
                optionList.SelectedItem = null;
            }
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            var realmDb = Realm.GetInstance();
        }

        private void listStudent_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            Student selectedStudent = listStudent.SelectedItem as Student;
            if(selectedStudent!=null)
            {
                optionItems.Add(new OptionItems { OptionText = "Edit",StudentId=selectedStudent.StudentID});
                optionItems.Add(new OptionItems { OptionText = "Delete", StudentId = selectedStudent.StudentID });
                optionItems.Add(new OptionItems { OptionText = "Cancel"});
                optionList.ItemsSource = optionItems;
                popupOptionView.IsVisible = true;
            }
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            popupEditView.IsVisible = false;
        }

        private async void Button_Clicked_1(object sender, EventArgs e)
        {
            var realmDB = Realm.GetInstance();
            var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);
            using (var db = realmDB.BeginWrite())
            {
                editStudent.StudentName = txtEditStudentName.Text;
                db.Commit();
            }
            await DisplayAlert("Success", "Student Updated","OK");
            txtEditStudentName.Text = string.Empty;
            popupEditView.IsVisible = false;
        }
    }
Jessie Zhang -MSFT
  • 9,830
  • 1
  • 7
  • 19
  • XamarinFormsRelam.Android fails to build, with a bunch of fundamental errors, including InitializeComponent() undefined. So, thanks for the quick response, but examples that don't build don't exactly instill confidence :) – dlchambers Jun 29 '21 at 13:15
  • 1
    In my side,I could build the sample succesfully and deploy to my device. You can try to delete bin and obj folders, then restart VS and try again – Jessie Zhang -MSFT Jun 30 '21 at 06:59
0

Are you deploying on a physical device? If that's the case, it's likely due to the automatic backup and restore functionality built into Android - when you deploy the app, it treats it as an install and restores the last known state.

You can read about it here: An Android app remembers its data after uninstall and reinstall but the tl;dr is - go to settings and turn off "Automatic Restore" or update your manifest to instruct Android not to backup the data.

Nikola Irinchev
  • 1,911
  • 1
  • 13
  • 17
  • So this works... sort of. When I edit Properties\AndroidManifest.xml and add those attributes, the data does indeed persist across runs. HOWEVER, AndroidManifest.xml seems to get rebuilt from the MainActivity's [Activity()] attribute, and this causes the allowBackup and fullBackupOnly attribs to disappear, and I'm back where I started. And Activity() doesn't support those attribs, so it's not quite there – dlchambers Jun 29 '21 at 13:33
  • This might be due to a bug that should have been fixed based on this Github issue: https://github.com/xamarin/xamarin-android/issues/4804. Are you using the latest Xamarin.Android version? – Nikola Irinchev Jun 29 '21 at 20:44
  • Using Xamarin.Forms v 5.0.0.2012 – dlchambers Jun 30 '21 at 12:12
  • This is a bug in the Xamarin.Android tooling, so make sure to update your Visual Studio and all associated components. – Nikola Irinchev Jun 30 '21 at 13:56