无法成功呈现回收者视图。得到错误:
“ java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView $ Adapter)'” >
即使我设置了RecyclerView
的首字母,也设置了线性布局并将其设置为适配器。谁能指出错误?
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_list);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
searchBar = (MaterialSearchBar) findViewById(R.id.searchBar);
if(getIntent() != null ){
if(getIntent().getStringExtra("categoryId") != null){
categoryId = getIntent().getStringExtra("categoryId");
fetchFoodList(categoryId);
}
}
databaseReference = FirebaseDatabase.getInstance().getReference("foodlist");
floatingActionButton = findViewById(R.id.food_list_fab);
recyclerView = findViewById(R.id.food_recycler_view);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
private void fetchFoodList(String categoryId) {
Query query = FirebaseDatabase.getInstance().getReference("foodlist").orderByChild("MenuId").equalTo(categoryId);
FirebaseRecyclerOptions<FoodModel> options = new FirebaseRecyclerOptions.Builder<FoodModel>().setQuery(query, new SnapshotParser<FoodModel>() {
@NonNull
@Override
public FoodModel parseSnapshot(@NonNull DataSnapshot snapshot) {
Log.d(TAG, "parseSnapshot: "+snapshot.child("Discount").getValue().toString());
return new FoodModel(snapshot.child("Description").getValue().toString(), snapshot.child("Discount").getValue().toString(), snapshot.child("Image").getValue().toString(), snapshot.child("MenuId").getValue().toString(), snapshot.child("Name").getValue().toString(), snapshot.child("Price").getValue().toString());
}
}).build();
FirebaseRecyclerAdapter firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<FoodModel, FoodViewHolder>(options) {
@NonNull
@Override
public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View v = inflater.inflate(R.layout.food_items, viewGroup, false);
return new FoodViewHolder(v);
}
@Override
protected void onBindViewHolder(@NonNull FoodViewHolder holder, final int position, @NonNull FoodModel model) {
holder.setFoodName(model.getName());
Log.d(TAG, "onBindViewHolder: "+model.getImage());
holder.setFoodImage(model.getImage());
holder.setFoodDescription(model.getDescription());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
答案 0 :(得分:2)
要解决此问题,请移动以下代码行:
recyclerView = findViewById(R.id.food_recycler_view);
此行之后:
searchBar = (MaterialSearchBar) findViewById(R.id.searchBar);.
通过这种方式,RecyclerView
对象将在使用之前初始化。