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.
Related
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>
I am making a chat section in my app, but the only problem I am facing is that whenever I enter a new message, some of the previous messages getting displayed in the recycler views get erased from the recycler view. But those messages are present in 'firestore'. They are not getting deleted from there but are getting vanished from the recycler view as soon as I enter a new message. When I restart the activity it works perfectly all messages are there.. but the problem only occurs when I enter a new message...and also when I scroll through the 'recyclerview'. Here are the codes...
This is the chatModel class :
import java.io.Serializable;
import java.util.Date;
public class chatModel implements Serializable {
private String Message,sender,Type,id;
private Date Time;
public chatModel()
{
}
public chatModel(String Message, String sender, String type,Date Time ,String id) {
this.Message = Message;
this.sender = sender;
Type = type;
this.Time = Time;
this.id = id;
}
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public Date getTime() {
return Time;
}
public void setTime(Date time) {
Time = time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
This is the DiscussionActivity class:
public class DiscussionActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseFirestore mFirestore;
private FirebaseStorage mStorage;
private DatabaseReference mDatabase;
private EditText msg;
private Button sendBtn;
private ImageView addDocs;
private Uri imageUri;
private String url;
private RecyclerView mChatContainer;
private List<chatModel> chatList;
private chatAdapter adapter;
private int position=0;
String getMessage,getTitle,getDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discussion);
mAuth = FirebaseAuth.getInstance();
mFirestore = FirebaseFirestore.getInstance();
mStorage = FirebaseStorage.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
msg = (EditText)findViewById(R.id.textContent);
sendBtn = (Button)findViewById(R.id.sendMsg);
addDocs = (ImageView)findViewById(R.id.include_documents);
getTitle = getIntent().getExtras().getString("Title");
int getCurrentYear = Calendar.getInstance().get(Calendar.YEAR);
int getCurrentMonth = Calendar.getInstance().get(Calendar.MONTH);
int getCurrentDate = Calendar.getInstance().get(Calendar.DATE);
getDate=getCurrentDate+getCurrentMonth+getCurrentYear+"";
mChatContainer = (RecyclerView)findViewById(R.id.chatContainer);
chatList = new ArrayList<>();
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = msg.getText().toString().trim();
int random = new Random().nextInt();
Map chat = new HashMap();
chat.put("Message",message);
chat.put("sender",mAuth.getCurrentUser().getUid());
chat.put("Time",FieldValue.serverTimestamp());
chat.put("Type","text");
chat.put("id",String.valueOf(random));
mFirestore.collection("Ideas").document(getTitle).collection("Discussions").add(chat).addOnCompleteListener(DiscussionActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful())
{
msg.setText("");
}
}
});
}
});
addDocs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
discussionOptionsSheetDialog obj = new discussionOptionsSheetDialog();
Bundle bundle = new Bundle();
bundle.putString("Title",getTitle);
bundle.putString("id",mAuth.getCurrentUser().getUid());
obj.setArguments(bundle);
obj.show(getSupportFragmentManager(),"discussionOptionsBottomSheet");
}
});
adapter = new chatAdapter(chatList,getTitle);
Query first = mFirestore.collection("Ideas").document(getTitle).collection("Discussions").orderBy("Time");
first.addSnapshotListener(DiscussionActivity.this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if(!documentSnapshots.isEmpty())
{
for(DocumentChange doc:documentSnapshots.getDocumentChanges())
{
if(doc.getType()==DocumentChange.Type.ADDED)
{
chatModel obj = doc.getDocument().toObject(chatModel.class);
chatList.add(obj);
DocumentSnapshot lastVisible = documentSnapshots.getDocuments()
.get(documentSnapshots.size() -1);
Query next = mFirestore.collection("Ideas").document(getTitle).collection("Discussions")
.orderBy("Time").startAfter(lastVisible);
adapter.notifyDataSetChanged();
}
if(doc.getType()==DocumentChange.Type.MODIFIED)
{
String docID = doc.getDocument().getId();
chatModel obj = doc.getDocument().toObject(chatModel.class);
if(doc.getOldIndex() == doc.getNewIndex())
{
chatList.set(doc.getOldIndex(),obj);
}
else
{
chatList.remove(doc.getOldIndex());
chatList.add(doc.getNewIndex(),obj);
adapter.notifyItemMoved(doc.getOldIndex(),doc.getNewIndex());
}
adapter.notifyDataSetChanged();
}
}
}
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(DiscussionActivity.this);
layoutManager.setReverseLayout(false);
layoutManager.setStackFromEnd(false);
mChatContainer.setHasFixedSize(false);
mChatContainer.setLayoutManager(layoutManager);
mChatContainer.setAdapter(adapter);
}
}
This is the activity_discussion.xml file :
<?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=".DiscussionActivity"
android:background="#6D7993">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_above="#id/writingSection"
android:id="#+id/chatContainer"
android:layout_marginRight="5dp">
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:id="#+id/writingSection"
android:layout_width="379dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/chat_background">
<EditText
android:id="#+id/textContent"
android:layout_width="342dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_toLeftOf="#id/include_documents"
android:hint="Write here.." />
<ImageView
android:layout_width="wrap_content"
android:layout_height="28dp"
android:src="#drawable/include_docs"
android:id="#+id/include_documents"
android:layout_toLeftOf="#id/sendMsg"
android:layout_marginTop="9dp"
android:layout_marginRight="3dp"/>
<Button
android:id="#+id/sendMsg"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_marginRight="2dp"
android:layout_marginTop="7dp"
android:background="#drawable/send_message" />
</RelativeLayout>
This is the chatAdapter class :
public class chatAdapter extends
RecyclerView.Adapter<chatAdapter.ViewHolder> {
private FirebaseAuth mAuth;
private FirebaseFirestore mFirestore;
private Context context;
private List<chatModel> chatMsgs;
private String title;
public chatAdapter(List<chatModel> chatMsgs,String title) {
this.chatMsgs = chatMsgs;
this.title = title;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
mAuth = FirebaseAuth.getInstance();
mFirestore = FirebaseFirestore.getInstance();
context = parent.getContext();
View view =
LayoutInflater.from(context).inflate(R.layout.chat_box_layout,null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final
int position) {
String getSenderId = chatMsgs.get(position).getSender();
final String getSenderMessage =
chatMsgs.get(position).getMessage();
final String getID = chatMsgs.get(position).getId();
final String theType = chatMsgs.get(position).getType();
if(theType.equals("text"))
{
if(getSenderId.equals(mAuth.getCurrentUser().getUid()))
{
holder.aBox.setVisibility(View.GONE);
holder.oIbox.setVisibility(View.GONE);
holder.mIbox.setVisibility(View.GONE);
//To get name...
mFirestore.collection("Users").document(getSenderId).get()
.addOnCompleteListener((Activity) context, new
OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull
Task<DocumentSnapshot> task) {
if(task.isSuccessful())
{
String getFirstName =
task.getResult().getString("Firstname");
String getLastName =
task.getResult().getString("Lastname");
holder.mName.setText(getFirstName.charAt(0)+getFirstName.substring(1).toLo . werCase());
}
}
});
holder.mContent.setText(getSenderMessage);
}
if(!getSenderId.equals(mAuth.getCurrentUser().getUid())) {
holder.mBox.setVisibility(View.GONE);
holder.aEdit.setVisibility(View.GONE);
holder.aDelete.setVisibility(View.GONE);
holder.oIbox.setVisibility(View.GONE);
holder.mIbox.setVisibility(View.GONE);
//To get name...
mFirestore.collection("Users").document(getSenderId).get()
.addOnCompleteListener((Activity) context, new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
String getFirstName = task.getResult().getString("Firstname");
String getLastName = task.getResult().getString("Lastname");
holder.aName.setText(getFirstName.charAt(0) + getFirstName.substring(1).toLowerCase());
}
}
});
holder.aContent.setText(getSenderMessage);
}
}
}
#Override
public int getItemCount() {
return chatMsgs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
//Variables for my chat lists...
private TextView mName,mContent;
private ImageView mDelete,mEdit;
private RelativeLayout mBox;
//Variable for other person's chat lists....
private TextView aName,aContent;
private ImageView aDelete,aEdit;
private RelativeLayout aBox;
//Variables for my images list..
private RelativeLayout mIbox;
private ImageView myImage,mIDelete;
private TextView myNameInImage;
//Variables for others image list..
private RelativeLayout oIbox;
private ImageView othersImage,oIDelete;
private TextView othersNameInImage;
public ViewHolder(View itemView) {
super(itemView);
//My variable initialization
mName = (TextView)itemView.findViewById(R.id.name);
mContent = (TextView)itemView.findViewById(R.id.chatContent);
mDelete = (ImageView)itemView.findViewById(R.id.delete);
mEdit = (ImageView)itemView.findViewById(R.id.editContent);
mBox = (RelativeLayout)itemView.findViewById(R.id.userChatBox);
//Other people's variables initialization..
aName = (TextView)itemView.findViewById(R.id.othersName);
aContent = (TextView)itemView.findViewById(R.id.othersChatContent);
aDelete = (ImageView)itemView.findViewById(R.id.othersDelete);
aEdit = (ImageView)itemView.findViewById(R.id.othersEditContent);
aBox = (RelativeLayout)itemView.findViewById(R.id.othersChatBox);
}
}
by this
but the only problem i am facing is that whenever i enter a new message...
I assume you mean getting messages when click sendBtn. Considering you code, fetching messages will happen only when OnCreate() raises (When app starts) >> So, it happens only once!
What you have to do is put first.addSnapshotListener() in a separate void and call in OnCreate() as well as sendBtn.setOnClickListener().
I hope I am being clear, and GOOD LUCK!
Apparently i changed my single chat box item layout, like i tried to make the current user chatbox(My message) and the other user chatbox in the same layout and tried to hide it accordingly...As soon as I changed it that is i made two separate layouts :
1. my_chatbox - To show my messages
2. other_chatbox.xml - For others to send a message..
and altered my adapter accordingly....
And it works now, even for the images. :)
here are codes : -
my_chatbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/userChatBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_alignParentTop="true">
<RelativeLayout
android:id="#+id/chatBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:background="#drawable/chat_background">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:text="Name"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000000"
android:textStyle="bold" />
<TextView
android:id="#+id/chatContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:text="Content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000000" />
</RelativeLayout>
<ImageView
android:id="#+id/delete"
android:layout_width="25dp"
android:layout_height="15dp"
android:layout_alignEnd="#+id/chatBox"
android:layout_below="#+id/chatBox"
android:layout_marginTop="-10dp"
android:src="#drawable/delete" />
<ImageView
android:id="#+id/editContent"
android:layout_width="25dp"
android:layout_height="15dp"
android:layout_below="#+id/chatBox"
android:layout_marginTop="-10dp"
android:layout_toStartOf="#+id/delete"
android:src="#drawable/edit"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
/>
</RelativeLayout>
</RelativeLayout>
the other_user_chatbox.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/userChatBox"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatBox"
android:layout_marginLeft="5dp"
android:layout_marginBottom="10dp"
android:background="#drawable/chat_background"
android:backgroundTint="#F4DDBB">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="Name"
android:textColor="#000000"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:id="#+id/chatContent"
android:text="Content"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
<ImageView
android:id="#+id/othersDelete"
android:layout_width="25dp"
android:layout_height="15dp"
android:layout_below="#id/chatBox"
android:src="#drawable/delete" />
<ImageView
android:layout_width="25dp"
android:layout_height="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:layout_below="#id/chatBox"
android:layout_toRightOf="#id/othersDelete"
android:src="#drawable/edit"
android:layout_marginRight="3dp"
android:id="#+id/othersEditContent"/>
</RelativeLayout>
</RelativeLayout>
Just try to keep the id's same in both the xml so as to make your viewHolder less complex.
And this is my chatAdapter.class :
public class chatAdapter extends RecyclerView.Adapter<chatAdapter.ViewHolder> {
private FirebaseAuth mAuth;
private FirebaseFirestore mFirestore;
private Context context;
private static final int SENT = 0;
private static final int RECEIVED = 1;
private String userID;
private List<chatModel> chatMsgs;
private String title;
public chatAdapter(List<chatModel> chatMsgs,String title,String userID) {
this.chatMsgs = chatMsgs;
this.title = title;
this.userID = userID;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
mAuth = FirebaseAuth.getInstance();
mFirestore = FirebaseFirestore.getInstance();
context = parent.getContext();
View view = null;
if(viewType == SENT)
{
view =
LayoutInflater.from(context).inflate(R.layout.chat_box_layout,parent,false);
}
if(viewType == RECEIVED)
{
view =
LayoutInflater.from(context).inflate(R.layout.other_user_chat_box,parent,false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
String getSenderId = chatMsgs.get(position).getSender();
final String getSenderMessage = chatMsgs.get(position).getMessage();
final String getID = chatMsgs.get(position).getId();
final String theType = chatMsgs.get(position).getType();
if(theType.equals("text"))
{
//To get name...
mFirestore.collection("Users").document(getSenderId).get()
.addOnCompleteListener((Activity) context, new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
String getFirstName = task.getResult().getString("Firstname");
String getLastName = task.getResult().getString("Lastname");
holder.mName.setText(getFirstName.charAt(0) + getFirstName.substring(1).toLowerCase());
}
}
});
holder.mContent.setText(getSenderMessage);
}
}
#Override
public int getItemCount() {
return chatMsgs.size();
}
#Override
public int getItemViewType(int position) {
if (chatMsgs.get(position).getSender() . equals(userID))
return SENT;
else
return RECEIVED;
}
public class ViewHolder extends RecyclerView.ViewHolder{
//Variables for my chat lists...
private TextView mName,mContent;
private ImageView mDelete,mEdit;
private RelativeLayout mBox;
public ViewHolder(View itemView) {
super(itemView);
//variable initialization
mName = (TextView)itemView.findViewById(R.id.name);
mContent = (TextView)itemView.findViewById(R.id.chatContent);
mDelete = (ImageView)itemView.findViewById(R.id.delete);
mEdit = (ImageView)itemView.findViewById(R.id.editContent);
mBox = (RelativeLayout)itemView.findViewById(R.id.userChatBox);
}
}
}
Hope it helps anyone else with the same problems and others too if they are interested.. :)
I am posting this question because I haven't found any proper solution related to my problem.
I am trying to retrieve my sensor data from Firebase but I am unable to do it. Please point out where am I doing wrong
Try.java
public class Try extends AppCompatActivity {
Button button;
ListView list;
DatabaseReference databaseTry;
List<TryObjectClass> tryObjectList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_try);
databaseTry =
FirebaseDatabase.getInstance().getReference("sensor_data");
button = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.list);
//list.setVisibility(View.INVISIBLE);
tryObjectList = new ArrayList<>();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseTry.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
tryObjectList.clear();
for (DataSnapshot TrySnapshot : dataSnapshot.getChildren()){
TryObjectClass tryObjectClass =
TrySnapshot.getValue(TryObjectClass.class);
tryObjectList.add(tryObjectClass);
}
TryAdapter adapter = new TryAdapter(Try.this, tryObjectList);
list.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
This is my object class
TryObjectClass.java
public class TryObjectClass {
private String date;
private String time;
private String humidity;
private String motion;
private String distance;
private String temperature;
public TryObjectClass(){
}
public TryObjectClass(String date, String time, String humidity, String
motion, String distance, String temperature) {
this.date = date;
this.time = time;
this.humidity = humidity;
this.motion = motion;
this.distance = distance;
this.temperature = temperature;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getMotion() {
return motion;
}
public void setMotion(String motion) {
this.motion = motion;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
}
This is my adapter class
TryAdapter.java
public class TryAdapter extends ArrayAdapter<TryObjectClass> {
private Activity context;
private List<TryObjectClass> objectList;
public TryAdapter(#NonNull Activity context, List<TryObjectClass>
objectList) {
super(context, R.layout.new_list,0);
this.context = context;
this.objectList = objectList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull
ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.new_list,null,true);
TextView date = (TextView) listViewItem.findViewById(R.id.date);
TextView distance = (TextView)
listViewItem.findViewById(R.id.distance);
TextView humidity = (TextView)
listViewItem.findViewById(R.id.humidity);
TextView motion = (TextView) listViewItem.findViewById(R.id.motion);
TextView temperature = (TextView)
listViewItem.findViewById(R.id.temperature);
TextView time = (TextView) listViewItem.findViewById(R.id.time);
TryObjectClass tryObjectClass = objectList.get(position);
date.setText(tryObjectClass.getDate());
distance.setText(tryObjectClass.getDistance());
humidity.setText(tryObjectClass.getHumidity());
motion.setText(tryObjectClass.getMotion());
temperature.setText(tryObjectClass.getTemperature());
time.setText(tryObjectClass.getTime());
return super.getView(position, convertView, parent);
}
}
try_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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=".Try"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Retrieved data"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:padding="10dp"
android:layout_marginLeft="90dp"
android:layout_marginTop="20dp"/>
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click here to retrieve the data"/>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
This is my list item
new_list.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Humidity -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Motion -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/motion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Temperature -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Time -"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#000"
android:padding="10dp"
android:layout_marginLeft="20dp"/>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
This is my database
smartborder-cef61
sensor_data
100
date: 1875
distance: "50M"
humidity: 4573
motion: "yes"
temperature: "30c"
time: 7377200
200
date: 23111996
distance: "50M"
humidity: 45
motion: "yes"
temperature: "30C"
time: 73775
I found something, try to put your setAdapter() outside your listener.
Inside your listener you will put this code:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot TrySnapshot : dataSnapshot.getChildren()){
TryObjectClass tryObjectClass = TrySnapshot.getValue(TryObjectClass.class);
tryObjectList.add(tryObjectClass);
}
adapter.notifyDataSetChanged();
}
And try to put your declared things in onCreate method, like your ValueEventListener, so you can add it in onStart and remove it in onDestroy when your activity have not to listen your changes anymore when your activity is destroyed. Here's part of my fragment ContatsFragment, it is working fine:
public class ContatsFragment extends Fragment {
private ListView listView;
private ArrayAdapter adapter;
private ArrayList<Contat> contats;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListenerContatos;
private Context context;
public ContatsFragment() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
context = getActivity();
databaseReference.addValueEventListener(valueEventListenerContatos);
}
#Override
public void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListenerContatos);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contats = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_contats, container, false);
listView = (ListView) view.findViewById(R.id.lv_contatos);
adapter = new ContatAdapter(getActivity(), contats);
listView.setAdapter(adapter);
Preferences preferences = new Preferences(getActivity());
String loggedUserId = preferences.getLoggedUserId();
databaseReference = FirebaseConfig.getFirebaseReference();
databaseReference = databaseReference.child("contats")
.child(loggedUserId);
valueEventListenerContatos = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
contats.clear();
for (DataSnapshot dados : dataSnapshot.getChildren()) {
Contat contat = dados.getValue(Contat.class);
contats.add(contat);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
return view;
}
}
I have got the solution...I made mistake in the giving the list object name...
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
I am having a list of items populating through recyclerview with android databinding technique and now I want to pass and populate the same data in detail Activity not getting the right thing to do such. So, kindly help to do this.
public class Fragment extends Fragment {
private FirebaseRecyclerAdapter adapter;
private Firebase mFirebaseRef = new Firebase("https://xyz.firebaseio.com/category/").child("list");
public Fragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.recycler_view, container, false);
final RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new FirebaseRecyclerAdapter<List, ViewHolder>List.class, R.layout.fragment,
ViewHolder.class, mFirebaseRef) {
#Override
protected void populateViewHolder(ViewHolder viewHolder, List list, int i) {
FragmentBinding binding = viewHolder.getBinding();
binding.setList(list);
}
};
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
return rootView;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public FragmentBinding binding;
public ViewHolder(View itemView) {
super(itemView);
binding = DataBindingUtil.bind(itemView);
itemView.setOnClickListener(this);
}
public FragmentBinding getBinding() {
return binding;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
**// need help here**
v.getContext().startActivity(intent);
}
}
#BindingAdapter("quantity")
public static void setQuantityText(TextView view, int quantity) {
view.setText(String.valueOf(quantity));
}
public static class Handlers {
public static void increment(View view, int max) {
FragmentBinding binding = DataBindingUtil.findBinding(view);
binding.setQuantity(Math.max(max, binding.getQuantity() + 1));
}
public static void decrement(View view, int min) {
FragmentBinding binding = DataBindingUtil.findBinding(view);
binding.setQuantity(Math.min(min, binding.getQuantity() - 1));
}
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="List"
type="com.xyz.www.android.model.List"/>
<variable
name="quantity"
type="int"/>
<variable
name="Handlers"
type="com.xyz.www.android.ui.fragments.Fragment.Handlers"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="#dimen/activity_horizontal_margin"
android:paddingEnd="#dimen/activity_horizontal_margin"
android:paddingTop="8dp">
<ImageView
android:layout_width="76dp"
android:layout_height="76dp"
android:contentDescription="#string/content_description"
app:imageUrl="#{List.productImageUrl}"
android:padding="8dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginTop="8dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="72dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productTitle}"
android:textSize="16sp"
android:textColor="#android:color/primary_text_light"
app:font="#{`Roboto-Regular.ttf`}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productSku}"
android:textSize="13sp"
android:paddingTop="8dp"
app:font="#{`Roboto-Regular.ttf`}"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Rs"
android:textSize="14sp"
android:paddingTop="8dp"
android:paddingEnd="2dp"
android:paddingStart="2dp"
app:font="#{`Roboto-Regular.ttf`}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{List.productSellingPrice}"
android:textSize="14sp"
android:paddingTop="8dp"
android:paddingStart="2dp"
android:paddingEnd="2dp"
android:textColor="#android:color/primary_text_light"
app:font="#{`Roboto-Regular.ttf`}"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentEnd="true"
android:paddingTop="16dp"
android:paddingBottom="16dp">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/decrease" />
<TextView
android:layout_width="32dp"
android:layout_height="wrap_content"
app:font="#{`Roboto-Regular.ttf`}"
app:quantity="#{quantity}"
android:textAlignment="center" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/increase" />
</LinearLayout>
</RelativeLayout>
#JsonIgnoreProperties(ignoreUnknown=true)
public class List extends BaseObservable {
String productTitle;
String productSku;
String productImageUrl;
String productDescription;
String productMrp;
String productSellingPrice;
public List() {
}
public List(String productTitle, String productSku,
String productImageUrl, String productDescription,
String productMrp, String productSellingPrice) {
this.productTitle = productTitle;
this.productSku = productSku;
this.productImageUrl = productImageUrl;
this.productDescription = productDescription;
this.productMrp = productMrp;
this.productSellingPrice = productSellingPrice;
}
#Bindable
public String getProductTitle() {
return productTitle;
}
#Bindable
public String getProductSku() {
return productSku;
}
#Bindable
public String getProductImageUrl() {
return productImageUrl;
}
#Bindable
public String getProductDescription() {
return productDescription;
}
#Bindable
public String getProductMrp() {
return productMrp;
}
#Bindable
public String getProductSellingPrice() {
return productSellingPrice;
}
There are a few ways to do this. One is to make List Parcelable so that you can pass it as an Intent extra. You'll then be able to extract it and populate the Detail page.
public static final LIST = "ListContent";
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
FragmentBinding binding = DataBindingUtil.findBinding(v);
intent.putExtra(LIST, binding.getList());
v.getContext().startActivity(intent);
}
Another is to pass only the ID for the List and read the information again in the detail binding. Add the ID to the List and then you'll be able to extract it when you start the activity:
public static final LIST_ID = "ListID";
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailedActivity.class);
FragmentBinding binding = DataBindingUtil.findBinding(v);
intent.putExtra(LIST_ID, binding.getList().getId());
v.getContext().startActivity(intent);
}
Either way, you can pull the data from the intent in the onCreate of your details Activity:
public void onCreate(...) {
Intent intent = getIntent();
// Using ID:
int id = intent.getIntExtra(LIST_ID);
List list = loadListFromId(id);
// Using Parcelable:
List list = intent.getParcelableExtra(LIST);
//...
}