1

The MainFragment pass the data to ActivityContentFragment but got the error that "java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference"

Mainfragment

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ActivityInfo activityInfo =(ActivityInfo) listView.getItemAtPosition(position);

                    Fragment fragment = new Fragment();
                    FragmentManager fm = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fm.beginTransaction();
                    fragmentTransaction.replace(R.id.content,new ActivityContentFragment());

                    Bundle bundle = new Bundle();
                    bundle.putSerializable("eventName",activityInfo);
                    fragment.setArguments(bundle);   
                    fragmentTransaction.commit();
                }
            });
        }

ActivityContentFragment

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_activity_content, container, false);

            activityInfo= (ActivityInfo)getArguments().getSerializable("eventName");       
            Log.d("why","eventName="+ activityInfo.eventName);
        return view;

    }

ActivityInfo class

public class ActivityInfo implements Serializable {

    public String eventName;
    public String date;
    public String review;

    public String toString(){
      return this.eventName;
    }

}
Shing Ysc
  • 15
  • 6
  • Try this out —>https://stackoverflow.com/questions/40689889/null-object-reference-error-while-passing-a-serializable-object-to-fragment – Swati Feb 13 '19 at 18:14

1 Answers1

0
Fragment fragment = new Fragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();

// The actual instance of the ActivityContentFragment is created here:
fragmentTransaction.replace(R.id.content,new ActivityContentFragment());

Bundle bundle = new Bundle();
bundle.putSerializable("eventName",activityInfo);

// This Fragment is not your ActivityContentFragment:
fragment.setArguments(bundle);   
fragmentTransaction.commit();

You're creating an instance of Fragment and applying the Bundle to that instance. You never apply the Bundle to the ActivityContentFragment that you're actually committing.

Instead, you can use:

ActivityContentFragment fragment = new ActivityContentFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("eventName", activityInfo);
fragment.setArguments(bundle);   

getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274