当前位置: 代码迷 >> java >> 空对象引用上的java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)'
  详细解决方案

空对象引用上的java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)'

热度:52   发布时间:2023-07-31 11:43:44.0

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;
    }

}
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();
  相关解决方案