这就是我的代码正在做的事情:
MainActivity 使用意图将对象“设备”传递给 ItemListActivity:
// When button is clicked to go to ItemListActivity
car = new Car();
device = new Device(car);
intent.putExtra("device", device);
设备对象有一个 Car 对象作为字段,并且都实现了可序列化。
现在 Car 也是一个片段类,因此在 ItemListActivity 中,我希望有一个选项可以在通过意图传递的设备对象中打开汽车片段。(这是一个主/细节流活动)
项目列表活动:
// in onCreate //
Intent intent = getIntent();
Device device = (Device) intent.getSerializableExtra("device");
View recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
//////////////////
private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(this, ItemsContent.ITEMS, mTwoPane, device));
}
public static class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
...
private Device mDevice;
// Here's the problem:
Car car = mDevice.getCar(); // getCar just returns the private Car field in Device
private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ItemsContent.ItemsPage item = (ItemsContent.ItemsPage) view.getTag();
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, item.id);
Fragment fragment;
fragment = car;
mParentActivity.getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
...
}
}
...
SimpleItemRecyclerViewAdapter(ItemListActivity parent,
List<ItemsContent.ItemsPage> items,
boolean twoPane, Device device) {
mValues = items;
mParentActivity = parent;
mTwoPane = twoPane;
mDevice = device;
}
}
(很多代码只是填充主/细节流活动的东西,但如果你也想看到,请告诉我)
当我尝试从 main 打开 ItemListActivity 时遇到的错误是:
java.lang.NullPointerException: Attempt to invoke virtual method 'Device.getCar()' on a null object reference
但我真的不明白为什么会发生这种情况,因为即使我只是设置 car = null,我的应用程序也会一直运行,直到我进入 ItemListActivity 并选择 Car 片段。然后应用程序崩溃,但我看不到设置 car = mDevice.getCar() 是如何不允许我的应用程序从 main 进入 ItemListActivity 的,所以我很困惑为什么我得到一个空错误当我尝试打开 ItemListActivity。谢谢!
编辑:添加了构造函数代码