System.NullReferenceException使用Xamarin将数据从Activity传递到FragmentActivity和Json

时间:2016-08-11 13:30:53

标签: c# android json xamarin

当我尝试使用Json序列化和反序列化将数据从System.NullReferenceException传递到Activity时,我收到FragmentActivity错误。当然,我可以简单地用字符串传递我想要的数据类型(姓名,公司名称等),但我想使用Json。

MainActivity.cs

private void LoginButton_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < LoginList.Count; i++)
        {
            overload = i;
            Intent intent;
            if (LoginList[i].sUsername == login.Text && LoginList[i].sPassword == pass.Text)
            {
                int kind = LoginList[i].iAccountType;
                if (kind == 0)
                {
                    intent = new Intent(this, typeof(ClientActivity));
                    intent.PutExtra("Client", JsonConvert.SerializeObject(ClientList[0]));
                    StartActivity(intent);
                }`
}//there are two more kinds of accounts

LoginList只是现有用户登录的列表(整个应用是演示),ClientList是客户帐户列表。 iAccountType是一个整数确定帐户类型,0表示客户帐户类型。

ClientActivity托管一个ViewPager,其中包含自定义ActionBar,其中包含多个标签(Fragments),其中一个标签为MyAccount,显示帐户信息,如姓名,姓氏等。

ClientActivity.cs

public class ClientActivity : FragmentActivity, ActionBar.ITabListener 
{
    private ViewPager viewPager;
    private FragmentManager fm;
    private ActionBar ClientBar;
    Client client;

    public class ClientFragmentAdapter : FragmentPagerAdapter
    {
        private List<Fragment> fragments;

        public ClientFragmentAdapter(FragmentManager fm, List<Fragment> fragments) : base(fm)
        {
            this.fragments = fragments;
        }

        public override int Count
        {
            get
            {
                return fragments.Count;
            }
        }

        public override Fragment GetItem(int position)
        {
            return fragments[position];
        }
    }

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ClientMain);

        //JSON DESERIALIZATION
        client = JsonConvert.DeserializeObject<Client>(Intent.GetStringExtra("Client"));//this line causes the NullReference error

        // Create your application here
        fm = SupportFragmentManager;

        //VIEWPAGER
        viewPager = FindViewById<ViewPager>(Resource.Id.viewPager);
        viewPager.Adapter = new ClientFragmentAdapter(fm, GetFragments());
        viewPager.PageSelected += ViewPager_PageSelected;

        //ACTION BAR
        ClientBar = this.ActionBar;
        ClientBar.NavigationMode = ActionBarNavigationMode.Tabs;
        ClientBar.SetDisplayShowTitleEnabled(true);
        addTabs();

    }

我只想补充一点,Xamarin已经多次抛出标题中提到的异常,无缘无故。到目前为止,清理,重建,删除导致错误的部分并重写它甚至删除整个应用程序并重写它对我有用,但我已经尝试了所有这些来修复此错误而没有正面结果

应用的数据传输部分基于本教程:https://www.youtube.com/watch?v=NtLac9HpHSw

0 个答案:

没有答案