放置在FrameLayout内的Fragment视图会抛出NullPointerException

时间:2016-10-25 01:56:18

标签: java android android-fragments nullpointerexception

我正在尝试在我的一项活动中使用FrameLayout。我希望这个FrameLayout成为活动中的占位符,我想在其中添加/替换/删除片段。

我有一个简单的咖啡馆应用程序用于学习android。为简单起见,我将发布Cake和Breads类别的代码。

问题: NullPointerException 。我不知道为什么我的片段视图为空的原因。我猜可能片段生命周期没有运行所以视图没有膨胀因此访问视图会抛出nullpointer?请帮助我理解为什么抛出nullpointer。

App的流程

用户在ListFragment中选择特定的蛋糕或面包> CakeAndBreadActivity被称为>显示蛋糕或面包特定细节

我正在寻找:视图中NullPointerException背后的解释和原因以及如何在使用FrameLayout时将Cakes和Bread详细信息显示在片段中。

的NullPointerException

--------- beginning of crash
10-25 01:41:21.550 2374-2374/com.cafe E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.cafe, PID: 2374
                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cafe/com.cafe.CakeAndBreadActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                 at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                 at android.os.Looper.loop(Looper.java:148)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                 at com.cafe.CakeAndBreadDetailFragment.displayCakeAndBreadDetails(CakeAndBreadDetailFragment.java:97)
                                                                 at com.cafe.CakeAndBreadActivity.displayCakeAndBreadDetails(CakeAndBreadActivity.java:30)
                                                                 at com.cafe.CakeAndBreadActivity.onCreate(CakeAndBreadActivity.java:19)
                                                                 at android.app.Activity.performCreate(Activity.java:6237)
                                                                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                 at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                 at android.os.Looper.loop(Looper.java:148) 
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

CakeAndBreadActivity

public class CakeAndBreadActivity extends Activity implements CakeAndBreadDetailFragment.onCakeAndBreadDetailFragmentListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cake_and_bread);
        displayCakeAndBreadDetails();
    }

    public void displayCakeAndBreadDetails(){

        Intent cakeAndBreadIntent = getIntent();
        int cakeAndBreadId = Integer.valueOf(cakeAndBreadIntent.getIntExtra("cakeAndBreadNumber", 0));

        CakeAndBreadDetailFragment cakeAndBreadDetail = new CakeAndBreadDetailFragment();

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        cakeAndBreadDetail.displayCakeAndBreadDetails(cakeAndBreadId);
        fragmentTransaction.replace(R.id.cake_and_bread_detail_frame_layout_id, cakeAndBreadDetail);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

    }

    @Override
    public void onCakeAndBreadDetail(int id) {

    }
}

activity_cake_and_bread.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.cafe.CakeAndBreadActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/cake_and_bread_detail_frame_layout_id"/>

</LinearLayout>

CakeAndBreadDetailFragment

public class CakeAndBreadDetailFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    private onCakeAndBreadDetailFragmentListener mListener;

    public CakeAndBreadDetailFragment() {
    }

    public static CakeAndBreadDetailFragment newInstance(String param1, String param2) {
        CakeAndBreadDetailFragment fragment = new CakeAndBreadDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_cake_and_bread_detail, container, false);
    }

    public void onButtonPressed(int id) {
        if (mListener != null) {
            mListener.onCakeAndBreadDetail(id);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof onCakeAndBreadDetailFragmentListener) {
            mListener = (onCakeAndBreadDetailFragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement onCakeAndBreadDetailFragmentListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface onCakeAndBreadDetailFragmentListener {
        // TODO: Update argument type and name
        void onCakeAndBreadDetail(int id);
    }

    public void displayCakeAndBreadDetails(int id){
        CakeAndBread cakeAndBread = (CakeAndBread)CakeAndBread.getCakeAndBreadList().get(id);
        View cakeAndBreadView = getView();
        TextView cakeAndBreadTextView = (TextView)cakeAndBreadView.findViewById(R.id.cake_and_bread_detail_fragment_id);
        cakeAndBreadTextView.setText(cakeAndBread.getCakeAndBreadName() + " " + cakeAndBread.getCakeAndBreadNutritionFacts());
    }
}

fragment_cake_and_bread_detail.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cafe.CakeAndBreadDetailFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/cake_and_bread_detail_fragment_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         /> 
</LinearLayout>

编辑:按照建议,当我尝试访问视图时,片段没有完全加载,因此抛出了nullpointerexception。现在我的问题是framelayout或者片段没有显示我放在片段中的textview,我该如何解决这个问题?我正在传递cake和bread id,然后在TextView的setText(...)方法中设置文本。

2 个答案:

答案 0 :(得分:3)

    cakeAndBreadDetail.displayCakeAndBreadDetails(cakeAndBreadId);
    fragmentTransaction.replace(R.id.cake_and_bread_detail_frame_layout_id, cakeAndBreadDetail);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

您正在呼叫displayCakeAndBreadDetails(..),呼叫displayCakeAndBreadDetails(..),呼叫getView()。 此时您尚未插入片段(在fragmentTransaction.commit();之后发生),因此没有与片段关联的视图。因此getView()返回null。

答案 1 :(得分:1)

@Kiskae是对的。当片段未准备好时,您正在调用cakeAndBreadDetail.displayCakeAndBreadDetails(cakeAndBreadId),这将导致NullPointerException。尝试:

public class CakeAndBreadActivity extends Activity implements CakeAndBreadDetailFragment.onCakeAndBreadDetailFragmentListener {
    public void displayCakeAndBreadDetails(){
        Intent cakeAndBreadIntent = getIntent();
        int cakeAndBreadId = Integer.valueOf(cakeAndBreadIntent.getIntExtra("cakeAndBreadNumber", 0));

        CakeAndBreadDetailFragment cakeAndBreadDetail = CakeAndBreadDetailFragment.newInstance(cakeAndBreadId);

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.cake_and_bread_detail_frame_layout_id, cakeAndBreadDetail);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

public class CakeAndBreadDetailFragment extends Fragment {
    private static final String ARG_CAKE_AND_BREAD_ID = "ARG_CAKE_AND_BREAD_ID";

    public CakeAndBreadDetailFragment() {
    }

    public static CakeAndBreadDetailFragment newInstance(int cakeAndBreadId) {
        CakeAndBreadDetailFragment fragment = new CakeAndBreadDetailFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CAKE_AND_BREAD_ID, cakeAndBreadId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_cake_and_bread_detail, container, false);

        if (getArguments != null) {
            int cakeAndBreadId = getArguments.getInt(ARG_CAKE_AND_BREAD_ID, -1);
            if (cakeAndBreadId != -1) {
                displayCakeAndBreadDetails(cakeAndBreadId);
            }
        }

        return view;
    }

    public void displayCakeAndBreadDetails(int id){
        ...
    }
}