Проблема заключается в следующем : Есть список с продуктами ReyclerView и есть рядом с каждым продуктом кнопка при нажатии на которую продукт добавляется в список,который в дальнейшем будет выводиться в новой activity
, как "список выбранных продуктов". Я пытаюсь это реализовать, прописал метод,запускаю и мне вылетает ошибка:
03-11 13:39:40.921 9503-9503/com.example.coursework E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.coursework, PID: 9503
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.coursework/com.example.coursework.ProductSelectionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.coursework.ProductSelectionActivity.onCreate(ProductSelectionActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Вот сам код:
public class ProductSelectionActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference reference;
private ArrayList<ProductModel>list;
private ProductAdapter adapter;
private ArrayList<String>basketList;
private TextView productName;
private Button addProductToBasket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_selection);
recyclerView = findViewById(R.id.product_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
productName = findViewById(R.id.product_name);
addProductToBasket = findViewById(R.id.addProductToBasket);
addProductToBasket.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
basketList = new ArrayList<String>();
basketList.add(productName.getText().toString());
Toast.makeText(ProductSelectionActivity.this, basketList.size(), Toast.LENGTH_SHORT).show();
}
});
Intent intent = getIntent();
String prodPosition = intent.getStringExtra("position");
reference = FirebaseDatabase.getInstance().getReference().child("products").child(prodPosition);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<ProductModel>();
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
ProductModel p = new ProductModel();
p.setProductName(dataSnapshot1.child("name").getValue().toString());
list.add(p);
}
adapter = new ProductAdapter(ProductSelectionActivity.this,list);
recyclerView.setAdapter(adapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
Кнопка называется addProductToBasket
. ProductName
это TextView
в списке, где выводится название продукта.
Код Адаптера :
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder>{
private Context context;
private ArrayList<ProductModel> list;
public ProductAdapter(Context context, ArrayList<ProductModel> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
return new ProductViewHolder(LayoutInflater.from(context).inflate(R.layout.product_item_cardview,parent,false));
}
@Override
public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) { // подставляются значения в RecyclerView
holder.textProduct.setText(list.get(position).getProductName());
}
@Override
public int getItemCount() {
return list.size();
}
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
class ProductViewHolder extends RecyclerView.ViewHolder {
TextView textProduct;
CardView cv;
public ProductViewHolder(@NonNull View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv_product);
textProduct = itemView.findViewById(R.id.product_name);
}
}
}