J'essayais de créer des événements de clics réactifs dans mon RecyclerAdapter. Je ne comprends pas la logique derrière cela car mes données sont créées automatiquement par API, donc j'ai quelques boutons dans ma liste et j'aime avoir une réponse en cliquant dessus.
Voici mon code: p>
Ma classe d'adaptateur:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_marginTop="8dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@drawable/radius_all_two"
android:layout_width="match_parent"
android:layout_height="190dp">
<ImageView
android:layout_width="110dp"
android:layout_height="120dp"
android:src="@drawable/bestseller"
android:id="@+id/view_cart_item_image"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JBL- Grip 100"
android:id="@+id/view_cart_item_subject"
android:textColor="#000"
android:textSize="14dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="25dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_marginTop="15dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category"
android:textColor="#089bcc"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="48dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Headphones"
android:id="@+id/view_cart_item_category"
android:textSize="11dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="48dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Brand"
android:textColor="#089bcc"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:layout_marginTop="65dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JBL"
android:id="@+id/view_cart_item_brand"
android:textSize="11dp"
android:layout_marginLeft="180dp"
android:layout_marginTop="65dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 1,290.00"
android:id="@+id/view_cart_item_neww"
android:textColor="#00c1ab"
android:textSize="15dp"
android:textStyle="bold"
android:layout_marginLeft="140dp"
android:layout_marginTop="83dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 2,580.00"
android:textSize="11dp"
android:id="@+id/view_cart_item_old"
android:layout_marginLeft="140dp"
android:layout_marginTop="106dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- 50%"
android:textSize="11dp"
android:id="@+id/view_cart_item_discount"
android:layout_marginLeft="210dp"
android:textColor="#ba0101"
android:layout_marginTop="106dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="P 1,290.00"
android:textSize="11dp"
android:layout_marginLeft="140dp"
android:id="@+id/view_cart_item_new_depends_count"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="x"
android:textSize="12dp"
android:layout_marginLeft="240dp"
android:textColor="#000"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="@drawable/left_arrow"
android:text="x"
android:id="@+id/view_cart_item_increment"
android:textSize="12dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="@drawable/right_arrow"
android:text="x"
android:id="@+id/view_cart_item_decrement"
android:textSize="12dp"
android:layout_marginLeft="304dp"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="31dp"
android:layout_height="16dp"
android:textSize="11dp"
android:textAlignment="center"
android:text="100"
android:id="@+id/view_cart_item_count"
android:layout_marginLeft="270dp"
android:layout_marginTop="123dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color"
android:textSize="11dp"
android:textColor="#089bcc"
android:layout_marginLeft="140dp"
android:layout_marginTop="147dp"/>
<ImageView
android:layout_width="34dp"
android:layout_height="17dp"
android:textSize="12dp"
android:id="@+id/view_cart_variant"
android:background="@color/colorPrimaryDark"
android:layout_marginLeft="175dp"
android:layout_marginTop="145dp"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
Mon erreur en essayant mon OnclickEvent: (sur mon // TODO :)
public class EppViewCart extends Fragment {
View inflatedView = null;
EppViewCartDetails items;
private List<EppViewCartDetails> dataitems = new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
inflatedView = inflater.inflate(R.layout.fragment_epp_view_cart, container, false);
retriveSQLITE();
return inflatedView;
}
private void retriveSQLITE() {
SqLiteDB sql = new SqLiteDB(getContext());
SQLiteDatabase db = sql.getWritableDatabase();
Cursor c = sql.retrieveAddToCart(db);
ArrayList<AddToCartModel> get = new ArrayList<>();
while (c.moveToNext()) {
final AddToCartModel details = new AddToCartModel();
details.setID(c.getString(c.getColumnIndexOrThrow("ID")));
details.setDateTime(c.getString(c.getColumnIndexOrThrow("DateTime")));
details.setID_ProductMasterListV(c.getString(c.getColumnIndexOrThrow("ID_ProductMasterListV")));
details.setImageFile(c.getString(c.getColumnIndexOrThrow("ImageFile")));
details.setOrdered(c.getString(c.getColumnIndexOrThrow("Ordered")));
get.add(details);
APICaller service = EppMainFragmentPropertyClient.getRetrofit().create(APICaller.class);
View_Response gets = new View_Response("1", details.getID(), details.getID_ProductMasterListV());
Call<List<View_Data_Properties>> call = service.getView(gets);
call.enqueue(new Callback<List<View_Data_Properties>>() {
@Override
public void onResponse(Call<List<View_Data_Properties>> call, Response<List<View_Data_Properties>> response) {
//Discount
String q = String.format("%.2f", Double.parseDouble(response.body().get(0).getLess()));
long l = Math.round(Double.parseDouble(q));
String percent = l + "%";
double amount = Double.parseDouble(response.body().get(0).getNewPrice());
DecimalFormat formatter = new DecimalFormat("#,###.00");
double amount2 = Double.parseDouble(response.body().get(0).getSRP());
DecimalFormat formatter2 = new DecimalFormat("#,###.00");
items = new EppViewCartDetails(
response.body().get(0).getID(),
response.body().get(0).getName(),
response.body().get(0).getCategory(),
response.body().get(0).getProductsBrand(),
response.body().get(0).getNewPrice(),
"â± " + formatter.format(amount),
"â± " + formatter2.format(amount2),
"-" + percent,
details.getOrdered(), response.body().get(0).getHexValue(),
response.body().get(0).getImageFile());
dataitems.add(items);
prepareItems();
}
@Override
public void onFailure(Call<List<View_Data_Properties>> call, Throwable t) {
}
});
}
}
private void prepareItems() {
//Items
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
RecyclerView recyclerView = inflatedView.findViewById(R.id.view_cart_recycler);
recyclerView.setLayoutManager(layoutManager);
EppViewCartAdapter mAdapter = new EppViewCartAdapter(dataitems);
recyclerView.setAdapter(mAdapter);
}
}
Ma classe d'activité:
Process: eppmobile.intellismart.com.EPP, PID: 18675
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at eppmobile.intellismart.com.EPP.ViewCart.EppViewCartAdapter.onCreateViewHolder(EppViewCartAdapter.java:58)
at eppmobile.intellismart.com.EPP.ViewCart.EppViewCartAdapter.onCreateViewHolder(EppViewCartAdapter.java:22)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6794)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
My CardView:
public class EppViewCartAdapter extends RecyclerView.Adapter<EppViewCartAdapter.MyViewHolder> {
View itemView;
ImageView add,less;
private List<EppViewCartDetails> orderData;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView subject,category,brand,neww,newd,old,discount,count,color;
ImageView image;
public MyViewHolder(View view) {
super(view);
subject=view.findViewById(R.id.view_cart_item_subject);
category=view.findViewById(R.id.view_cart_item_category);
brand=view.findViewById(R.id.view_cart_item_brand);
neww=view.findViewById(R.id.view_cart_item_neww);
old=view.findViewById(R.id.view_cart_item_old);
discount=view.findViewById(R.id.view_cart_item_discount);
newd=view.findViewById(R.id.view_cart_item_new_depends_count);
count=view.findViewById(R.id.view_cart_item_count);
image=view.findViewById(R.id.view_cart_item_image);
add=itemView.findViewById(R.id.view_btn_add);
less=itemView.findViewById(R.id.view_btn_less);
}
}
public EppViewCartAdapter(List<EppViewCartDetails> preorderList) {
this.orderData = preorderList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_cart_card_view, parent, false);
//TODO: I was trying to make a set onlcick listener here but it has errors.
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EppViewCartDetails data= orderData.get(position);
double amount = Double.parseDouble(data.getCount())*Double.parseDouble(data.getNeww());
DecimalFormat formatter = new DecimalFormat("#,###.00");
holder.subject.setText(data.getSubject());
holder.category.setText(data.getCategory());
holder.brand.setText(data.getBrand());
holder.neww.setText("â± "+formatter.format(amount));
holder.newd.setText(data.getNewd());
holder.old.setText(data.getOld());
holder.old.setPaintFlags(holder.old.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.discount.setText(data.getDiscount());
holder.count.setText(data.getCount());
Picasso.with(itemView.getContext()).load("https://eppteststorage.blob.core.windows.net/images/"+data.getImage()).placeholder(R.drawable.small_logo).into(holder.image, new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
Log.e("tae tae"," PAkultie");
}
@Override
public void onError() {
}
}
);
}
@Override
public int getItemCount() {
return orderData.size();
}
}
My Cart_view:
entrez la description de l'image ici
(si vous voyez le " ", j'essayais d'y ajouter du responsive mais il s'exécute dans RecyclerView avec mon adaptateur, de sorte que je ne savais pas si où pourrais-je placer mon événement onclick.)
Ma vue dans recyclerview (j'ai mis en commentaire mon // TODO :) (Il est en cours d'exécution mais aucune fonction d'ajout et de soustraction.)
entrer l'image description ici
J'ai également essayé ceci pour (holder.add.setOn ...)
entrez la description de l'image ici
Et ceci: (MyViewHolder)
3 Réponses :
Il s'agit d'une exception de pointeur nul que vous devez comprendre.
vous devez remplacer itemView.findViewById (R.id.view_btn_add) par view.findViewById(R.id.view_btn_add)
car le nom de mise en page de l'adaptateur est voir pas itemview
il suffit de regarder votre code
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
et vous devez ajouter un écouteur de clic soit dans MyViewHolder () ou dans onBindViewHolder()
déplacez ce code
public MyViewHolder(View view) {
super(view);
}
J'ai essayé de le changer comme ceci view.findViewById (R.id.view_btn_add); mais c'est encore la même erreur.
Que voulez-vous dire, monsieur? désolé, j'ai fait beaucoup de tests mais je ne comprends pas pourquoi j'obtiens une erreur sur mon code. j'apprends aussi là-dessus puisque c'est ma première rencontre dans mon développement.
pouvez-vous publier votre mise en page xml (R.layout.view_cart_card_view) ici
mec vous n'avez aucune vue avec cet id R.id.view_btn_add en vue xml
Le plantage se produit car vous définissez l'écouteur de clics sur la vue nulle add .
Commencez par vérifier votre fichier de mise en page pour tous les ID définis dans la classe MyViewHolder. Je ne trouve pas l'identifiant view_btn_add dans votre fichier de mise en page. Attribuez-lui donc la vue appropriée.
Et puis dans votre méthode onCreateViewHolder, vous configurez l'écouteur onClick sur la vue add avant de l'initialiser.
Déplacez donc votre add.setOnClickListener (...) dans la classe MyViewHolder après avoir défini toutes les vues. Donc votre crash disparaîtra.
J'ai essayé ceci aussi, sur MyViewHolder (View view) {add = view.findViewById (R.id.view_btn_add); less = view.findViewById (R.id.view_btn_less); // et ce code ici add.setOnClickListener (new View.OnClickListener () {@Override public void onClick (View v) {Toast.makeText (itemView.getContext (), "Ajouter une réponse Click correctement.", Toast.LENGTH_SHORT). spectacle(); } }); } mais cela provoque à nouveau une erreur en tant que null
doit vérifier ma modification monsieur, j'ai été téléchargé une pièce jointe :)
Pouvez-vous mettre à jour votre question après avoir déplacé la méthode de clic dans la classe MyViewHolder?
je viens de joindre un fichier monsieur sur ma question .. (image du bas) code + erreur ci-joint monsieur :)
Oui, j'ai vérifié. Il semble que cela devrait être des œuvres. Veuillez donc vérifier l'ID de la vue add dans votre fichier de mise en page. Est-ce que cela correspond à l'identifiant de l'adaptateur?
J'ai vérifié ma mise en page, elle a été définie comme Imageview, je l'appelle aussi Imageview ... mais elle appelle l'erreur comme nulle.
hé @PAkultie J'ai vérifié votre code, je n'ai trouvé aucune vue avec l'identifiant view_btn_add . Attribuez donc cet identifiant avec la vue appropriée.
ouais je l'ai vu
Cela vous aide-t-il à identifier votre problème?
J'ai trouvé la réponse, dans mes autres données de vue panier, il y a le même identifiant dans mon xml afin que ive renomme simplement mes boutons dans mon xml et en hérite sur ma classe.
Mon viewCart:
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_cart_card_view, parent, false);
add=itemView.findViewById(R.id.view_cart_item_increment1);
less=itemView.findViewById(R.id.view_cart_item_decrement1);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
EppViewCartDetails data= orderData.get(position);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Add Click response properly.", Toast.LENGTH_SHORT).show();
}
});
}
Mon adaptateur:
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="@drawable/left_arrow"
android:text="x"
android:id="@+id/view_cart_item_increment1"
android:textSize="12dp"
android:layout_marginLeft="250dp"
android:layout_marginTop="123dp"/>
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:src="@drawable/right_arrow"
android:text="x"
android:id="@+id/view_cart_item_decrement1"
android:textSize="12dp"
android:layout_marginLeft="304dp"
android:layout_marginTop="123dp"/>