在Android中处理片段时出现空指针异常

时间:2018-03-30 12:25:58

标签: android android-layout android-studio android-fragments nullpointerexception

我正在研究我想要将数据从send片段发送到另一个片段的功能。我在一个片段中设置参数说" A Fragment"从另一个人那里得到它" B Fragment"但问题是当我跳到" B片段"来自" C Fragment"我的应用程序崩溃并抛出错误 java.lang.NullPointerException:尝试调用虚方法' java.lang.String android.os.Bundle.getString(java.lang.String) '在空对象引用上

我的代码:

片段A

     Bundle bundle = new Bundle();
            bundle.putString("advisor_id", advisor_id);

            FragmentMicroLearningArticlesList fragmentMicroLearningArticlesList = new FragmentMicroLearningArticlesList();
            fragmentMicroLearningArticlesList.setArguments(bundle);
            android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();

            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frame, fragmentMicroLearningArticlesList);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

片段B

      String  advisor_id = "";
   if(getArguments().getString("advisor_id") != null )
    {
        advisor_id = getArguments().getString("advisor_id");
    }
    else {
        advisor_id = "";
    }

Logs

2 个答案:

答案 0 :(得分:2)

如错误所示,检查参数是否为空......

if( getArguments() != null && getArguments().getString("advisor_id") != null )

答案 1 :(得分:1)

片段B

  String  advisor_id = "";
   if(getArguments()!= null )
    {
        advisor_id = getArguments().getString("advisor_id");
    }
    else {
        advisor_id = "";
    }