Android:FragmentActivity onCreateView with sharedprefs

时间:2015-07-12 07:53:19

标签: android android-fragments nullpointerexception sharedpreferences

我有一个FragmentActivity,我试图在onCreateView方法中恢复Sharedpreferences。

我的代码是:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle args = getArguments();
        int position = args.getInt(ARG_OBJECT);
        int tabLayout = 0;
        switch (position) {
            case 0:
                tabLayout = R.layout.layout_one;
                break;
            case 1:
                tabLayout = R.layout.layout_two;
                break;
        }

        View rootView = inflater.inflate(tabLayout, container, false);

        //Get restore state of all checkboxes
        SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
        String topack00value = prefs.getString("topack00", "");

        CheckedTextView topack00 = (CheckedTextView) rootView.findViewById(R.id.topack_00);

        switch (topack00value) {
            case "yes":
                topack00.setTextColor(getResources().getColor(R.color.cyan700));
                topack00.setPaintFlags(topack00.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                break;
            case "no":
                topack00.setTextColor(getResources().getColor(R.color.black));
                topack00.setPaintFlags(topack00.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
                break;
            default:
                topack00.setTextColor(getResources().getColor(R.color.black));
                topack00.setPaintFlags(topack00.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
                break;
        }

        return rootView;

我经常尝试调用null对象资源错误。错误指向topack00 checktextView,但我已经将它链接到'rootView'视图。

我看了几个类似的案例,但我似乎没事。我还是完全错过了什么。 类似问题: Attempt to invoke virtual method

坚持了5个小时。 :|

1 个答案:

答案 0 :(得分:0)

感谢你们的建议。我在离开电脑的几分钟内想出了一个理论(它有点工作)。在我回到家之前无法测试它。问题在于启动两种不同布局的开关案例。 CheckedTextView的ID仅存在于tab 1的第一个布局中,而不存在导致它为null的另一个布局中。感谢。