RecyclerView only displaying the top Data - android

Chat class
private void fetchMessages() {
rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Adapter
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>{
private List<Messages> userMessageList;
public MessageAdapter (List<Messages>userMessageList)
{
this.userMessageList = userMessageList;
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView messageText;
public MessageViewHolder(View view)
{
super(view);
messageText = (TextView)view.findViewById(R.id.message_text);
}
}
#Override
public int getItemCount()
{
return userMessageList.size();
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.messages_layout_of_users,parent,false);
return new MessageViewHolder(V);
}
#Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
Messages messages = userMessageList.get(position);
holder.messageText.setText(messages.getMessage());
}
}
Messages.class
public class Messages {
private String message;
private String type;
private boolean seen;
private long time;
public Messages(){};
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isSeen() {
return seen;
}
public void setSeen(boolean seen) {
this.seen = seen;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
XML
Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textSize="15dp"
android:id="#+id/message_text"
android:background="#drawable/messages_text_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
Activity Chat layout
<?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="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
app:titleTextColor="#ffffff"
>
<TextView
android:textColor="#ffffff"
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.Toolbar>
<Button
android:id="#+id/add_image"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<EditText
android:id="#+id/input_message"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/send_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="#+id/send_message"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<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:layout_below="#+id/toolbar"
android:layout_above="#+id/input_message"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/messageList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</RelativeLayout>
Fetching of the message is fine. But it wont fetch all the messages. Only the first message is displayed. why is this happening?

Have You Tried Scrolling The Page .
Since your RecyclerView ListItem has layout_height and layout_width as matchparent
Every item could be taking Full Space On the Window
Try Scrolling The Window
Or set layout_height as wrap content For constraint Layout
Or Try Increasing layout_height Or recycler view To match_parent

Related

UI bug while updating recycler view

I'm using FirebaseUI FirestorePagingAdapter for recycler view adapter and the recycler view uses GridLayout type with 2 columns . The recycler view item block cantains 1 image view and few others textView , when I scroll down the list and scroll back up top the image view size decreases , this bug continues every time I scroll down and back up .
It also happens when I update the adapter .
Below is the code for it . Btw I'm using Navigation Component UI.
private FirestorePagingAdapter<ProductModel, HomePagingHolder> pagingAdapter;
private FirestorePagingOptions<ProductModel> pagingOptions;
private final PagingConfig config = new PagingConfig(15, 10, false);
POJO class
public class ProductModel {
private boolean availability;
private DocumentReference category_reference;
private boolean customizable;
private String delivery_fee;
private String description;
private String max_order_quantity;
private String name;
private String price;
private List<String> thumbnails;
private String productID;
public ProductModel(){}
public ProductModel(boolean availability, DocumentReference category_reference, boolean customizable,
String delivery_fee, String description, String max_order_quantity, String name, String price, List<String> thumbnails) {
this.availability = availability;
this.category_reference = category_reference;
this.customizable = customizable;
this.delivery_fee = delivery_fee;
this.description = description;
this.max_order_quantity = max_order_quantity;
this.name = name;
this.price = price;
this.thumbnails = thumbnails;
}
public boolean isAvailability() {
return availability;
}
public void setAvailability(boolean availability) {
this.availability = availability;
}
public DocumentReference getCategory_reference() {
return category_reference;
}
public void setCategory_reference(DocumentReference category_reference) {
this.category_reference = category_reference;
}
public String getProductID() {
return productID;
}
public void setProductID(String productID) {
this.productID = productID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public boolean isCustomizable() {
return customizable;
}
public void setCustomizable(boolean customizable) {
this.customizable = customizable;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
public String getMax_order_quantity() {
return max_order_quantity;
}
public void setMax_order_quantity(String max_order_quantity) {
this.max_order_quantity = max_order_quantity;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public List<String> getThumbnails() {
return thumbnails;
}
public void setThumbnails( List<String> thumbnails) {
this.thumbnails = thumbnails;
}
}
ViewHolder class
static class HomePagingHolder extends RecyclerView.ViewHolder {
private final TextView pName;
private final TextView pPrice;
private final ImageView pImg;
private final TextView pThumbnailCount;
public HomePagingHolder(#NonNull View itemView) {
super(itemView);
pName = itemView.findViewById(R.id.productName);
pPrice = itemView.findViewById(R.id.productPrice);
pImg = itemView.findViewById(R.id.productImg);
pThumbnailCount = itemView.findViewById(R.id.thumbnail_count_txt);
}
}
Inside the Fragment
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
...
...
if (pagingOptions == null) {
getProductFromFireStore(false);
initFirestoreUIAdapter();
}
}
Getting the data
private void getProductFromFireStore(boolean check) {
pagingOptions = new FirestorePagingOptions.Builder<ProductModel>().setLifecycleOwner(this).setQuery(productCollection,
config, snapshot -> {
ProductModel model = snapshot.toObject(ProductModel.class);
if (model != null) {
model.setProductID(snapshot.getId());
}
return Objects.requireNonNull(model);
}).build();
if (check) {
pagingAdapter.updateOptions(pagingOptions);
}
}
productCollection inside the setQuery(...) points to a Collection reference inside Firestore.
Adapter
private void initFirestoreUIAdapter() {
pagingAdapter = new FirestorePagingAdapter<ProductModel, HomePagingHolder>(pagingOptions) {
#Override
protected void onBindViewHolder(#NonNull HomePagingHolder holder, int position, #NonNull ProductModel model) {
holder.pName.setText(model.getName());
holder.pPrice.setText(String.format("%s %s", getResources().getString(R.string.rupee_symbol), model.getPrice()));
holder.pThumbnailCount.setText(String.valueOf(model.getThumbnails().size()));
Glide.with(requireContext()).load(model.getThumbnails().get(0)).into(holder.pImg);
holder.itemView.setOnClickListener(view -> {
bundle.putString(Fire.FIELD_PRODUCT_ID, model.getProductID());
NavHostFragment.findNavController(HomeFragment.this).navigate(R.id.action_home_to_productFragment2, bundle);
});
}
#NonNull
#Override
public HomePagingHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(requireContext()).inflate(R.layout.block_home_product_item, parent, false);
return new HomePagingHolder(v);
}
};
}
Recycler view item block
<?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="wrap_content"
android:background="#drawable/product_item_ripple"
android:clickable="true"
android:focusable="true">
<com.google.android.material.card.MaterialCardView
android:id="#+id/imgCard"
android:layout_width="180dp"
android:layout_height="220dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:cardBackgroundColor="#color/colorSurface"
app:cardCornerRadius="8dp"
app:cardElevation="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
app:cardCornerRadius="8dp"
app:cardElevation="0dp">
<ImageView
android:id="#+id/productImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:background="#color/colorSurface"
android:src="#drawable/log_in_lounge_bg"
tools:ignore="ContentDescription" />
</androidx.cardview.widget.CardView>
<TextView
android:id="#+id/thumbnail_count_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/white_txt_bg"
android:drawablePadding="4dp"
android:elevation="4dp"
android:fontFamily="#font/nunito"
android:text="3"
app:drawableEndCompat="#drawable/ic_multiple_image" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:id="#+id/productName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ellipsize="end"
android:fontFamily="#font/montserrat"
android:maxLines="2"
android:text="Arm chair blue color"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="#+id/imgCard"
app:layout_constraintStart_toStartOf="#+id/imgCard"
app:layout_constraintTop_toBottomOf="#+id/imgCard" />
<TextView
android:id="#+id/productPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/nunito"
android:text="TextView"
android:textColor="#color/colorTextMini"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/productName"
app:layout_constraintStart_toStartOf="#+id/productName"
app:layout_constraintTop_toBottomOf="#+id/productName" />
</androidx.constraintlayout.widget.ConstraintLayout>
Item block
<?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="wrap_content"
android:background="#drawable/product_item_ripple"
android:clickable="true"
android:focusable="true">
<com.google.android.material.card.MaterialCardView
android:id="#+id/imgCard"
android:layout_width="180dp"
android:layout_height="220dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:cardBackgroundColor="#color/colorSurface"
app:cardCornerRadius="8dp"
app:cardElevation="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/productImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_centerInParent="true"
android:background="#color/colorSurface"
android:src="#drawable/log_in_lounge_bg"
app:shapeAppearance="#style/IsthmusShapeableImageStyle"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/thumbnail_count_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/white_txt_bg"
android:drawablePadding="4dp"
android:elevation="4dp"
android:fontFamily="#font/nunito"
tools:text="3"
app:drawableEndCompat="#drawable/ic_multiple_image" />
</RelativeLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:id="#+id/productName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:ellipsize="end"
android:fontFamily="#font/montserrat"
android:maxLines="2"
tools:text="Arm chair blue color"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="#+id/imgCard"
app:layout_constraintStart_toStartOf="#+id/imgCard"
app:layout_constraintTop_toBottomOf="#+id/imgCard" />
<TextView
android:id="#+id/productPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/nunito"
tools:text="TextView"
android:textColor="#color/colorTextMini"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/productName"
app:layout_constraintStart_toStartOf="#+id/productName"
app:layout_constraintTop_toBottomOf="#+id/productName" />
</androidx.constraintlayout.widget.ConstraintLayout>

How to integrate dialogflow in android apps

I want to integrate my chatbot(created by dialogflow) to my apps and I have create the xml files but I didn't find a way how to match between them.
I have already database using room library persistance .And, I'm coding with Java.
How can I itegrate my agent into my apps?And how to add a recylerViewAdapter for my chatmessages.
Thank you
msg_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/leftText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_alignParentStart="true"
android:text="Hello this is me!!"
android:padding="8dp"
android:textColor="#212121"
android:background="#drawable/left_background"
android:elevation="2dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/rightText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_alignParentEnd="true"
android:text="Hi!! How are you!!"
android:background="#drawable/right_background"
android:textColor="#fff"
android:padding="8dp"
android:elevation="2dp"
android:layout_alignParentRight="true" />
</RelativeLayout>
Chatbot.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".Chatbot">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:paddingBottom="50dp"
android:clipToPadding="false"
android:background="#f4f6f7"
tools:listitem="#layout/msglist"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="10dp"
android:elevation="2dp"
android:layout_toStartOf="#+id/addBtn"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/addBtn">
<EditText
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#fff"
android:hint="Type a Message"
android:minHeight="50dp"
android:textSize="18sp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/addBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentEnd="true"
android:background="#drawable/back_fab"
android:layout_marginBottom="10dp"
android:layout_marginEnd="5dp"
android:elevation="4dp"
android:layout_centerInParent="true"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp">
<ImageView
android:id="#+id/fab_img"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_centerInParent="true"
android:src="#drawable/ic_send_white_24dp"
android:tint="#fff"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
ChatbotActivity
public class Chatbot extends AppCompatActivity implements AIListener {
RecyclerView recyclerView;
EditText message;
RelativeLayout addBtn;
ChatbotAdapter adapter;
Boolean flagFab = true;
private AIService aiService;
private AIServiceContext customAIServiceContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbot);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
message = (EditText)findViewById(R.id.message);
addBtn = (RelativeLayout)findViewById(R.id.addBtn);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = message.getText().toString().trim();
if (!message.equals("")) {
ChatMessage chatMessage = new ChatMessage(msg, "user");
}
message.setText("");
}
});
adapter = new ChatbotAdapter();
recyclerView.setAdapter(adapter);
final AIConfiguration config = new AIConfiguration("Acces",
AIConfiguration.SupportedLanguages.French,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, config);
customAIServiceContext = AIServiceContextBuilder.buildFromSessionId("ID");
aiService.setListener(this);
final AIDataService aiDataService = new AIDataService(config);
final AIRequest aiRequest = new AIRequest();
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = message.getText().toString().trim();
if (!msg.equals("")) {
aiRequest.setQuery(msg);
new AsyncTask<AIRequest,Void, AIResponse>(){
#Override
protected AIResponse doInBackground(AIRequest... aiRequests) {
final AIRequest request = aiRequests[0];
try {
final AIResponse response =
aiDataService.request(aiRequest);
return response;
} catch (AIServiceException e) {
}
return null;
}
#Override
protected void onPostExecute(AIResponse response) {
if (response != null) {
Result result = response.getResult();
String reply = result.getFulfillment().getSpeech();
}
}
}.execute(aiRequest);
}
else {
aiService.startListening();
}
message.setText("");
}
});
}
#Override
public void onResult(AIResponse response) {
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
}
#Override
public void onListeningCanceled() {
}
#Override
public void onListeningFinished() {
}
}
Chatmessage
public class ChatMessage {
private String msgText;
private String msgUser;
public ChatMessage(String msgText, String msgUser){
this.msgText = msgText;
this.msgUser = msgUser;
}
public ChatMessage(){
}
//+getter & setter
}
ChatbotAdapter
//I don't know how to code this class
public class ChatbotAdapter extends RecyclerView.Adapter<ChatbotAdapter.ChatHolder>
{
#NonNull
#Override
public ChatHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.msglist, viewGroup, false);
return new ChatHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ChatHolder chatHolder, int i) {
}
#Override
public int getItemCount() {
return 0;
}
public class ChatHolder extends RecyclerView.ViewHolder {
TextView leftText, rightText;
public ChatHolder(View itemView) {
super(itemView);
leftText = (TextView) itemView.findViewById(R.id.leftText);
rightText = (TextView) itemView.findViewById(R.id.rightText);
}
}
}
Your question is not that clear. Please add some more details like what is you want, what you have implemented and what issue is coming.
You may also try my implementation. I am not using Recycler view in my implementation, but you could follow the following article I wrote for integrating Dialogflow with Android. Try an follow the V2 version as V1 will phase out by October this year.
Also, Do not use fragment for Chatbot as it somehow does not work. Try and make a simple chatbot using my implementation and then you can work towards your own implementation.
Hope it works.

Unable to populate RecyclerView adapter with Firebase data

I'm trying to fetch the data from my Firebase database but from some reason it doesn't work, so I'll try to provide as much info as posible ..
This is the database snapshot:
This is a POJO class:
public class Result2 implements Serializable {
private int score;
private String userName;
public Result2(int score, String userName) {
this.score = score;
this.userName = userName;
}
public int getScore() {
return score;
}
public String getUserName() {
return userName;
}
}
This is my activitys layout called activity_results.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:weightSum="2"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:textColor="#000"
android:textSize="16sp"
android:gravity="center"
android:text="USERNAME"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<TextView
android:textColor="#000"
android:textSize="16sp"
android:text="SCORE"
android:gravity="center"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
<View
android:background="#000"
android:layout_width="match_parent"
android:layout_height="1dp"
/>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:clipToPadding="false"
android:scrollbars="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
As you can see, I want to have 2 TextViews that will act like tabs and a RecyclerView underneath that will show the data
Here is my Adapters ViewHolder layout called score_view_holder.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/username"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textSize="14sp" />
<TextView
android:id="#+id/score"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textSize="14sp" />
</LinearLayout>
<View
android:background="#4545"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"/>
So it will contain two horizontal TextViews and a View as a line below..
Here is my Adapter:
public class ScoreAdapter extends RecyclerView.Adapter<ScoreAdapter.ScoreViewHolder> {
private List<Result2> results = new ArrayList<>();
public void setResults(List<Result2> results) {
this.results.clear();
this.results.addAll(results);
notifyDataSetChanged();
}
#Override
public ScoreAdapter.ScoreViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.score_view_holder, parent, false);
return new ScoreAdapter.ScoreViewHolder(view);
}
#Override
public void onBindViewHolder(ScoreAdapter.ScoreViewHolder holder, int position) {
Result2 result = getResult(position);
if (result != null) {
holder.setUsername(result.getUserName() != null ? result.getUserName() : "-");
holder.setScore(String.valueOf(result.getScore()));
}
}
private Result2 getResult(int position) {
return !results.isEmpty() ? results.get(position) : null;
}
#Override
public int getItemCount() {
return results.size();
}
public class ScoreViewHolder extends RecyclerView.ViewHolder {
private TextView username;
private TextView score;
public ScoreViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
score = itemView.findViewById(R.id.score);
}
public void setUsername(String username) {
this.username.setText(username);
}
public void setScore(String score) {
this.score.setText(score);
}
}
}
It should get List of Result2 objects and just set text in those two TextViews (username and score)
And finally my Activity where all the magic doesn't happen :)
public class Results extends AppCompatActivity {
private DatabaseReference mDatabase;
private ScoreAdapter scoreAdapter;
private RecyclerView recyclerView;
private List<Result2> results = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
recyclerView = findViewById(R.id.recycler_view);
scoreAdapter = new ScoreAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(scoreAdapter);
mDatabase = FirebaseDatabase.getInstance().getReference();
loadResults();
}
private void loadResults() {
mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Result2 result = childSnapshot.getValue(Result2.class);
if(result != null) {
results.add(result);
}
}
Toast.makeText(Results.this, String.valueOf(results.size()), Toast.LENGTH_SHORT).show();
scoreAdapter.setResults(results);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
}
Funniest thing, Toast shows correct number of Results, but when scoreAdapter.setResults(results); is called, screen blinks and goes back to first screen... Does it have something to do with a POJO class, or onDataChange method or main thread?
I tried with debugging and also funny thing here.. This is what is caught on breakpoint inside ScoreAdapter setResult method:
I tried setting breakpoints inside onBindViewHolder and getResults() but none of them gets called :o
if(result != null) {
results.add(result);
}
See here you are checking result != null. But result is a reference variable of type Results. So it will not be null, it will contains some value.
So, try removing that if statement and do only -
results.add(result);

Recycler View with firebase just displaying the first instance

Hi I ma trying to build an app that has a list of events retrieved from a firebase database but when I run it it displays just the first event stored.
there is the code I used to generate the list:
private RecyclerView recyclerView;
private FirebaseRecyclerAdapter<Event,EventViewHolder> firebaseRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendario);
recyclerView = (RecyclerView) findViewById(R.id.eventiList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Query query = FirebaseDatabase.getInstance().getReference("Eventi");
FirebaseRecyclerOptions<Event> options =
new FirebaseRecyclerOptions.Builder<Event>().setQuery(query, Event.class).build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Event, EventViewHolder>(options) {
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.event_layout, parent, false);
return new EventViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull EventViewHolder holder, final int position, #NonNull Event model) {
holder.setDay(model.getData().substring(0,2));
holder.setMonth(model.getMese());
holder.setName(model.getNome());
holder.setLuogo(model.getLuogo());
holder.setendStart(model.getOra_inizio()+ " - "+ model.getOra_fine());
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class EventViewHolder extends RecyclerView.ViewHolder
{
View mview;
public EventViewHolder(View itemView)
{
super(itemView);
mview=itemView;
}
public void setDay(String day)
{
TextView mtext= (TextView)mview.findViewById(R.id.day);
mtext.setText(day);
}
public void setName(String name)
{
TextView maut=(TextView)mview.findViewById(R.id.Event_Name);
maut.setText(name);
}
public void setMonth(String month)
{
TextView maut=(TextView)mview.findViewById(R.id.month);
maut.setText(month);
}
public void setLuogo(String luogo)
{
TextView maut=(TextView)mview.findViewById(R.id.luogo);
maut.setText(luogo);
}
public void setendStart(String endStart)
{
TextView maut=(TextView)mview.findViewById(R.id.start_end);
maut.setText(endStart);
}
}
#Override
protected void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
//mAdapter.stopListening();
firebaseRecyclerAdapter.stopListening();
}
this is the code of the model class
public class Event {
private String Nome;
private String data;
private String descrizione;
private String luogo;
private String mese;
private String ora_fine;
private String ora_inizio;
private String type;
public Event()
{
}
public Event(String nome, String data, String descrizione, String luogo, String mese, String ora_fine, String ora_inizio, String type) {
Nome = nome;
this.data = data;
this.descrizione = descrizione;
this.luogo = luogo;
this.mese = mese;
this.ora_fine = ora_fine;
this.ora_inizio = ora_inizio;
this.type = type;
}
public String getNome() {
return Nome;
}
public String getData() {
return data;
}
public String getDescrizione() {
return descrizione;
}
public String getLuogo() {
return luogo;
}
public String getMese() {
return mese;
}
public String getOra_fine() {
return ora_fine;
}
public String getOra_inizio() {
return ora_inizio;
}
public String getType() {
return type;
}
}
this is the Calendar activity layout
<android.support.v4.widget.DrawerLayout 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"
tools:context=".Calendario"
android:id="#+id/Calendar_draw">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/eventiList"></android.support.v7.widget.RecyclerView>
</android.support.v4.widget.DrawerLayout>
This is the code for the recycler view row
<?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="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="119dp"
android:background="#color/darkBlue">
<TextView
android:id="#+id/day"
android:layout_width="86dp"
android:layout_height="66dp"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/Event_Name"
android:layout_marginStart="18dp"
android:textColor="#color/white"
android:textSize="50dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="18dp" />
<TextView
android:id="#+id/month"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/day"
android:layout_marginBottom="11dp"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_alignLeft="#+id/day" />
<TextView
android:id="#+id/Event_Name"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="124dp"
android:layout_marginTop="13dp"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textColor="#color/white"
android:textStyle="bold"
android:layout_alignParentLeft="true"
android:layout_marginLeft="124dp" />
<TextView
android:id="#+id/start_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginStart="135dp"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/white"
android:textStyle="italic" />
<TextView
android:id="#+id/luogo"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_alignStart="#+id/start_end"
android:layout_below="#+id/day"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/white"
android:textStyle="italic" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
As you can see from the image that follows it displays just one event and I have 5 in the database
Display
The code worked fine for other lists that are in the app I don't understand why it is not working for this one hope I can get an answer here, thanks
Edit: this is the Database tree
Database Tree
Problem Solved, the layout_height parameter was set to match_parent in the event_layout LinearLayout and CardView. I set it to wrap_content on both and it worked.

Display firebase data in custom recyclerview

I want to display the firebase data into the custom recyclerview. The data is added to the firebase from the arduino which i want to display in the app itself.
i am trying to run the following code but the app simply opens and doesnt display anything. Each time the app runs on the android, it opens and doesnt diaplay anything. The same code is working with my other 2-3 projects but doesnt seem to work in this case.
1.MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DatabaseReference myref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.mango);
myref = FirebaseDatabase.getInstance().getReference().child("database").child("values");
FirebaseRecyclerAdapter<valueretriever, ProgramViewHolder> recyclerAdapter = new FirebaseRecyclerAdapter<valueretriever, ProgramViewHolder>(
valueretriever.class,
R.layout.individual_row,
ProgramViewHolder.class,
myref
) {
#Override
protected void populateViewHolder(ProgramViewHolder viewHolder, valueretriever model, int position) {
viewHolder.setMoisture(model.getMoisture());
viewHolder.setMotor_time(model.getMotortime());
viewHolder.setPower(model.getPower());
}
};
recyclerView.setAdapter(recyclerAdapter);
}
public static class ProgramViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView txtmoisture;
TextView txtmotor_time;
TextView txtpower;
String moisturee, motortimee, powerr;
public ProgramViewHolder(View itemView) {
super(itemView);
mView = itemView;
txtmoisture = itemView.findViewById(R.id.textview1);
txtmotor_time = itemView.findViewById(R.id.textview2);
txtpower = itemView.findViewById(R.id.textview3);
}
public void setMoisture(String moisture) {
txtmoisture.setText(moisture);
moisturee = txtmoisture.getText().toString();
}
public void setMotor_time(String motor_time) {
txtmotor_time.setText(motor_time);
motortimee = txtmotor_time.getText().toString();
}
public void setPower(String power) {
txtpower.setText(power);
powerr = txtpower.getText().toString();
}
}
}
2.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/mango"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
3.valueretriever.java
public class valueretriever {
private String moisture;
private String motor_time;
private String power;
public valueretriever() {
}
public valueretriever(String moisture, String motor_time, String power) {
this.moisture = moisture;
this.motor_time = motor_time;
this.power = power;
}
public String getMoisture() {
return moisture;
}
public void setMoisture(String moisture) {
this.moisture = moisture;
}
public String getMotortime() {
return motor_time;
}
public void setMotortime(String motor_time) {
this.motor_time = motor_time;
}
public String getPower() {
return power;
}
public void setPower(String power) {
this.power = power;
}
}
4.individual_row.xml
<?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="300dp"
android:background="#282828"
android:orientation="vertical">
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="#+id/textview2"
android:layout_centerHorizontal="true"
android:gravity="center_vertical"
android:textColor="#ffffff"
android:textSize="50sp" />
<TextView
android:id="#+id/textview2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:gravity="center_vertical"
android:textColor="#ffffff"
android:textSize="50sp" />
<TextView
android:id="#+id/textview3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:gravity="center_vertical"
android:textColor="#ffffff"
android:textSize="50sp" />
</RelativeLayout>

Categories

Resources