问题描述
MainFragment将数据传递给ActivityContentFragment,但出现错误“在空对象引用上出现java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)'”
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类
public class ActivityInfo implements Serializable {
public String eventName;
public String date;
public String review;
public String toString(){
return this.eventName;
}
}
1楼
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();
您正在创建一个Fragment
实例并将Bundle
应用于该实例。
永远不要将Bundle
应用于实际提交的ActivityContentFragment
。
相反,您可以使用:
ActivityContentFragment fragment = new ActivityContentFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("eventName", activityInfo);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.content, fragment).commit();