RecyclerView only lists first item despite layout changes - java

I understand this might be a duplicate, but every other solution here didn't work in my case, such as changing the layout_height to wrap_content instead of match_parent.
My Firestore database has 2 values stored inside an array, and I want to display both of them (more in the future) in my RecyclerView, however, it only displays the first value, at position 0.
Here is my Activity where the Recycler and the Adapter are created:
ActivityOs
private FirestoreAdapter listAdapter;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference osRef = db.collection("cliente");
private DocumentReference docRef = osRef.document("clienteTeste");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_os);
RecyclerView recyclerView = findViewById(R.id.recyclerViewOs);
/*docRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.e("RESULTADO","result:" + document.toString());
}
}
});*/
Query query = osRef.orderBy("serviceOrder",
Query.Direction.ASCENDING);
FirestoreRecyclerOptions<ServiceDocument> options =
new FirestoreRecyclerOptions.Builder<ServiceDocument>()
.setQuery(osRef, ServiceDocument.class)
.build();
listAdapter = new FirestoreAdapter(options);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
#Override
protected void onStart() {
super.onStart();
listAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
listAdapter.stopListening();
}
The commented code shows me that the database does indeed return the 2 values stored in it.
Here is my Adapter class:
public class FirestoreAdapter extends FirestoreRecyclerAdapter<ServiceDocument, FirestoreAdapter.ViewHolder> {
public FirestoreAdapter(#NonNull FirestoreRecyclerOptions<ServiceDocument> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull ServiceDocument model) {
holder.osIdItem.setText(String.valueOf(model.serviceOrderArray.get(position).getId()));
holder.osClientItem.setText(model.serviceOrderArray.get(position).getClient().getName());
holder.osDateItem.setText(model.serviceOrderArray.get(position).getDate());
holder.osValueItem.setText(String.valueOf(model.serviceOrderArray.get(position).getTotalValue()));
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.layout_os_item, parent, false);
return new FirestoreAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView osIdItem;
private TextView osClientItem;
private TextView osDateItem;
private TextView osValueItem;
public ViewHolder(View itemView) {
super(itemView);
osIdItem = itemView.findViewById(R.id.osIDItem);
osClientItem = itemView.findViewById(R.id.osClientNameItem);
osDateItem = itemView.findViewById(R.id.osDateItem);
osValueItem = itemView.findViewById(R.id.osValueItem);
}
}
}
And here are my layouts, activity_os.xml where my RecyclerView is created, and layout_os_item.xml where the layouts for each item of the recycler are made.
Activity_os.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/activity_os"
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="wrap_content"
android:layout_marginBottom="0dp"
android:background="#color/white"
tools:context="com.leonardomaito.autocommobile.activities.OsActivity">
<include
android:id="#+id/include"
layout="#layout/layout_header_search" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/glRecyclerLimit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="124dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewOs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="650dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/glRecyclerLimit"
app:layout_constraintVertical_bias="0.0"
tools:listitem="#layout/layout_os_item" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btNewOs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Inserir OS"
android:onClick="createNewOs"
android:src="#drawable/custom_plus_icon"
app:backgroundTint="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.98"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/glRecyclerLimit"
app:layout_constraintVertical_bias="0.988"
app:rippleColor="#color/autocom_blue" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout_os_item.xml
<androidx.cardview.widget.CardView
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="wrap_content"
tools:showIn="#layout/activity_os"
android:background="#drawable/custom_card_view">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:background="#drawable/custom_card_view">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/custom_os_icon"
android:paddingLeft="5dp"/>
<TextView
android:id="#+id/osIDItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="N 00000"
android:textColor="#color/autocom_blue"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/osDateItem"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/osDateItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.943"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.222" />
<TextView
android:id="#+id/osClientNameItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textColor="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/osIDItem"
app:layout_constraintVertical_bias="0.111" />
<TextView
android:id="#+id/osValueItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:text="R$ 10,000"
android:textColor="#color/autocom_blue"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.791"
app:layout_constraintStart_toEndOf="#+id/osClientNameItem"
app:layout_constraintTop_toBottomOf="#+id/osDateItem"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Any help is welcome!
Edit
Current Result:
Expected Result
Basically, Item 0 or the first item is correct, however, the second item in my database should also appear in Item 1.

Related

Create Custom Dialog in an Adapter

I'm trying to display a Custom Dialog tapping a Card (I use recyclerview and firebase). I have an Adapter in which I have the onClick method. In there I want to put my custom dialog in order to open it when I click the card.
Here is the ArticoloAdapter.java
public class ArticoloAdapter extends RecyclerView.Adapter<ArticoloAdapter.VersionVH> {
private List<Articolo> listaArticoli;
private Context mCtx;
public ArticoloAdapter(Context mCtx, List<Articolo> listaArticoli){
this.mCtx = mCtx;
this.listaArticoli = listaArticoli;
}
#NonNull
#Override
public ArticoloAdapter.VersionVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.articolo_stock, parent, false);
return new VersionVH(view);
}
#Override
public void onBindViewHolder(#NonNull final ArticoloAdapter.VersionVH holder, int position) {
final Articolo articolo = listaArticoli.get(position);
holder.nome.setText(articolo.getNome());
if(articolo.getQuantita() == 1){
String quantita = Integer.toString(articolo.getQuantita()) + " Disponibile";
holder.quantita.setText(quantita);
} else {
String quantita = Integer.toString(articolo.getQuantita()) + " Disponibili";
holder.quantita.setText(quantita);
}
Picasso.get().load(articolo.getImg()).into(holder.img);
}
public int getItemCount(){
return listaArticoli.size();
}
public class VersionVH extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView img;
private TextView nome, quantita;
public VersionVH(View itemView){
super(itemView);
nome = itemView.findViewById(R.id.nomeArticolo);
quantita = itemView.findViewById(R.id.quantita);
img = itemView.findViewById(R.id.immagine);
cardView = itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here i want to put my custom_dialog
}
});
}
}
}
Here is my StockFragment (in which I have my card retrieved from Firebase):
public class StockFragment extends Fragment {
private RecyclerView recyclerView;
private List<Articolo> listaArticoli;
private ArticoloAdapter articoloAdapter;
private DatabaseReference query;
private LinearLayoutManager mLayoutManager;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_stock, container, false);
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
recyclerView = root.findViewById(R.id.recycleViewStock);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(articoloAdapter);
listaArticoli = new ArrayList<>();
query = FirebaseDatabase.getInstance().getReference("Articoli");
query.addListenerForSingleValueEvent(valueEventListener);
return root;
}
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listaArticoli.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Articolo articolo = snapshot.getValue(Articolo.class);
listaArticoli.add(articolo);
}
articoloAdapter = new ArticoloAdapter(getActivity(), listaArticoli);
recyclerView.setAdapter(articoloAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
};
}
and here is my custom_dialog.xml:
<?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="350dp"
android:layout_height="650dp"
android:background="#drawable/dialog_bg"
tools:ignore="UseSwitchCompatOrMaterialXml">
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06999999"
app:srcCompat="#android:drawable/sym_def_app_icon">
</ImageView>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="146dp"
android:layout_marginEnd="146dp"
android:text="Nome Prodotto"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.19999999">
</TextView>
<com.google.android.material.textview.MaterialTextView
android:id="#+id/materialTextView"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:gravity="center_horizontal"
android:inputType="textMultiLine"
android:text="Ciao questo è un testo di prova per daniele e vedere se gli piace o meno come esce"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3">
</com.google.android.material.textview.MaterialTextView>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="25dp"
android:layout_marginEnd="32dp"
android:hint="Nome"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/materialTextView"
app:layout_constraintVertical_bias="0.0"
android:layout_marginLeft="50dp"
android:layout_marginRight="32dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textNome"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout2"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="32dp"
android:layout_marginRight="32dp"
android:hint="Cognome"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout"
app:layout_constraintVertical_bias="0.0">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textCognome"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout3"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="32dp"
android:hint="Numero Di Telefono"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout2"
app:layout_constraintVertical_bias="0.0"
android:layout_marginLeft="50dp"
android:layout_marginRight="32dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/textNumero"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
<EditText
android:id="#+id/testEnabeld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Prova"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/switchGaranzia"
app:layout_constraintVertical_bias="0.0" />
<Switch
android:id="#+id/switchGaranzia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="2dp"
android:text="Garanzia"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textInputLayout3"
app:layout_constraintVertical_bias="0.0" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="49dp"
android:layout_height="328dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.925">
<ImageView
android:layout_width="35dp"
android:layout_height="54dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="1dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="16dp"
app:srcCompat="#drawable/icons8_utente_24" />
<ImageView
android:layout_width="35dp"
android:layout_height="54dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="16dp"
app:srcCompat="#drawable/icons8_utente_24" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Use the code below and add a child with match_parent attribute width and height inside the CardView and add the listener to the child view instead of the CardVeiw
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here i want to put my custom_dialog
Dialog dialog = new Dialog(mContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
dialog.getWindow().setLayout(ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
});

How to remove empty space when visibility is set to GONE

I've set the visibility of RecyclerView to gone. How would I be able to remove the empty space it takes?
I tried putting layout_height as wrap_content, but it still doesn't show anything.
Recycler View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Card View:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="250dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:id="#+id/cardView"
android:backgroundTint="#5A10E7"
android:elevation="90dp"
android:orientation="vertical"
android:textColor="#FFFFFF"
app:cardCornerRadius="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.282">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/Requestfulfilled"
android:layout_width="139dp"
android:layout_height="41dp"
android:layout_weight="1"
android:backgroundTint="#4CAF50"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Request Fullfilled"
android:text="Fulfilled"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/DeleteRequest"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="#+id/RlocationView"
app:layout_constraintTop_toBottomOf="#+id/RlocationView" />
<Button
android:id="#+id/DeleteRequest"
android:layout_width="139dp"
android:layout_height="41dp"
android:backgroundTint="#F44336"
android:clickable="true"
android:defaultFocusHighlightEnabled="true"
android:hint="Delete"
android:text="Delete"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/RlocationView"
app:layout_constraintHorizontal_bias="0.894"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.904" />
<TextView
android:id="#+id/RemailView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Email"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RdateView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/RbloodView"
android:layout_width="116dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Blood Group"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toStartOf="#+id/RdateView"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RdateView"
android:layout_width="164dp"
android:layout_height="42dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Date of Requirement"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/RlocationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/RbloodView"
app:layout_constraintTop_toBottomOf="#+id/RemailView" />
<TextView
android:id="#+id/RlocationView"
android:layout_width="340dp"
android:layout_height="35dp"
android:allowUndo="true"
android:focusable="auto"
android:focusableInTouchMode="true"
android:text="Location"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/Requestfulfilled"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RdateView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Code to set Card visibility as GONE:
public class yourRequestActivity extends AppCompatActivity {
private RecyclerView cardView;
private DatabaseReference dbRefForReq, dbRefForResp;
private FirebaseAuth mAuth;
private String AuthUserEmail, UserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.request_response_view);
mAuth = FirebaseAuth.getInstance();
AuthUserEmail = mAuth.getCurrentUser().getEmail();
UserID = mAuth.getCurrentUser().getUid();
dbRefForResp = FirebaseDatabase.getInstance().getReference().child("Responses").child(String.valueOf(UserID));
dbRefForReq = FirebaseDatabase.getInstance().getReference().child("Blood Requests");
dbRefForReq.keepSynced(true);
cardView = (RecyclerView) findViewById(R.id.recycleView);
cardView.setHasFixedSize(true);
cardView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<getDbContents> options =
new FirebaseRecyclerOptions.Builder<getDbContents>()
.setQuery(dbRefForReq, getDbContents.class)
.build();
FirebaseRecyclerAdapter<getDbContents, contentHolder> adapter = new FirebaseRecyclerAdapter<getDbContents, contentHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final contentHolder holder, final int position, #NonNull final getDbContents model) {
final int finalPosition = position + 1;
if (model.getUser().equals(AuthUserEmail)) {
dbRefForReq.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DataSnapshot checkFulfillment = dataSnapshot.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment");
if (checkFulfillment.exists()) {
if (checkFulfillment.child("Fulfilled").getValue().equals("yes")) {
/*------------- Set current user card as visible -----------------*/
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
} else {
holder.frameView.setVisibility(View.VISIBLE);
holder.fulfilled.setVisibility(View.VISIBLE);
holder.requestFulfilled.setVisibility(View.GONE);
/*------------- Set current user card as visible -----------------*/
holder.userEmail.setText(AuthUserEmail);
holder.bloodGroup.setText(model.getBloodGroup());
holder.dateOfRequirement.setText(model.getDate());
holder.Location.setText(model.getLocation());
////////////////////////////////////////////////////////////////////
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else if (model.getUser().equals(null)) {
holder.userEmail.setText("You have not posted any request");
} else {
holder.frameView.setVisibility(View.GONE);
}
/* Fulfilled and Delete button Functionality */
holder.fulfilled.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String, Object> response = new HashMap<>();
response.put("Fulfilled", "yes");
/*-----------------Remove Responses------------------*/
dbRefForResp.removeValue();
///////////////////////////////////////////////////////
/*-----------------Update and insert child with fulfilled status as yes------------------*/
dbRefForReq.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment").setValue(response).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(yourRequestActivity.this, "Request fulfillment status posted", Toast.LENGTH_SHORT).show();
}
});
////////////////////////////////////////////////////////////////////
holder.fulfilled.setVisibility(View.GONE);
holder.requestFulfilled.setVisibility(View.VISIBLE);
}
});
}
#NonNull
#Override
public contentHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_request_card, viewGroup, false);
contentHolder contentViewHolder = new contentHolder(view);
return contentViewHolder;
}
};
cardView.setAdapter(adapter);
adapter.startListening();
}
public class contentHolder extends RecyclerView.ViewHolder {
TextView userEmail, bloodGroup, dateOfRequirement, Location, requestFulfilled;
Button fulfilled;
FrameLayout frameView;
public contentHolder(#NonNull View itemView) {
super(itemView);
userEmail = itemView.findViewById(R.id.RemailView);
bloodGroup = itemView.findViewById(R.id.RbloodView);
dateOfRequirement = itemView.findViewById(R.id.RdateView);
Location = itemView.findViewById(R.id.RlocationView);
requestFulfilled = (TextView) itemView.findViewById(R.id.fulfilledTextMessage);
frameView = (FrameLayout) itemView.findViewById(R.id.cardFrame);
fulfilled = (Button) itemView.findViewById(R.id.Requestfulfilled);
}
}
}
I want to remove the blank space which occurs while visibility is set to GONE, as shown in the snapshot below.
Image of empty space on removing top card
Image before setting visibility GONE
Simply remove the object from the list if its user is not equal to AuthUserEmail and notify your adapter.
NO NEED TO MAKE VISBILITY GONE OF THE HOLDER VIEW
Your RecyclerView takes space even if visibility is set to gone. It still takes space because there are items that RecyclerView wants to display. Although you can fix this by removing the items RecyclerView wants to show. It would take a lot of memory if you want show that RecyclerView again because you still have to add the items back. What I would recommend is to wrap your RecyclerView with a layout eg. LinearLayout and set that layout's visibility to gone.
Try doing this:
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Place your RecyclerView here -->
<!-- change visibility of container view -->
</LinearLayout>
*Edit: You didn't explain it well. I get what you want now. You simply have to remove the item from your RecyclerView list. The best way to do this is by using DiffUtil. This a great tutorial online showing how you can implement it in Java. https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction
Cover your RecyclerView with a FrameLayout and then set your visibility over there.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_gravity="top"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
If this doesnt works then:
Cover your Cardview which is the layout that you designed for your Recyclerview with a FrameLayout. Anyone of them will surely work out for you.

Send data inside recyclerview with button in Fragment

I have 2 layouts where first layout for Fragment and second layout for RecyclerView. I have created CardView in RecyclerView, every CardView has some data. And I have created button below RecyclerView where the function of button for sending Data on CardView. My problem is I don't know how to send data when i click button in Fragment.
Fragment Layout :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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/container_daftar_alamat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.menu.menu_signin.menu.MenuAddressFragment">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMoveTambahAlamat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:background="#null"
android:drawableStart="#drawable/ic_tambah_alamat"
android:drawablePadding="10dp"
android:text="Tambah Alamat"
android:textAllCaps="false"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="normal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:text="Daftar Alamat"
android:textColor="#color/colorRed"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tambah_alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/gunakanAlamat"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="100dp"
android:background="#drawable/bg_button_red"
android:text="Gunakan Alamat"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="16sp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
RecyclerView Layout :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="12dp"
android:orientation="vertical"
app:cardBackgroundColor="#color/colorWhite"
app:cardCornerRadius="4dp"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/radioButton">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/nameUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Muhammad Rafi Bahrur Rizki"
android:textColor="#color/colorBlack"
android:textSize="14sp"
android:textStyle="bold"
tools:ignore="UnusedAttribute" />
<TextView
android:id="#+id/addressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:maxLines="1"
android:text="(Alamat Kantor)"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/streetName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:justificationMode="inter_word"
android:text="Mangga Dua Square Lantai 1 Jakarta,"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp"
tools:ignore="UnusedAttribute" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/blokAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="Blok C no. 148 - 150"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/cityAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/countryAddressUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="DKI Jakarta - 15025"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/phoneUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="0812951825"
android:textColor="#color/textColorSaksFifthAvenue"
android:textSize="14sp" />
</TableRow>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp">
<Button
android:id="#+id/buttonEdit"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:drawableStart="#drawable/ic_edit"
android:text="Edit"
android:textAllCaps="false"
android:textSize="12sp" />
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#id/buttonEdit"
android:drawableStart="#drawable/ic_delete"
android:text="Hapus"
android:textAllCaps="false"
android:textSize="12sp" />
</RelativeLayout>
</TableLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When i select RadioButton, only data in RadioButton will be obtained. And when i click button, the data will be send to another activity.
Adapter RecyclerView :
public class AdapterGetAddress extends RecyclerView.Adapter<AdapterGetAddress.ViewHolder> {
Context context;
private List<ModelGetAddress> modelGetAddressList;
private BaseApiService baseApiService;
private int previousSelected = -1;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_address, parent, false);
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
final ModelGetAddress adapterAddress = modelGetAddressList.get(position);
}
#Override
public int getItemCount() {
return modelGetAddressList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nameUser, addressUser, streetName, blokAddressUser, cityAddressUser, countryUser, phoneUser;
private RadioButton radioButton;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameUser = itemView.findViewById(R.id.nameUser);
addressUser = itemView.findViewById(R.id.addressUser);
streetName = itemView.findViewById(R.id.streetName);
countryUser = itemView.findViewById(R.id.countryAddressUser);
blokAddressUser = itemView.findViewById(R.id.blokAddressUser);
cityAddressUser = itemView.findViewById(R.id.cityAddressUser);
phoneUser = itemView.findViewById(R.id.phoneUser);
radioButton = itemView.findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
}
});
}
}
}
Code in Fragment :
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here's were i'm stuck
}
});
return view;
}
}
You can solve this via an interface.
public interface ItemClickedCallback{
void onItemClicked(String nameUser //, the other data you wanna pass );
}
pass it through the constructor of your adapter.
Use this adapter constructor
ItemClickedCallback callback;
public AdapterGetAddress(Context context, List<ModelGetAddress> modelGetAddressList, ItemClickedCallback callback) {
this.context = context;
this.modelGetAddressList = modelGetAddressList;
this.callback= callback;
}
When checking a radio button of any item; call the interface method, like this.
radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
previousSelected = getAdapterPosition();
notifyItemRangeChanged(0, modelGetAddressList.size());
// I want this All String will be send when i click button in Fragment
String getNameUser = nameUser.getText().toString();
String getAddressUser = streetName.getText().toString();
String getCountryUser = countryUser.getText().toString();
String getBlokUser = blokAddressUser.getText().toString();
String getCityUser = cityAddressUser.getText().toString();
String getPhoneUser = phoneUser.getText().toString();
callback.onItemClicked(getNameUser //, the rest..);
}
});
Now, when you initialize the adapter in the fragment, create the new interface via the constructor and assign the data to class variables like this.
public class MenuAddressFragment extends Fragment {
private Button gunakanAlamat;
private String nameUser_;
// the rest...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_address, container, false);
AdapterGetAddress adapter = new AdapterGetAddress(getActivity, list, new ItemClickedCallback() {
#Override
public void onItemClicked(String userName //, the rest..) {
// assign to the class variable like this
nameUser_ = userName;
// the rest..
}
}););
gunakanAlamat = view.findViewById(R.id.gunakanAlamat);
gunakanAlamat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Use the data as you want..
}
});
return view;
}
}

My recycler view doesn't show all items that it has, how can I fix it?

I have something wrong with recyclerView. It doesn't show all items. For example, recyclerView has 12 items, but it shows like 10 with a half items. I can set paddingBottom for it, and it shows all items, but I don't think it is a good way. How can I fix it? I think maybe it becouse of my buttons above it.
acctivity_search_coin.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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingBottom="50dp"
app:layout_constraintTop_toBottomOf="#+id/lianerForThreeBtn" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#FFFFFF"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:textSize="15sp"
android:drawablePadding="6dp"
android:gravity="center_vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/lianerForThreeBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/button2">
<Button
android:id="#+id/btn1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/btn2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/btn3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity_recycler_view_adapter_coin_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/denominationTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginEnd="8dp"
android:layout_toEndOf="#+id/secondIV"
android:textSize="20sp" />
<TextView
android:id="#+id/yearTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/denominationTV"
android:layout_alignStart="#+id/denominationTV"
android:layout_alignParentEnd="true"
android:layout_marginStart="0dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:textSize="20sp" />
<ImageView
android:id="#+id/firstIV"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_marginStart="0dp"/>
<ImageView
android:id="#+id/secondIV"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="4dp"
android:layout_toEndOf="#+id/firstIV"/>
</RelativeLayout>
RecyclerViewAdapterCoinList.java
public class RecyclerViewAdapterCoinList extends RecyclerView.Adapter<RecyclerViewAdapterCoinList.ViewHolder> {
private List<String> mYearList;
private List<String> mDenominationList;
private List<String> mImageList1;
private List<String> mImageList2;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
Context context;
RecyclerViewAdapterCoinList(Context context, List<String> denominationList,List<String> yearList, List<String> imageList1,List<String> imageList2) {
this.mInflater = LayoutInflater.from(context);
this.mYearList = yearList;
this.mDenominationList = denominationList;
this.mImageList1 = imageList1;
this.mImageList2 = imageList2;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.activity_recycler_view_adapter_coin_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String year = mYearList.get(position);
String denomination = mDenominationList.get(position);
String imageString1 = mImageList1.get(position);
String imageString2 = mImageList2.get(position);
holder.denominationTV.setText(denomination);
holder.yearTV.setText(year);
try {
Glide.with(context).load(imageString1).into(holder.firstIV);
Glide.with(context).load(imageString2).into(holder.secondIV);
}catch (Exception e){e.printStackTrace();}
}
// total number of rows
#Override
public int getItemCount() {
return mDenominationList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView denominationTV;
TextView yearTV;
ImageView firstIV;
ImageView secondIV;
ViewHolder(View itemView) {
super(itemView);
denominationTV = itemView.findViewById(R.id.denominationTV);
yearTV = itemView.findViewById(R.id.yearTV);
firstIV = itemView.findViewById(R.id.firstIV);
secondIV = itemView.findViewById(R.id.secondIV);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {
return mDenominationList.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Try adding app:layout_constraintBottom_toBottomOf="parent" in the recycler view and also make the height of the recycler view to be 0dp (match_constraint).

update RecyclerView after fetching data from server

I´ve got a problem with my RecyclerView. I want to update the Cards (inside the RecyclerView) after fetching the data from the server. First I thought there´s a problem with fetching or parsing the JSON-data, or sending the data via EventBus to the Fragment but when I display the parsed Objects in a TextView in the Fragment, everything is shown up. So the real problem is the RecyclerView / Adapter.
I´ve initialized the RecyclerView with an empty ArrayList, but when and HOW do I have to update the data for the RecyclerView? I´ve also read some Posts here on Stackoverflow, but I found no suitable solution...
This is the onCreateView from UserFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View mView = inflater.inflate(R.layout.fragment_users, container, false);
mRecyclerView = (RecyclerView) mView.findViewById(R.id.rv_user);
//set LayoutManager for View
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
//set Adapter for View
mAdapter = new UserAdapter(userList);
mRecyclerView.setAdapter(mAdapter);
Log.d(TAG, "onCreateView");
return mView;
}
and this is my UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
public static final String TAG = "UserAdapter";
private ArrayList<User> mUser;
public UserAdapter(ArrayList<User> user) {
mUser = user;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public CardView cv;
public TextView user_name;
public TextView user_lastName;
public TextView user_city;
public ViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.rv_user);
user_name = (TextView) itemView.findViewById(R.id.tv_user_name);
user_lastName = (TextView) itemView.findViewById(R.id.tv_user_lastname);
user_city = (TextView) itemView.findViewById(R.id.tv_user_city);
Log.d(TAG, "Viewholder");
}
}
//initialize Viewholder
#Override
public UserAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout_person, viewGroup, false);
Log.d(TAG, "onCreateViewHolder");
return new ViewHolder(mView);
}
//Bind data to view
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.user_name.setText(mUser.get(position).getUser().getFirstname());
holder.user_lastName.setText(mUser.get(position).getUser().getLastname());
holder.user_city.setText(mUser.get(position).getUser().getCity());
Log.d(TAG, "onBindViewHolder");
}
public void setUserList(ArrayList<User> user){
this.mUser = user;
notifyItemRangeChanged(0, user.size());
notifyDataSetChanged();
}
public void updateData(ArrayList<User> userList) {
mUser.clear();
mUser.addAll(userList);
notifyDataSetChanged();
}
public void removeItem(int position) {
mUser.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
Log.d(TAG, "getItemCount");
if (mUser == null) {
return 0;
} else {
return mUser.size();
}
} }
This is the onResponse in the MainActivity:
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseStr = response.body().string();
Gson gson = new Gson();
Type userListType = new TypeToken<ArrayList<User>>() {
}.getType();
final ArrayList<User> userList = gson.fromJson(responseStr, userListType);
CustomMessageEvent event = new CustomMessageEvent();
event.setUserList(userList);
EventBus.getDefault().post(event);
System.out.print(responseStr);
response.body().close();
}
}
UPDATE
XML-File (CardView)
<android.support.v7.widget.CardView 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/rv_user"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="3dp"
android:elevation="11dp"
android:foregroundGravity="center_horizontal"
android:scrollbars="vertical"
android:theme="#style/AppThemeFSF"
app:cardBackgroundColor="#color/cardview_light_background"
app:cardCornerRadius="4dp"
app:cardElevation="4dp"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:id="#+id/iv_profile_picture"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Name"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Nachname"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Stadt"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_user_name"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Name"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="14sp"/>
<TextView
android:id="#+id/tv_user_lastname"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Nachname"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="14sp"/>
<TextView
android:id="#+id/tv_user_city"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:gravity="left|center"
android:text="Stadt"
android:textAppearance="?android:textAppearanceLarge"
android:textSize="14sp"
/>
</LinearLayout>
</LinearLayout>
Thanks in advance guys, have a great day!
The problem is that you are not subscribing to receive you event back. So, when you call:
EventBus.getDefault().post(event);
No one is getting the event! And you are not populating you list. So your adapter has nothing to show.
Subscribe for the event like this:
#Subscribe
public void receiveEvent(CustomMessageEvent event){
mAdapter.updateData(event.getUserList())
}
This method should be in your fragments. If you put this inside your adapter you are going to violate the single responsibility principle. The only responsibility that your adapter should have is to link the list to the RecyclerView.
Happy coding!
Ok guys... I´ve got the solution! And this drives me a bit crazy... The problem was not the Adapter or the ViewHolder or anything inside the Fragment. The "real" problem was the text-size from the TextView inside the CardView-Elements. I deleted this properties and now every single dataset is available!
Thank you so much for your help and your tips! You´re great!
HAPPY coding ;)

Categories