刷新Xamarin中的当前活动

时间:2014-09-30 12:25:40

标签: android listview android-intent xamarin refresh

我是Xamarin的新手,我正试图从自己身上刷新MainActivity。我阅读了很多关于此的论坛,但我仍然无法找到任何解决方案。我的问题是我需要从另一种方法中刷新,而不是在onCreate()方法中。

我的MainActivitylistview,我想重新加载整个活动以刷新列表视图。我需要重新加载整个活动,因为在我的情况下我无法使用NotifyDataSetChanged(),因为我对listview所做的更改不在onCreate()方法内,而不在新活动也没有。我有一个CAB菜单,用户可以从中选择从列表视图中删除所选的注释。我在NotifyDataSetChanged()方法中使用onResume()方法,当我在另一项活动中对listview进行更改但它无法正常工作时,它工作正常当我从当前活动中创建它们时,因为那时没有调用onResume()方法。

我试过这样做:

Intent refresh = new Intent(this,typeof(MainActivity));
refresh.AddFlags(ActivityFlags.NoAnimation);
Finish();
StartActivity(refresh);

但它已经在第一行给了我NullPointerException ..我认为例外是#34;这个"。所以我尝试了不同的方式:而不是使用"这个"我在Intent refresh = new Intent(context ,typeof(MainActivity));方法中使用 - onCreate() where context = this。但是通过这种方式它仍然给了我一个NullPointerException,但这一次在行 - StartActivity(refresh) ..

提前致谢! :)

2 个答案:

答案 0 :(得分:0)

NotifyDataSetChanged()绝对可以在OnCreate / OnResume之外的其他方式使用

如果您想使用NotifyDataSetChanged(),则需要更改ListAdapter中与ListView相关联的项目。

像这样的东西

namespace MyNamespace
{
   [Activity]
   public MyActivity : Activity
   {

      private ArrayAdapter<string> myAdapter = null;

      public override void OnCreate(Bundle savedInstanceState)
      {
            myAdapter = new ArrayAdapter<string>(); //or whatever type your adapter is.
            myListView.Adapter = myAdapter; 
      }

      private void UpdateList()
      {
            //Delete item
            myAdapter.Remove(item);

            //Insert item
            myAdapter.Insert(item, 0); //0 = position for new item

            //Add item
            myAdapter.Add(item);

            myAdapter.NotifyDataSetChanged();
       }
   }
}

答案 1 :(得分:0)

这是代码:

    public List<DeliveryNoteInfo> _lstNoteInfo = new List<DeliveryNoteInfo>();
    public ObjectToSerialize objectToSerialize;
    public Serializer serializer;
    private ListView objListItem;
    private MonoBaseAdapter2 myAdapter = null;
    static AlertDialog levelDialog;
    static string[] items;
    static Context context2;

    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);
        addButton.Click += delegate {
            StartActivity (typeof(AddActivity));
        };
        Button sortButton = FindViewById<Button>(Resource.Id.SortButton);
        sortButton.Click += delegate {
            ShowSortDialog(_lstNoteInfo);
        };
        Button exitButton = FindViewById<Button>(Resource.Id.ExitButton);
        exitButton.Click += delegate {
            Finish();
        };
        context2 = this;
        // 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);
        myAdapter = new MonoBaseAdapter2 (this, _lstNoteInfo);
        objListItem.Adapter = myAdapter;
        objListItem.FastScrollEnabled = true;
        objListItem.ChoiceMode = (ChoiceMode)AbsListViewChoiceMode.MultipleModal;
        objListItem.SetMultiChoiceModeListener (new CabMenu(this,this,objListItem));


        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("Name",_lstNoteInfo[e.Position].Name);
            itemClicked.PutExtra("Supplier",_lstNoteInfo[e.Position].Supplier);
            itemClicked.PutExtra("Amount",_lstNoteInfo[e.Position].Amount);
            itemClicked.PutExtra("Info",_lstNoteInfo[e.Position].AddInfo);
            StartActivity (itemClicked);
        };

    }

    protected override void OnResume ()
    {
        base.OnResume ();
        var lstNoteInfo = new List<DeliveryNoteInfo>();
        var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
        if (System.IO.File.Exists (path + "outputFile.txt")) {
            objectToSerialize = serializer.DeSerializeObject ("outputFile.txt");
            lstNoteInfo = objectToSerialize.DeliveryNoteInfo;
        }
        _lstNoteInfo.Clear ();
        _lstNoteInfo.AddRange (lstNoteInfo);
        ((MonoBaseAdapter2)objListItem.Adapter).NotifyDataSetChanged ();
        objListItem.Invalidate ();
        ((MonoBaseAdapter2)objListItem.Adapter).NotifyDataSetInvalidated ();

    }

    public void makeNote (String fileName, String finalDate, String type,String noteName, String amount, String supplier, String addInfo)
    {
        _lstNoteInfo.Add (new DeliveryNoteInfo (){ ImageID = fileName, Date = finalDate,Type = type, Name = noteName, Amount = amount, Supplier = supplier, AddInfo = addInfo});
        objectToSerialize.DeliveryNoteInfo = _lstNoteInfo;
        serializer.SerializeObject("outputFile.txt", objectToSerialize);
        Console.WriteLine ("Name: " + noteName);
        Console.WriteLine ("Amount: " + amount);
    }
    public void RefreshAfterDelete(List<DeliveryNoteInfo> updatedList)
    {
        _lstNoteInfo.Clear ();
        _lstNoteInfo.AddRange (updatedList);
        objectToSerialize.DeliveryNoteInfo = _lstNoteInfo;
        serializer.SerializeObject("outputFile.txt", objectToSerialize);
        UpdateList ();
    }
    public void PrintCollection<T>(IEnumerable<T> col)
    {
        foreach(var item in col)
            System.Console.WriteLine("ITEM"); 
    }
    void deserialize ()
    {
        objectToSerialize = serializer.DeSerializeObject ("outputFile.txt");
        _lstNoteInfo = objectToSerialize.DeliveryNoteInfo;
    }
    void deserialize(List<DeliveryNoteInfo> list)
    {
        objectToSerialize = serializer.DeSerializeObject ("outputFile.txt");
        list = objectToSerialize.DeliveryNoteInfo;
    }
    void serialize (List<DeliveryNoteInfo> list)
    {
        objectToSerialize.DeliveryNoteInfo = list;
        serializer.SerializeObject("outputFile.txt", objectToSerialize);
    }
    private void ShowSortDialog(List<DeliveryNoteInfo> updatedList)
    {

        // Strings to Show In Dialog with Radio Buttons
        items = new string[]{" Date "," Name "," Type of delivery "," Supplier "};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.SetTitle("Sort by ..");
        builder.SetSingleChoiceItems(items, -1,  onClick);
        levelDialog = builder.Create();
        levelDialog.Show();
    }
    public void onClick(object sender, DialogClickEventArgs e) {
        var item = (int) e.Which;
        List<DeliveryNoteInfo> list = new List<DeliveryNoteInfo> (); 
        switch(item)
        {
        case 0:
            // Your code when first option seletced
            Console.WriteLine ("Sorting by date..");
            break;
        case 1:
            //  Sorting by name
            objectToSerialize = serializer.DeSerializeObject ("outputFile.txt");
            list = objectToSerialize.DeliveryNoteInfo;
            List<DeliveryNoteInfo> SortedList = list.OrderBy (o => o.Name).ToList ();
            RefreshAfterDelete (SortedList);
            Console.WriteLine ("Sorting by name..");
            break;
        case 2:
            // Your code when 3rd option seletced
            Console.WriteLine ("Sorting by type of delivery..");
            break;
        case 3:
            // Your code when 4th  option seletced  
            Console.WriteLine ("Sorting by supplier ..");
            break;

        }
        levelDialog.Dismiss();    
    }
    private void ListClicked (object sender, DialogClickEventArgs e)
    {
        var builder = new AlertDialog.Builder (this);
        builder.SetMessage (string.Format ("You selected: {0} , {1}", (int)e.Which, items [(int)e.Which]));

        builder.Show ();
    }
    private void UpdateList()
    {
      myAdapter.NotifyDataSetChanged();
    }
}