How to pass web service data into the RecylerView in Android? - java

I am taking data from "https://jsonplaceholder.typicode.com/todos" with using Retrofit, and I want to create RecyclerView with these data but my app is crashing.
What is the problem exactly? I also debuged app, I am taking all data from web but cannot put them into the recyclerview..
This is my adapter class
public class RecylerViewAdapter extends RecyclerView.Adapter<RecylerViewAdapter.MyViewHolder> {
List<Bilgiler> bilgilerList;
public RecylerViewAdapter(List<Bilgiler> bilgilerList) {
this.bilgilerList = bilgilerList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.userid.setText(bilgilerList.get(position).getUserId());
holder.id.setText(bilgilerList.get(position).getId());
holder.title.setText(bilgilerList.get(position).getTitle());
holder.checkBox.setChecked(bilgilerList.get(position).getCompleted());
}
#Override
public int getItemCount() {
return bilgilerList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView userid,id,title;
CheckBox checkBox;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
userid = itemView.findViewById(R.id.userid);
id = itemView.findViewById(R.id.id);
title = itemView.findViewById(R.id.titlee);
checkBox= itemView.findViewById(R.id.checkBox);
}
}
}
Finally, this is my Main class
public class MainActivity extends AppCompatActivity {
private List<Bilgiler> bilgilerList;
private RecyclerView recyclerView;
private RecylerViewAdapter recylerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyler);
take();
}
public void take() {
Call<List<Bilgiler>> bilgiList = ManagerAll.getInstance().getirBilgileri();
bilgiList.enqueue(new Callback<List<Bilgiler>>() {
#Override
public void onResponse(Call<List<Bilgiler>> call, Response<List<Bilgiler>> response) {
if (response.isSuccessful()) {
bilgilerList=response.body();
recylerViewAdapter= new RecylerViewAdapter(bilgilerList);
recyclerView.setAdapter(recylerViewAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Log.i("xxx",response.body().toString());
}
}
#Override
public void onFailure(Call<List<Bilgiler>> call, Throwable t) {
}
});
}
}
This is XML of page.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#color/purple_200"
>
<TextView
android:id="#+id/userid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="177dp"
android:layout_marginTop="39dp"
android:layout_marginEnd="177dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="178dp"
android:layout_marginTop="31dp"
android:layout_marginEnd="176dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/userid" />
<TextView
android:id="#+id/titlee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="183dp"
android:layout_marginTop="31dp"
android:layout_marginEnd="170dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/id" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="155dp"
android:layout_marginTop="21dp"
android:layout_marginEnd="162dp"
android:text="CheckBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/titlee" />
</androidx.constraintlayout.widget.ConstraintLayout>

Try calling the notifyDataSetChanged method on the adapter after getting the new data
bilgiList.enqueue(new Callback<List<Bilgiler>>() {
#Override
public void onResponse(Call<List<Bilgiler>> call, Response<List<Bilgiler>> response) {
if (response.isSuccessful()) {
bilgilerList=response.body();
recylerViewAdapter = new RecylerViewAdapter(bilgilerList);
recyclerView.setAdapter(recylerViewAdapter);
recylerViewAdapter.notifyDataSetChanged();
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
Log.i("xxx",response.body().toString());
}
}
#Override
public void onFailure(Call<List<Bilgiler>> call, Throwable t) {
}
});

Related

how to display data in shapeableimageview from firebase?

Given:method of receiving data which for some reason does not work. adapter for using SwipeCard koloda library
Goal: load photo and name from folder in firebase into shapeableimageview and textview respectively
Problem: the method of receiving data does not work and the name and photo are not loaded from the folder.
Adapter:
public class SwipeAdapter extends BaseAdapter {
private Context context;
private List<Integer> list;
public SwipeAdapter(Context context,List<Integer>list) {
this.context=context;
this.list=list;
}
#Override
public int getCount() {
return 20;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View view;
if(convertView==null)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_koloda,parent,false);
}else {
view=convertView;
}
return view;
}
}
Activity with a receive method
private SwipeAdapter adapter;
private List<Integer> list;
private TextView nameusercard;
private ShapeableImageView imageosnovnoe;
Koloda koloda;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
koloda=findViewById(R.id.koloda);
list=new ArrayList<>();
adapter=new SwipeAdapter(this,list);
koloda.setAdapter(adapter);
nameusercard=(TextView) findViewById(R.id.nameusercard);
imageosnovnoe=(ShapeableImageView) findViewById(R.id.imageosnovnoe);
}
private void getUserWInfo()
{
DatabaseReference reference= FirebaseDatabase.getInstance().getReference()
.child("Userw");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()&&snapshot.getChildrenCount()>0)
{
String name=snapshot.child("name").getValue().toString();
nameusercard.setText(name);
if (snapshot.hasChild("image")) {
String image = snapshot.child("image").getValue().toString();
Picasso.get().load(image).into(imageosnovnoe);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Xml item_koloda
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_margin="15dp"
app:cardCornerRadius="15dp"
app:cardElevation="5dp">
<LinearLayout
android:id="#+id/linearmain"
android:layout_width="match_parent"
android:layout_height="400dp"
android:orientation="vertical">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/imageosnovnoe"
android:layout_width="match_parent"
android:layout_height="400dp"
android:backgroundTint="#color/white"
android:scaleType="fitXY"
app:srcCompat="#drawable/aaaaa" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearhori"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:layout_gravity="bottom"
android:weightSum="3">
<ImageView
android:id="#+id/like"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_weight="1"
android:src="#drawable/sas"
/>
<ImageView
android:id="#+id/disslike"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_weight="1"
android:src="#drawable/aan"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
I tried to register the method in the adapter but it didn't work either.

Not Getting Data into my Recycler View using Firebase [duplicate]

This question already has answers here:
FirebaseListAdapter not pushing individual items for chat app - Firebase-Ui 3.1
(2 answers)
Closed 2 years ago.
My RecyclerView is not displaying any data.
buynow.java
public class buynow extends AppCompatActivity {
private RecyclerView recyclerView;
DatabaseReference ProductRef;
private EditText searchField;
private Button search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buynow);
ProductRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
searchField = (EditText) findViewById(R.id.search_field);
search_btn = (Button) findViewById(R.id.search_button);
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseUserSearch();
}
});
}
private void firebaseUserSearch(){
FirebaseRecyclerOptions<Products> options = new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(ProductRef,Products.class).build();
FirebaseRecyclerAdapter<Products, UsersViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<Products, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull UsersViewHolder holder, int position, #NonNull
Products model) {
holder.setDetails(model.getPname(), model.getPprice(), model.getPmrp(),
model.getPcondition(), model.getPimage());
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
//View Holder Class
public class UsersViewHolder extends RecyclerView.ViewHolder{
View mView;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(String phoneName, String phonePrice, String phoneMrp, String
phoneCondition, String phoneImage){
TextView phone_name = (TextView) mView.findViewById(R.id.product_name);
TextView phone_price = (TextView) mView.findViewById(R.id.product_price);
TextView phone_mrp = (TextView) mView.findViewById(R.id.product_mrp);
TextView phone_condition = (TextView) mView.findViewById(R.id.product_condition);
ImageView phone_image = (ImageView)mView.findViewById(R.id.product_image);
phone_name.setText(phoneName);
phone_price.setText(phonePrice);
phone_mrp.setText(phoneMrp);
phone_condition.setText(phoneCondition);
Picasso.with(getApplicationContext()).load(phoneImage).into(phone_image);
}
}
}
Products.java
public class Products {
private String pname,pprice,pimage,pmrp,pcondition;
public Products(){
}
public Products(String pname, String pprice, String pimage, String pmrp, String pcondition) {
this.pname = pname;
this.pprice = pprice;
this.pimage = pimage;
this.pmrp = pmrp;
this.pcondition = pcondition;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPprice() {
return pprice;
}
public void setPprice(String pprice) {
this.pprice = pprice;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public String getPmrp() {
return pmrp;
}
public void setPmrp(String pmrp) {
this.pmrp = pmrp;
}
public String getPcondition() {
return pcondition;
}
public void setPcondition(String pcondition) {
this.pcondition = pcondition;
}
}
Layout for RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:background="#color/primanrybg">
<RelativeLayout
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/buyphones_layout_bg">
<ImageView
android:id="#+id/product_image"
android:layout_width="60dp"
android:layout_height="90dp"
android:src="#drawable/rapid_pickup_foreground" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:textSize="16sp"
android:textColor="#color/black"
android:paddingStart="16dp"
android:paddingBottom="4dp"
android:text="iPhone 6s Space Grey (64GB)"/>
<LinearLayout
android:id="#+id/condition"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_marginLeft="16dp"
android:background="#drawable/search_frame"
android:layout_below="#id/product_name"
android:layout_marginBottom="3dp"
android:padding="2dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/yes_no_bg"
android:textColor="#color/white"
android:paddingStart="4dp"
android:padding="1dp"
android:paddingEnd="4dp"
android:text="Condition:" />
<TextView
android:id="#+id/product_condition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginRight="3dp"
android:padding="1dp"
android:textColor="#color/black"
android:text="Like New" />
</LinearLayout>
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/condition"
android:layout_toRightOf="#+id/product_image"
android:textSize="18sp"
android:textColor="#color/black"
android:paddingStart="16dp"
android:text="9,9999"/>
<TextView
android:id="#+id/product_mrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/product_price"
android:layout_below="#id/condition"
android:textSize="18sp"
android:text="24000"
android:textColor="#color/grey"
android:paddingStart="10dp"/>
I am not getting data into my RecyclerView. It is just not showing anything no error nothing. Any help is very appreciated.
I am getting my data from firebase and putting them into the recyclerview to display a list of products.
I would be really great if you can point out what is wrong with my code so that i can correct it.
You need to add startListening() to start listening for data in firebaseui:
The FirebaseRecyclerAdapter uses an event listener to monitor changes to the Firebase query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference in my Adapter class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm having these error on my coding
Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference onBindViewHolder(BrandAdapter.java:67) and
BrandAdapter.onBindViewHolder(BrandAdapter.java:34).
I'm not really sure what went wrong as I follow the tutorial very closely. And my database is not empty.
It contains child.
this is my adapter class
public class BrandAdapter extends RecyclerView.Adapter<BrandAdapter.MyViewHolder> {
private Context context;
List<String> key;
ArrayList<Brand> brandList;
public BrandAdapter(ArrayList<Brand> brandList) {
this.brandList = brandList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.brand_list, viewGroup, false);
context = viewGroup.getContext();
return new BrandAdapter.MyViewHolder(view);
}
public BrandAdapter(Context c) {
this.context = c;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.brand_name.setText(brandList.get(i).getBrand_name());
Picasso.with(context).load(brandList.get(i).getBrand_image()).into(myViewHolder.image);
// Picasso.with(mcontext).load(brand.getBrand_image()).into(myViewHolder.image);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String bName = brandList.get(i).getBrand_name();
String pic = brandList.get(i).getBrand_image();
Log.i("loz", bName);
Intent intent = new Intent(context, updateBrand.class);
intent.putExtra("brand_name", bName);
intent.putExtra("imgurl", pic);
context.startActivity(intent);
}
});
#Override
public int getItemCount() {
return brandList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView brand_name;
CardView brand_cv;
ImageView image, btnDelete;
LinearLayout frame_layout;
public MyViewHolder(View itemView) {
super(itemView);
brand_name = itemView.findViewById(R.id.name);
image = itemView.findViewById(R.id.image);
brand_cv = itemView.findViewById(R.id.brand_cv);
btnDelete = itemView.findViewById(R.id.delete);
frame_layout = itemView.findViewById(R.id.frame_layout);
}
}
}
my Brand Activity class
public class BrandActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ArrayList<Brand> brandList;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brand);
databaseReference = FirebaseDatabase.getInstance().getReference("Brand").child("");
recyclerView = findViewById(R.id.rv);
searchView = findViewById(R.id.searchView);
}
#Override
protected void onStart() {
super.onStart();
if (databaseReference != null) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
brandList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
brandList.add(ds.getValue(Brand.class));
}
}
BrandAdapter brandAdapter = new BrandAdapter(brandList);
recyclerView.setAdapter(brandAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(BrandActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/lightgray">
<TextView
android:id="#+id/brand_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sample"
android:textStyle="bold"
android:textColor="#color/white"
android:textAlignment="center"
android:background="#color/black"
android:textSize="20sp"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#FCFAFA"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/delete"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:visibility="visible"
app:srcCompat="#drawable/trash" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
</androidx.cardview.widget.CardView>
Brand model
public class Brand {
public String brand_id;
public String brand_name;
public String brand_image;
public Brand(){}
public Brand(String brand_id, String brand_name, String brand_image) {
this.brand_id = brand_id;
this.brand_name = brand_name;
this.brand_image = brand_image;
}
public String getBrand_id() {
return brand_id;
}
public void setBrand_id(String brand_id) {
this.brand_id = brand_id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getBrand_image() {
return brand_image;
}
public void setBrand_image(String brand_image) {
this.brand_image = brand_image;
}
}
In your MyViewHolder you are trying to find view that doesn't exist in your layout. So, try to change brand_name = itemView.findViewById(R.id.name) to brand_name = itemView.findViewById(R.id.brand_name). The same problem is also related to the other views in layout except image and delete: you don't have views with brand_cv and frame_layout ids.

Multiple TextView in RecycleView. how to do that?

Hello I just started the Android and I do not understand how to put more TextView in a RecyclerView
I have already seen this solution but I do not understand: How to create RecyclerView with multiple view type?
I tried to make a table with multiple dimensions but it did not work.
Adapter:
public class DeviceRecyclerView extends RecyclerView.Adapter<DeviceRecyclerView.ViewHolder> {
private String[]data;
public DeviceRecyclerView(String[]data){
this.data = data;
}
#Override
public DeviceRecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.device_list_row, parent , false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String name = data[position];
String rssi = data[position];
String uuid = data[position];
holder.DeviceNameTextView.setText(name);
holder.DeviceUUIDTextViewValue.setText(rssi);
holder.DeviceRSSIVTextViewValue.setText(uuid);
}
#Override
public int getItemCount() {
return data.length;
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView DeviceNameTextView;
TextView DeviceUUIDTextViewValue;
TextView DeviceRSSIVTextViewValue;
public ViewHolder (View itemView){
super(itemView);
DeviceNameTextView = itemView.findViewById(R.id.DeviceNameTextView);
DeviceUUIDTextViewValue = itemView.findViewById(R.id.DeviceUUIDTextViewValue);
DeviceRSSIVTextViewValue = itemView.findViewById(R.id.DeviceRSSIVTextViewValue);
}
}
MainActivity:
RecyclerView deviceList = (RecyclerView)findViewById(R.id.recycler_view_NoPaired);
deviceList.setLayoutManager(new LinearLayoutManager(this));
String[]names = {"Samsung64656"};
String[]rssi = {"ezez"};
String[]uuid = {"08:90:e5:90"};
deviceList.setAdapter(new DeviceRecyclerView(names));
My XML.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="180dp"
android:gravity="center_vertical"
tools:layout_editor_absoluteX="30dp"
tools:layout_editor_absoluteY="81dp">
<View
android:id="#+id/ColoredRect"
android:layout_width="10dp"
android:layout_height="160dp"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="#E27F26"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/DeviceNameTextView"
android:layout_width="133dp"
android:layout_height="24dp"
android:layout_marginStart="20dp"
android:layout_marginTop="16dp"
android:text="#string/device_name_label"
android:textColor="#color/TextColor"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/DeviceUUIDTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="8dp"
android:text="#string/deviceUUIDTextView"
android:textColor="#color/TextColor"
android:textSize="12sp"
app:layout_constraintBottom_toTopOf="#+id/DeviceUUIDTextViewValue"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/DeviceNameTextView" />
<TextView
android:id="#+id/DeviceUUIDTextViewValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="14sp"
android:text=""
android:textColor="#color/TextColor"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/DeviceUUIDTv" />
<TextView
android:id="#+id/rssiLabelTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="16dp"
android:text="#string/deviceRSSITextView"
android:textColor="#color/TextColor"
android:textSize="12sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/DeviceUUIDTextViewValue" />
<TextView
android:id="#+id/DeviceRSSIVTextViewValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="14sp"
android:text=""
android:textColor="#color/TextColor"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rssiLabelTextView" />
</android.support.constraint.ConstraintLayout>
Please explain me clearly how to do it. I am French sorry for spelling errors.
You just need to add some textView in you'r XML row (named device_list_row.xml), and init their in your adapter, like you have already did with 3 textview.
But's more easy with Object than use array of string, for data. for example in you'r case , make Device class object
Device.java
public class Device {
String name;
String rssi;
String uuid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRssi() {
return rssi;
}
public void setRssi(String rssi) {
this.rssi = rssi;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
And adapter code ->
public class DeviceRecyclerView extends RecyclerView.Adapter<DeviceRecyclerView.ViewHolder> {
private ArrayList<Device> deviceList;
public DeviceRecyclerView(Arraylist<Device> deviceList){
this.deviceList= deviceList;
}
#Override
public DeviceRecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.device_list_row, parent , false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Device device = deviceList.get(position);
holder.deviceNameTextView.setText(device.getName());
holder.deviceUUIDTextViewValue.setText(device.getUuid());
holder.deviceRSSIVTextViewValue.setText(device.getRssi());
}
#Override
public int getItemCount() {
return deviceList.length;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView deviceNameTextView, deviceUUIDTextViewValue, deviceRSSIVTextViewValue;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
deviceNameTextView = itemView.findViewById(R.id.DeviceNameTextView);
deviceUUIDTextViewValue = itemView.findViewById(R.id.DeviceUUIDTextViewValue);
deviceRSSIVTextViewValue = itemView.findViewById(R.id.DeviceRSSIVTextViewValue);
}
#Override
public void onClick(View v) {
Log.i("DEBUG","Item RecyclerView Cliqué");
}
}
With that, you init your Adapter with list of Device Object, who can have any variable has you want without need to pass more array or data to Adapter:-)
And for make a new Device, and use it in RV
Device device = new Device();
device.setName("Device Name 01");
device.setUuid("uuid value");
device.SetRssi("rssi value");
ArrayList<Device> deviceList = new ArrayList<>();
deviceList.add(device);
//Init adapter and fill it
DeviceRecyclerView deviceRecyclerView = new DeviceRecyclerView(deviceList);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(llm);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(deviceRecyclerView);

RecyclerView - I can't add more than 1 line

I'm with a problem to add more than 1 line(item) in my RecyclerView, the item overwrites the previous one when I tap the button, but if I create a List<> with data in hardcoded on onCreate, It works adding more than 1 line in the RecyclerView. Follow the code:
ListChecklistAdapter
public class ListChecklistAdapter extends RecyclerView.Adapter<ListChecklistAdapter.ListChecklistViewHolder> {
private List<Checklist> mChecklist;
private Context mCtx;
public ListChecklistAdapter(Context ctx, List<Checklist> checklists) {
mCtx = ctx;
mChecklist = checklists;
}
#Override
public ListChecklistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_checklist, parent, false);
return new ListChecklistViewHolder(view);
}
#Override
public void onBindViewHolder(ListChecklistViewHolder holder, int position) {
holder.cbItem.setText(mChecklist.get(position).getDescricao());
holder.cbItem.setChecked(mChecklist.get(position).isCheckado());
}
#Override
public int getItemCount() {
return mChecklist.size();
}
public class ListChecklistViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_checkbox)
CheckBox cbItem;
public ListChecklistViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public void refreshData(List<Checklist> item) {
this.mChecklist.clear();
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
}
item_checklist
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/item_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:paddingLeft="6dp"
android:text=" "
tools:text="Exemplo de item de lista" />
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.rcv_lista)
RecyclerView rvLista;
int valor;
private List<Checklist> lista;
private ListChecklistAdapter listChecklistAdapter;
#BindView(R.id.btn_add_item)
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
private int cont() {
return valor++;
}
public void novoItem(View view) {
lista = new ArrayList<>();
lista.add(new Checklist("Item " + (cont() + 1), true));
loadRecycler(lista);
}
private void loadRecycler(List<Checklist> lista) {
if (listChecklistAdapter == null) {
Log.i("LOG", "IF");
listChecklistAdapter = new ListChecklistAdapter(this, lista);
rvLista.setAdapter(listChecklistAdapter);
rvLista.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvLista.addItemDecoration(new DividerItemDecoration(this, 1));
return;
} else {
Log.i("LOG", "ELSE");
listChecklistAdapter.refreshData(lista);
listChecklistAdapter.onAttachedToRecyclerView(rvLista);
}
}
}
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context="teste.com.br.recyclercomcheckbox.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv_lista"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:onClick="novoItem"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="+ novo item"
android:textColor="#009688" />
</LinearLayout>
Just remove this line this.mChecklist.clear(); from your refreshData() method.
public void refreshData(List<Checklist> item) {
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
#Nilesh Rathod solved the problem! I just deleted this.mChecklist.clear(); from the ListCheckAdapter.java > refreshData()
Thanks for everyone to help too!

Categories