片段替换给出NullPointerException

时间:2015-11-29 20:10:39

标签: android android-fragments parse-platform nullpointerexception

所以我有一个主要活动,默认情况下有MainPage片段,当使用导航抽屉导航到LoginPage片段并为Parse提升有效的用户名和密码然后单击按钮返回MainPage片段时;给出此错误:

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference

单击按钮提交值时的以下代码:

MainPage mainPage = new MainPage();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentContainer, mainPage);
fragmentTransaction.commit();

所以它在第一次启动MainPage片段之前运行的这些代码行给出了错误:

**(Gives Error Here)**query.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            ArrayList<String> names = new ArrayList<String>();
            if (e != null) {
                Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show();
            }
           **(Gives Error Here)**  for (ParseObject Obj1 : objects) {
                names.add(Obj1.get("Name").toString());
            }

            ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(getContext(), R.layout.items, names);
            ListView listview = (ListView) getActivity().findViewById(R.id.mainPageListView);
            listview.setAdapter(arrayadapter);

        }
    });

2 个答案:

答案 0 :(得分:1)

Ok通过在主片段页面中添加此行来解决:

View view = inflator.inflate(R.layout.fragmentMain,container,false);

将当前回报更改为:return view;

答案 1 :(得分:0)

您可以按标签检索片段。

Fragment fragment = getFragmentManager().findFragmentByTag("stringtag");

但是你必须在调用replace时定义它:

fragmentTransaction.replace(R.id.FragmentContainer, mainPage, "stringtag");