Search code examples
c#androidlistviewxamarinbaseadapter

Refreshing the listview of MainActivity after finishing another activity


I have troubles with refreshing my listview adapter after I close another activity. I am making program for delivery notes and my main screen is a list with notes. My problem is that when I add a new note(which I am making in another activity) the new note is note appearing on the list. It appears only after rotation of the screen or refreshing the whole program. Here is my code for the MainActivity:

protected override void OnCreate (Bundle SavedInstanceState)
    {
        base.OnCreate (SavedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        // Get our UI controls from the loaded layout
        Button addButton = FindViewById<Button>(Resource.Id.AddButton);
        // Loading the already saved notes from external file
        objectToSerialize = new ObjectToSerialize();
        serializer = new Serializer ();
        var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
        if (System.IO.File.Exists (path + "outputFile.txt")) {
            deserialize ();
        }
        //Displaying the Notes in a custom made ListView 
        objListItem = FindViewById<ListView> (Resource.Id.listView1);
        objListItem.Adapter = new MonoBaseAdapter2 (this, _lstNoteInfo);
        objListItem.FastScrollEnabled = true;

        objListItem.ItemClick += delegate(object sender, AdapterView.ItemClickEventArgs e) {
            var itemClicked = new Intent(this,typeof(InfoActivity));
            itemClicked.PutExtra("File name",_lstNoteInfo[e.Position].ImageID);
            itemClicked.PutExtra("Date",_lstNoteInfo[e.Position].Date);
            itemClicked.PutExtra("Type",_lstNoteInfo[e.Position].Type);
            itemClicked.PutExtra("Supplier",_lstNoteInfo[e.Position].Supplier);
            itemClicked.PutExtra("Amount",_lstNoteInfo[e.Position].Amount);
            itemClicked.PutExtra("Info",_lstNoteInfo[e.Position].AddInfo);
            StartActivity (itemClicked);
        };

        addButton.Click += delegate {
            StartActivity (typeof(AddActivity));
        };

    }

I have tried with overriding onResume() and using the invalidate(), notifyDataSetChanged(), refreshDrawableState(); methods, but none of them worked. Maybe I am not using them as I should I don't know .. I would appreciate any ideas! :)


Solution

  • @Override
    protected void onResume() {
        super.onResume();
        posts.clear();
        posts.addAll(tempPosts);
        postsAdapter.notifyDataSetChanged();
    }
    

    I use this in my project, works like a charm.

    Post is my List, and tempPost is list where I save edited post list.