2014-09-30 78 views
0

我是Xamarin的新手,我正試圖從自己刷新MainActivity。我讀了很多論壇,但我仍然找不到任何解決方案。我的問題是我需要從另一種方法進行更新,而不是在onCreate()方法中。刷新Xamarin中的當前活動

我的MainActivitylistview我想重新加載整個活動以刷新列表視圖。我需要重新加載整個活動,因爲在我的情況下我不能使用NotifyDataSetChanged(),因爲我對listview所做的更改不在onCreate()方法中,也不在新的活動中。我有一個CAB菜單,用戶可以選擇從列表視圖中刪除選定的註釋。我在我的onResume()方法中使用了NotifyDataSetChanged()方法,當我在另一個活動中對listview進行更改時,它的工作正常,但當它從當前活動中生成時不起作用,因爲沒有調用onResume()方法。

我試着做這樣的:

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

,但它給我NullPointerException第一行已經..我認爲唯一的例外是「本」。所以我嘗試了不同的方式:不是使用「this」,而是使用 - Intent refresh = new Intent(context ,typeof(MainActivity));其中context = this在onCreate()方法中。但通過這種方式,它仍然給我一個NullPointerException,但這次在行 - StartActivity(refresh) ..

在此先感謝! :)

+0

'NotifyDataSetChanged'最肯定的運作'OnCreate' /'OnResume'覆蓋之外。 – Johan 2014-09-30 12:50:08

+0

是的,它的工作原理,但我已經在onCreate方法中初始化我的適配器..我不知道如何在onCreate()方法外使用它。 – 2014-09-30 12:51:24

+0

看到我的答案,這是一個小例子,但會起作用。 – Johan 2014-09-30 13:00:01

回答

0

NotifyDataSetChanged()最肯定的運作OnCreate/OnResume外面等覆蓋

如果你想使用NotifyDataSetChanged(),您需要更改該鏈接到ListViewListAdapter的項目。

像這樣的事情

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(); 
     } 
    } 
} 
+0

是的,但如果我想在除onCreate()以外的其他方法中使用myAdapter.NotifyDataSetChanged(),那麼你將會有NullPointerException ..因爲即使你這樣做,你實例化onCreate()內的適配器。 – 2014-09-30 13:09:09

+0

No ,因爲它是一個全局(類的範圍)字段,它不會爲空。 – Johan 2014-09-30 13:11:57

+0

我現在有一個NullReferenceException .. – 2014-09-30 13:17:38

0

Thisi是代碼:

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(); 
    } 
} 
+0

我試圖在RefreshAfterDelete()方法中刷新它.. – 2014-09-30 13:23:35

+0

在該方法中'objListItem'也爲null嗎? – Johan 2014-09-30 13:27:03

+0

如果我嘗試這樣做: ((MonoBaseAdapter2)objListItem.Adapter).NotifyDataSetChanged();它仍然給我[NullReferenceException],因此它也是空的。 – 2014-09-30 13:30:02