0

我在 App.cs 中存储了一个对象列表,因为我想在用户浏览其他内容页面(使用导航页面)时保留数据。当他返回到有 Picker 的页面时,我希望上面有相同的项目,但是在再次设置 ItemsSources 时它会使应用程序崩溃。

包含选择器的页面:

public class Local
{
   public string cidade { get; set; }
   public int id { get; set; }
}

if (((App)App.Current).Backup.Count<1)
{
   try
   {
      using (WebClient browser = new WebClient())
      {
          Uri uriCidades = new Uri("xxxxx.php");
          jsonCidades = await browser.DownloadStringTaskAsync(uriCidades);
      }
      var ListaCidades = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Local>>(jsonCidades);
      PickerCidades.ItemsSource = ListaCidades; // it works as expected
      ((App)App.Current).Backup = ListaCidades;  // it works as expected
   }
   catch (Exception)
   {
      throw;
   }
}
else
{
    PickerCidades.ItemsSource = ((App)App.Current).Backup; // the app crashs here

}

这是在 App.cs


public class Local
{
   public string cidade { get; set; }
   public int id { get; set; }
}
public List<Local> Backup = new List<Local>();

错误输出:

System.NullReferenceException: Object reference not set to an instance of an object.
  at MasterDetailPageNavigation.ContactsPage.CarregaCidades () [0x0016a] in ContactsPage.xaml.cs:56
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-08/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
  at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <11f101b564894ca7af6c482ddc51c698>:0
  at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <11f101b564894ca7af6c482ddc51c698>:0
  at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <11f101b564894ca7af6c482ddc51c698>:0
  at at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.47(intptr,intptr)
4

2 回答 2

0

我可以通过将x:FieldModifier="public static"添加到我的选择器标签来解决此问题。现在它可以工作了,后面的代码没有变化。

于 2020-01-17T02:41:32.083 回答
0

如果它在您有注释的代码行上引发 NullReferenceException,那么只有 3 种可能性:PickerCidades 为 null、App 为 null 或 App.Current 为 null。如果您在该行设置断点并在调试器中暂停,您应该能够将鼠标悬停在每个单独的引用上并查看哪个(或多个)为空。

于 2020-01-17T01:43:23.777 回答