使用 Bundle 将列表视图值从 Fragment 传递到 Fragment 时获取空对象引用

Getting Null Object Reference when passing List View value from Fragment to Fragment using Bundle

我试图使用 setOnItemClickListener 将一些数据从 ListView 传递到 Fragment 到另一个 Fragment 使用 bundle 但我得到空对象引用

这是第一个 Fragment

ClickListener

HomeMakananMieayamFragment.java

ListViewMenuMieAyam.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
                switch (position) {
                    case 0 :
                        //set getter to be called based on position
                        MieAyam mieAyamGeter1 = (MieAyam)ListViewMenuMieAyam.getItemAtPosition(position);
                        //declare new code
                        String FoodCode1 = "MA1";
                        //get MakananName using getter
                        String FoodName1 = mieAyamGeter1.getmMakananName();
                        //get MakananPrice using getter
                        int FoodPrice1 = mieAyamGeter1.getmMakananHarga();
                        //set the MakananPrice to String to passed to intent
                        String Price1 = String.valueOf(FoodPrice1);
                        //Pass the variables
                        FragmentOrdertoCart fragmentOrdertoCart = new FragmentOrdertoCart();
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("FoodCode", FoodCode1);
                        bundle1.putString("FoodName", FoodName1);
                        bundle1.putString("FoodPrice", Price1);
                        fragmentOrdertoCart.setArguments(bundle1);

                        Fragment FragmentOrdertoCart1 = new FragmentOrdertoCart();
                        // consider using Java coding conventions (upper first char class names!!!)
                        FragmentTransaction transaction1 = getFragmentManager().beginTransaction();
                        // Replace whatever is in the fragment_container view with this fragment,
                        // and add the transaction to the back stack
                        transaction1.replace(R.id.ContainerMieAyam, FragmentOrdertoCart1);
                        transaction1.addToBackStack(null);
                        // Commit the transaction
                        transaction1.commit();
                        break;
                    case 1:
                        MieAyam mieAyamGeter2 = (MieAyam)ListViewMenuMieAyam.getItemAtPosition(position);
                        String FoodCode2 = "MA2";
                        String FoodName2 = mieAyamGeter2.getmMakananName();
                        int FoodPrice2 = mieAyamGeter2.getmMakananHarga();
                        String Price2 = String.valueOf(FoodPrice2);
                        FragmentOrdertoCart fragmentOrdertoCart2 = new FragmentOrdertoCart();
                        Bundle bundle2 = new Bundle();
                        bundle2.putString("FoodCode", FoodCode2);
                        bundle2.putString("FoodName", FoodName2);
                        bundle2.putString("FoodPrice", Price2);
                        fragmentOrdertoCart2.setArguments(bundle2);

                        Fragment FragmentOrdertoCart2 = new FragmentOrdertoCart();
                        // consider using Java coding conventions (upper first char class names!!!)
                        FragmentTransaction transaction2 = getFragmentManager().beginTransaction();

                        // Replace whatever is in the fragment_container view with this fragment,
                        // and add the transaction to the back stack
                        transaction2.replace(R.id.ContainerMieAyam, FragmentOrdertoCart2);
                        transaction2.addToBackStack(null);
                        // Commit the transaction
                        transaction2.commit();
                        break;
                    case 2:
                        MieAyam mieAyamGeter3 = (MieAyam)ListViewMenuMieAyam.getItemAtPosition(position);
                        String FoodCode3 = "MA3";
                        String FoodName3 = mieAyamGeter3.getmMakananName();
                        int FoodPrice3 = mieAyamGeter3.getmMakananHarga();
                        String Price3 = String.valueOf(FoodPrice3);
                        FragmentOrdertoCart fragmentOrdertoCart3 = new FragmentOrdertoCart();
                        Bundle bundle3 = new Bundle();
                        bundle3.putString("FoodCode", FoodCode3);
                        bundle3.putString("FoodName", FoodName3);
                        bundle3.putString("FoodPrice", Price3);
                        fragmentOrdertoCart3.setArguments(bundle3);

                        Fragment FragmentOrdertoCart3 = new FragmentOrdertoCart();
                        // consider using Java coding conventions (upper first char class names!!!)
                        FragmentTransaction transaction3 = getFragmentManager().beginTransaction();
                        // Replace whatever is in the fragment_container view with this fragment,
                        // and add the transaction to the back stack
                        transaction3.replace(R.id.ContainerMieAyam, FragmentOrdertoCart3);
                        transaction3.addToBackStack(null);
                        // Commit the transaction
                        transaction3.commit();
                        break;
                }
            }
        });

这是第二个Fragment FragmentOrdertoCart.java


import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toolbar;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FragmentOrdertoCart#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentOrdertoCart extends Fragment {
    TextView TxtvOrdertoCartCode,TxtvOrdertoCartName,TxtvOrdertoCartPrice;
    Toolbar toolbarOrdertoCart;
    LinearLayout ContainerContentOrdertoCart;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FragmentOrdertoCart() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragmentOrdertoCart.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentOrdertoCart newInstance(String param1, String param2) {
        FragmentOrdertoCart fragment = new FragmentOrdertoCart();
        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);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View viewRoot = inflater.inflate(R.layout.fragment_orderto_cart, container, false);

        TxtvOrdertoCartCode = viewRoot.findViewById(R.id.TxtvOrdertoCartCode);
        TxtvOrdertoCartName = viewRoot.findViewById(R.id.TxtvOrdertoCartName);
        TxtvOrdertoCartPrice = viewRoot.findViewById(R.id.TxtvOrdertoCartPrice);
        ContainerContentOrdertoCart = viewRoot.findViewById(R.id.ContainerContentOrdertoCart);

        Bundle bundle = this.getArguments();
        assert bundle != null;
        String Code = bundle.getString("FoodCode");
        String Name = bundle.getString("FoodName");
        String Price = bundle.getString("FoodPrice");

        TxtvOrdertoCartCode.setText(Code);
        TxtvOrdertoCartName.setText(Name);
        TxtvOrdertoCartPrice.setText(Price);

        toolbarOrdertoCart = viewRoot.findViewById(R.id.ToolbarOrdertoCart);
        toolbarOrdertoCart.setNavigationIcon(R.drawable.arrowbackicon);
        toolbarOrdertoCart.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContainerContentOrdertoCart.setVisibility(View.GONE);
                // Create new fragment and transaction
                Fragment FragmentMieAyam = new HomeMakananMieayamFragment();
                // consider using Java coding conventions (upper first char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.COntainerOrdertoCart, FragmentMieAyam);
                transaction.addToBackStack(null);
                // Commit the transaction
                transaction.commit();
            }
        });
        // Inflate the layout for this fragment
        return viewRoot;
    }
}

错误日志

    Process: com.example.pesanpalgading20, PID: 28032
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.BaseBundle.getString(java.lang.String)' on a null object reference
        at com.example.pesanpalgading20.FragmentOrdertoCart.onCreateView(FragmentOrdertoCart.java:79)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl.run(FragmentManagerImpl.java:150)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

看来你练错了

  1. 在每种情况下您只需要一个 Fragment 实例,现在您正在初始化两个。
  2. 此外,您在与第二个片段进行交易时将捆绑包传递给第一个片段时犯了一个错误在每种情况下。

在每个 ccase 中尝试以下代码:

Bundle bundle1 = new Bundle();
bundle1.putString("FoodCode", FoodCode1);
bundle1.putString("FoodName", FoodName1);
bundle1.putString("FoodPrice", Price1);
   

Fragment fragmentOrdertoCart1 = new FragmentOrdertoCart();
fragmentOrdertoCart1.setArguments(bundle1);                    
FragmentTransaction transaction1 = getFragmentManager().beginTransaction();
transaction1.replace(R.id.ContainerMieAyam, fragmentOrdertoCart1);
transaction1.addToBackStack(null);
transaction1.commit();