简体   繁体   English

多次更改方向后,savedInstanceState中的值将变为null

[英]Value in savedInstanceState becomes null after multiple orientation changes

I am making a master-detail application and I am observing some odd behavior I can't explain / find an answer for. 我正在做一个主从应用程序,并且观察到一些我无法解释/找不到答案的奇怪行为。

So my master fragment is just a ListView that when you click on an item, it opens up the detail page. 因此,我的主片段只是一个ListView,当您单击某个项目时,它会打开详细信息页面。 So when you're on the detail page, you can press the back button, and it will go back to the master fragment with no errors. 因此,当您在详细信息页面上时,可以按“后退”按钮,它将无误返回到主片段。

If you're on the detail change, and then do an orientation change and then press back, still no errors occur. 如果您要更改详细信息,然后更改方向,然后按回,则仍然不会发生错误。

But when you're on the detail page, and then do an orientation change, and then do an orientation change back (so portrait -> landscape -> portrait), I get a null pointer exception when I am trying to restore the ListView. 但是,当您在详细信息页面上,然后进行方向更改,然后再进行方向更改(因此,纵向->横向->纵向)时,在尝试还原ListView时出现空指针异常。

Here is the offending code: 这是有问题的代码:

        if (savedInstanceState == null) {

            posts = new ArrayList<Post>();
            loading = true;
            refreshData();

        } else {

            loading = false;
            posts = savedInstanceState.getParcelableArrayList("posts");
            adapter = new ListviewAdapterPost(getActivity(), R.layout.cell_layout_post,
                    posts);
            //This line is the one that throws the null pointer.
            listview.setAdapter(adapter);

        }

I did a check, and the posts ArrayList is null after the two orientation changes, but not after just one. 我进行了检查,两次方向更改后,职位ArrayList为null,而不仅仅是一次。 This code is taking place in the onCreateView method in my master fragment. 这段代码在我的主片段的onCreateView方法中进行。

If you need any other code, let me know! 如果您需要任何其他代码,请告诉我!

  1. you'd use android:configChanges="orientation" to avoid recrating your activity whenever orientation changes. 您可以使用android:configChanges =“ orientation”避免每当方向更改时就重新评估您的活动。

  2. you can save & retrieve your fragment instance by creating your Fragment instance manually. 您可以通过手动创建Fragment实例来保存和检索片段实例。

in your Fragment create newInstance like: 在您的片段中创建newInstance,例如:

public static MasterFragment newInstance() {
        MasterFragment mf = new MasterFragment ();
        Bundle args = new Bundle();
        if(posts != null && posts.length > 0)
            args.putSerializable("posts", posts);   
        mf.setArguments(args);
        return mf;
    }

and create your fragment from newInstance in your activity like this 然后像这样在活动中从newInstance创建片段

MasterFragment mf = MasterFragment.newInstance();
*
*transaction
*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM