我在 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)