I am trying to create a time line to represent all the added announcement in CardView ,
I follow every single things in this tutorial
https://www.youtube.com/watch?v=WmPGLoB28T8
but an exception throw when I was trying to retrieve the data from firebase cant now why and how to handle it :
MyHolder :
package com.volunteer.android.HolderClasses;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.volunteer.android.R;
public class AnnouncementHolder extends RecyclerView.ViewHolder {
public TextView orgtname ;
public TextView Evenname;
public CardView HomeCard ;
public TextView Start;
public TextView City;
public TextView Field;
public TextView moreinfo;
public TextView contactInfo;
public ImageView pic ;
public ImageView report ;
FirebaseAuth mAuth ;
DatabaseReference reportRef ;
public AnnouncementHolder(View view){
super(view);
mAuth=FirebaseAuth.getInstance();
reportRef= FirebaseDatabase.getInstance().getReference().child("Reports");
reportRef.keepSynced(true);
HomeCard=(CardView)view.findViewById(R.id.CardviewHome);
orgtname = (TextView) view.findViewById(R.id.textViewOragName);
Evenname = (TextView) view.findViewById(R.id.textViewEventName);
Start = (TextView) view.findViewById(R.id.TextViewDate);
City = (TextView) view.findViewById(R.id.TextViewCity);
Field = (TextView) view.findViewById(R.id.TextViewField);
moreinfo = (TextView) view.findViewById(R.id.TextViewPost);
contactInfo = (TextView) view.findViewById(R.id.contact);
pic =(ImageView)view.findViewById(R.id.ImagproSe);
report=(ImageView)view.findViewById(R.id.report_btn);
}
public void setPost_key(final String postKey){
reportRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
if(dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())){
report.setImageResource(R.drawable.ic_link);
}
else {
report.setImageResource(R.mipmap.ic_report_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
MyAdapter:
[package com.volunteer.android.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.volunteer.android.HolderClasses.AnnouncementHolder;
import com.volunteer.android.R;
import com.volunteer.android.data.Announcement;
import com.volunteer.android.data.Constants;
import java.util.ArrayList;
/**
* Created by macbookpro on 8/20/16 AD.
*/
public class AnnouncementAdapter extends RecyclerView.Adapter<AnnouncementHolder> {
Context c;
ArrayList<Announcement> Announcements = new ArrayList<>();
String Uid;
Firebase announcRef ;
Firebase reportRef ;
FirebaseAuth mAuth ;
// final String AnnKey ;
private boolean mProccesLike=false ;
public AnnouncementAdapter(Context c, ArrayList<Announcement> Announcements , String Uid){
this.c=c;
this.Announcements=Announcements;
this.Uid=Uid;
// expRef=new Firebase(Constants.USER_ECPERIENCE_PATH);
mAuth=FirebaseAuth.getInstance();
reportRef=new Firebase(Constants.FIREBASE_URL+"/Reports");
}
#Override
public void onBindViewHolder(AnnouncementHolder holder, int position) {
final Announcement announcement = Announcements.get(position);
holder.orgtname.setText((Announcements.get(position)).getOrgName());
holder.Evenname.setText((Announcements.get(position)).getEventName());
holder.contactInfo.setText((Announcements.get(position)).getContact());
holder.Field.setText((Announcements.get(position)).getField());
holder.Start.setText((Announcements.get(position)).getStartDate());
holder.moreinfo.setText((Announcements.get(position)).getMoreInfo());
holder.City.setText((Announcements.get(position)).getCity());
// holder.setPost_key(announcement.getAnnId());
holder.report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProccesLike=true ;
reportRef.addValueEventListener(new com.firebase.client.ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
if (mProccesLike){
if (dataSnapshot.child(announcement.getAnnId()).hasChild(mAuth.getCurrentUser().getUid())){
reportRef.child(announcement.getAnnId()).child(mAuth.getCurrentUser().getUid()).removeValue();
mProccesLike=false ;
}else {
reportRef.child(announcement.getAnnId()).child(mAuth.getCurrentUser().getUid()).setValue("True");
mProccesLike=false ;
}
}}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
});
}
public void animate(RecyclerView.ViewHolder viewHolder) {
final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(c, R.anim.anticipateovershoot_interpolator);
viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}
#Override
public AnnouncementHolder onCreateViewHolder (ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_home, parent, false);
AnnouncementHolder holder =new AnnouncementHolder(v);
return holder;
}
#Override
public int getItemCount() {
return Announcements.size(); //mAssignments.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
// Insert a new item to the RecyclerView on a predefined position
public void insert(Announcement announcement, int position) {
Announcements.add(position, announcement);
notifyItemInserted(position);
}
// Remove a RecyclerView item containing a specified Data object
public void remove(Announcement announcement) {
int position = Announcements.indexOf(announcement);
Announcements.remove(position);
notifyItemRemoved(position);
}
}][1]
Saving method :
public void saveAnnouncement (View view){
org=editTextOrg.getText().toString().trim();
if (org.length()>300){
return;
}
Event=editTextEvent.getText().toString().trim();
if (Event.length()>300){
return;
}
sDate=editTextSd.getText().toString().trim();
if (sDate.length()>300){
return;}
info=editTextInfo.getText().toString().trim();
if (info.length()>300){
return;
}
contact=editTextContat.getText().toString().trim();
if (contact.length()>300){
return;
}
if (cityName==null){
return;
}
if (Feild==null){
return;
}
sDate=editTextSd.getText().toString().trim();
Announcement announcement = new Announcement(Uid,"" ,org, Event, sDate, cityName,Feild , info , contact );
//Map<String, Object> map = new HashMap<>();
// map.put("announcement",announcement);
mRef.child("Announcement").push().setValue(announcement);
The Retriving class :
package com.volunteer.android.Fragment;
/**
* Created by macbookpro on 8/23/16 AD.
*/
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.volunteer.android.R;
import com.volunteer.android.adapter.AnnouncementAdapter;
import com.volunteer.android.data.Announcement;
import com.volunteer.android.data.Constants;
import java.util.ArrayList;
/**
* Created by jnoo1 on 8/11/2016.
*/
public class Home extends Fragment {
RecyclerView rv ;
ArrayList<Announcement> announcements = new ArrayList<>();
AnnouncementAdapter adapter ;
Firebase myRef ;
FloatingActionButton AddAnouncement ;
FirebaseAuth mAuth ;
String Uid ;
public Home(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view =inflater.inflate(R.layout.fragment_etailse,container,false);
Firebase.setAndroidContext(getActivity());
myRef = new Firebase(Constants.FIREBASE_URL);
rv =(RecyclerView)view.findViewById(R.id.recyclerViewHome);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
AddAnouncement=(FloatingActionButton) view.findViewById(R.id.fab1);
mAuth=FirebaseAuth.getInstance();
Uid=mAuth.getCurrentUser().getUid();
adapter=new AnnouncementAdapter(getActivity(),announcements,Uid);
rv.setAdapter(adapter);
RefreshData();
return view ;
}
public void RefreshData (){
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
getUpdates(dataSnapshot);}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(FirebaseError firebaseError) {}
}); }
private void getUpdates (DataSnapshot dataSnapshot ){
announcements.clear();
for (DataSnapshot Ds : dataSnapshot.getChildren())
{
Announcement announcement=new Announcement();
announcement.setOrgName( Ds.getValue(Announcement.class).getOrgName());
announcement.setEventName(Ds.getValue(Announcement.class).getEventName());
announcement.setCity(Ds.getValue(Announcement.class).getCity());
announcement.setField(Ds.getValue(Announcement.class).getField());
announcement.setStartDate(Ds.getValue(Announcement.class).getStartDate());
announcement.setMoreInfo(Ds.getValue(Announcement.class).getMoreInfo());
announcement.setContact(Ds.getValue(Announcement.class).getContact());
// announcement.setAnnId((String) Ds.getKey());
//exp.setCity((String) dataSnapshot.child("city").getValue());
announcements.add(announcement);
}
if (announcements.size()>0){
adapter=new AnnouncementAdapter(getActivity(),announcements,Uid);
rv.setAdapter(adapter); }
else {
Toast.makeText(getActivity() ," No thing to show ", Toast.LENGTH_SHORT).show(); } }
}
The error crash my app evrytime :
09-15 17:11:35.622 5862-5884/com.volunteer.android I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:3 and remote module com.google.android.gms.tagmanager:3
09-15 17:11:35.622 5862-5884/com.volunteer.android I/DynamiteModule: Selected local version of com.google.android.gms.tagmanager
09-15 17:11:35.648 5862-5884/com.volunteer.android W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded)
09-15 17:11:35.648 5862-5884/com.volunteer.android I/GoogleTagManager: Tag Manager initilization took 23ms
09-15 17:11:35.819 5862-5862/com.volunteer.android D/FirebaseCrashApiImpl: throwable com.firebase.client.FirebaseException: Failed to bounce to type
09-15 17:11:35.849 5862-5862/com.volunteer.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.volunteer.android, PID: 5862
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at com.volunteer.android.Fragment.Home.getUpdates(Home.java:107)
at com.volunteer.android.Fragment.Home.access$000(Home.java:32)
at com.volunteer.android.Fragment.Home$1.onChildAdded(Home.java:85)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "UserInformation" (class com.volunteer.android.data.Announcement), not marked as ignorable (11 known properties: , "contact", "moreInfo", "eventName", "city", "orgName", "startDate", "uid", "field", "annId", "picture", "key"])
at [Source: java.io.StringReader#1a04a2ef; line: 1, column: 21] (through reference chain: com.volunteer.android.data.Announcement["UserInformation"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at com.volunteer.android.Fragment.Home.getUpdates(Home.java:107)
at com.volunteer.android.Fragment.Home.access$000(Home.java:32)
at com.volunteer.android.Fragment.Home$1.onChildAdded(Home.java:85)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-15 17:11:36.234 5993-5993/com.volunteer.android:background_crash W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
package com.volunteer.android.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.firebase.database.Exclude;
/**
* Created by macbookpro on 8/10/16 AD.
*/
public class Announcement {
#JsonIgnore
private String Key ;
private String OrgName;
private String EventName;
private String StartDate;
private String City;
private String Field;
private String MoreInfo;
private String Contact;
private String Picture;
private String Uid;
private String AnnId ;
public Announcement (){
// defualt ;
}
public Announcement (String Uid, String AnnId ,String OrgName,String EventName,String StartDate,String City,String Field, String MoreInfo, String Contact){
this.Uid=Uid;
this.AnnId=AnnId;
this.OrgName=OrgName;
this.EventName=EventName;
this.StartDate=StartDate;
this.City=City;
this.Field=Field;
this.MoreInfo=MoreInfo;
this.Contact=Contact;
}
public void setAnnId (String AnnId){this.AnnId=AnnId;}
public String getAnnId (){return AnnId;}
public void setKey(String Key){
Key=Key;
}
#Exclude
public String getKey(){
return Key;
}
public void setUid (String Uid){this.Uid=Uid;}
public String getUid (){return Uid ; }
public void setOrgName(String orgName){
OrgName=orgName;
}
public String getOrgName(){
return OrgName;
}
public void setEventName(String EName){
EventName=EName;
}
public String getEventName(){
return EventName;
}
public void setStartDate(String Date){
StartDate= Date;
}
public String getStartDate(){
return StartDate;
}
public void setCity(String c){
City=c;
}
public String getCity(){
return City;
}
public void setField(String f){
Field=f;
}
public String getField(){
return Field;
}
public void setMoreInfo(String m){
MoreInfo=m;
}
public String getMoreInfo(){
return MoreInfo;
}
public void setContact(String Contact){
this.Contact=Contact;
}
public String getContact(){
return Contact;
}
public void setPicture(String p){
Picture=p;
}
public String getPicture(){
return Picture;
}
}
Related
Everything works well until I retrieve data from my database, I want to know what seems to be the problem and the ways how to fix this. I really need help for this. It seems like the error occurs in the line 43 of the History.java. Thank you so much for your response.
Here is the error code from Logcat
FATAL EXCEPTION: main
Process: com.example.heartapp, PID: 31504
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.heartapp.Member2
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.example.heartapp.History$1.onDataChange(History.java:43)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2022-11-15 20:38:26.810 31504-31504 Process com.example.heartapp I Sending signal. PID: 31504 SIG: 9
2022-11-15 20:38:26.854 1476-1670 InputDispatcher pid-1476 E channel 'd52c022 com.example.heartapp/com.example.heartapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
---------------------------- PROCESS ENDED (31504) for package com.example.heartapp ----------------------------
2022-11-15 20:38:26.859 1476-1670 InputDispatcher pid-1476 E channel '5fc9a49 com.example.heartapp/com.example.heartapp.History (server)' ~ Channel is unrecoverably broken and will be disposed!
2022-11-15 20:38:26.881 1476-2965 WindowManager pid-1476 E win=Window{d52c022 u0 com.example.heartapp/com.example.heartapp.MainActivity EXITING} destroySurfaces: appStopped=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true
2022-11-15 20:38:26.908 2286-15179 DollieAdapterService pid-2286 E notifyActivityState pkg:com.example.heartapp/com.example.heartapp.History state:20 fg:false mUid:10127
Here is my History.java
package com.example.heartapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class History extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference databaseReference;
MyAdapter adapter;
ArrayList<Member2> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
String email=getIntent().getStringExtra("keyemail");
recyclerView=findViewById(R.id.History);
databaseReference=FirebaseDatabase.getInstance().getReference(email);
list=new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter=new MyAdapter(this,list);
recyclerView.setAdapter(adapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Member2 user = dataSnapshot.getValue(Member2.class);
list.add(user);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Here is my Memeber2.java
package com.example.heartapp;
public class Member2 {
String age;
String sex;
String stp1;
String stp2a;
String stp2b;
String stp2c;
String stp2d;
String stp2e;
String stp2f;
String stp2g;
String stp2h;
String stp2i;
String stp3;
String stp4a;
String stp4b;
String stp4c;
String stp4d;
String stp4e;
String stp4f;
String stp4g;
String stp4h;
String stp5;
String result;
String tips;
public Member2() {
}
public String getage() {
return age;
}
public String getsex() {
return sex;
}
public String getstp1() {
return stp1;
}
public String getstp2a() {
return stp2a;
}
public String getstp2b() {
return stp2b;
}
public String getstp2c() {
return stp2c;
}
public String getstp2d() {
return stp2d;
}
public String getstp2e() {
return stp2e;
}
public String getstp2f() {
return stp2f;
}
public String getstp2g() {
return stp2g;
}
public String getstp2h() {
return stp2h;
}
public String getstp2i() {
return stp2i;
}
public String getstp3() {
return stp3;
}
public String getstp4a() {
return stp4a;
}
public String getstp4b() {
return stp4b;
}
public String getstp4c() {
return stp4c;
}
public String getstp4d() {
return stp4d;
}
public String getstp4e() {
return stp4e;
}
public String getstp4f() {
return stp4f;
}
public String getstp4g() {
return stp4g;
}
public String getstp4h() {
return stp4h;
}
public String getstp5() {
return stp5;
}
public String getresult() {
return result;
}
public String gettips() {
return tips;
}
}
Here is the code for MyAdapter.java
package com.example.heartapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Member2> list;
public MyAdapter(Context context, ArrayList<Member2> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.items,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Member2 user = list.get(position);
holder.age.setText(user.getage());
holder.result.setText(user.getresult());
holder.sex.setText(user.getsex());
holder.stp1.setText(user.getstp1());
holder.stp2a.setText(user.getstp2a());
holder.stp2b.setText(user.getstp2b());
holder.stp2c.setText(user.getstp2c());
holder.stp2d.setText(user.getstp2d());
holder.stp2e.setText(user.getstp2e());
holder.stp2f.setText(user.getstp2f());
holder.stp2g.setText(user.getstp2g());
holder.stp2h.setText(user.getstp2h());
holder.stp2i.setText(user.getstp2i());
holder.stp3.setText(user.getstp3());
holder.stp4a.setText(user.getstp4a());
holder.stp4b.setText(user.getstp4b());
holder.stp4c.setText(user.getstp4c());
holder.stp4d.setText(user.getstp4d());
holder.stp4e.setText(user.getstp4e());
holder.stp4f.setText(user.getstp4f());
holder.stp4g.setText(user.getstp4g());
holder.stp4h.setText(user.getstp4h());
holder.stp5.setText(user.getstp5());
holder.tips.setText(user.gettips());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView age, result, sex, stp1, stp2a, stp2b, stp2c, stp2d, stp2e, stp2f, stp2g, stp2h, stp2i, stp3, stp4a, stp4b, stp4c, stp4d, stp4e, stp4f, stp4g, stp4h, stp5, tips;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
age=itemView.findViewById(R.id.tvAge);
result=itemView.findViewById(R.id.tvResult);
sex=itemView.findViewById(R.id.tvSex);
stp1=itemView.findViewById(R.id.tvstp1);
stp2a=itemView.findViewById(R.id.tvstp2a);
stp2b=itemView.findViewById(R.id.tvstp2b);
stp2c=itemView.findViewById(R.id.tvstp2c);
stp2d=itemView.findViewById(R.id.tvstp2d);
stp2e=itemView.findViewById(R.id.tvstp2e);
stp2f=itemView.findViewById(R.id.tvstp2f);
stp2g=itemView.findViewById(R.id.tvstp2g);
stp2h=itemView.findViewById(R.id.tvstp2h);
stp2i=itemView.findViewById(R.id.tvstp2i);
stp3=itemView.findViewById(R.id.tvstp3);
stp4a=itemView.findViewById(R.id.tvstp4a);
stp4b=itemView.findViewById(R.id.tvstp4b);
stp4c=itemView.findViewById(R.id.tvstp4c);
stp4d=itemView.findViewById(R.id.tvstp4d);
stp4e=itemView.findViewById(R.id.tvstp4e);
stp4f=itemView.findViewById(R.id.tvstp4f);
stp4g=itemView.findViewById(R.id.tvstp4g);
stp4h=itemView.findViewById(R.id.tvstp4h);
stp5=itemView.findViewById(R.id.tvstp5);
tips=itemView.findViewById(R.id.tvTips);
}
}
}
Here also the structure in my database
It looks like one or more of the child nodes of the path you read are not full Member2 object, but rather is just a string value. The easiest way to troubleshoot this is to print the key of the snapshot just before you try to get the object from it:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Log.i("Firebase", // 👈 Log the key and value
"Reading Member2 from "+dataSnapshot.getKey() // 👈 to know where the
+", value="+dataSnapshot.getValue() // 👈 problem is in your
); // 👈 data
Member2 user = dataSnapshot.getValue(Member2.class);
list.add(user);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // 👈 never ignore errors
}
});
I have a object class that I want to use it between activities.
I used exactly the same method for another activities and worked perfectly fine. But here I can't figure it out what I am doing wrong. This is the object class :
`package com.mecachrome.ffbf;
import android.os.Parcel;
import android.os.Parcelable;
public class topic implements Parcelable {
public static Creator<topic> getCREATOR() {
return CREATOR;
}
public static final Creator<topic> CREATOR = new Creator<topic>() {
#Override
public topic createFromParcel(Parcel in) {
return new topic(in);
}
#Override
public topic [] newArray(int size) {
return new topic[size];
}
};
private String name;
private String comment;
private String id;
private String username;
public topic() {
}
public topic(String name, String comment, String id, String username) {
this.name = name;
this.comment = comment;
this.id = id;
this.username = username;
}
protected topic(Parcel in) {
name = in.readString();
comment = in.readString();
id = in.readString();
username = in.readString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return "topic{" +
"name='" + name + '\'' +
", comment='" + comment + '\'' +
", id='" + id + '\'' +
", username='" + username + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(comment);
dest.writeString(id);
dest.writeString(username);
}
}`
This is the class that I want to take the object from:
`package com.mecachrome.ffbf;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class forum extends AppCompatActivity {
RecyclerView rv_forum;
forumAdapter myadapter;
Button add_topic;
Button test;
DatabaseReference databaseref;
private ArrayList<topic> topicList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum);
add_topic = findViewById(R.id.btn_new_topic);
rv_forum = findViewById(R.id.rv_topics);
rv_forum.setHasFixedSize(true);
rv_forum.setLayoutManager(new LinearLayoutManager(this));
test = findViewById(R.id.test_btn);
topicList = new ArrayList<>();
databaseref = FirebaseDatabase.getInstance().getReference("forum_topics");
databaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dss: snapshot.getChildren()){
topic top = dss.getValue(topic.class);
topicList.add(top);
}
myadapter = new forumAdapter(forum.this, topicList, mTopic -> {
Intent intent = new Intent(forum.this, topic_chat.class);
intent.putExtra("topic",mTopic);
startActivity(intent);
});
rv_forum.setAdapter(myadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(forum.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
add_topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(forum.this, add_new_topic.class);
startActivity(i);
}
});
}
}`
And this is the class that I want to transfer the object to:
`package com.mecachrome.ffbf;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class topic_chat extends AppCompatActivity {
RecyclerView rv_chat;
chatAdapter myadapter;
Button send;
TextView topic_name;
TextView chat_text;
String chat;
private topic mTopic;
private ArrayList<chat> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic_chat);
mTopic = getIntent().getParcelableExtra("topic");
send = findViewById(R.id.btn_send_chat);
rv_chat = findViewById(R.id.rv_topics);
rv_chat.setHasFixedSize(true);
rv_chat.setLayoutManager(new LinearLayoutManager(this));
topic_name = findViewById(R.id.tv_topic_name);
chat_text = findViewById(R.id.et_comment);
chat = chat_text.getText().toString().trim();
chatList = new ArrayList<>();
DatabaseReference databaseref = FirebaseDatabase.getInstance().getReference("forum_topics").child(mTopic.getId()).child("chat");
topic_name.setText(mTopic.getName());
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.SHORT).format(calendar.getTime());
chatList = new ArrayList<>();
databaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dss: snapshot.getChildren()){
chat mess = dss.getValue(chat.class);
chatList.add(mess);
}
myadapter = new chatAdapter(topic_chat.this, chatList, chat -> {
Intent intent = new Intent(topic_chat.this, topic_chat.class);
startActivity(intent);
});
rv_chat.setAdapter(myadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(topic_chat.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chat msg = new chat(mTopic.getName(),chat,mTopic.getId(),currentDate);
databaseref.setValue(msg).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
Toast.makeText(topic_chat.this, "Review was been added Successfully", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(topic_chat.this, "Review failed to post. Try Again!", Toast.LENGTH_SHORT).show();
}
});;
}
});
}
}`
The object class is "topic"
The error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mecachrome.ffbf.topic.getId()' on a null object reference
On this line
DatabaseReference databaseref = FirebaseDatabase.getInstance().getReference("forum_topics").child(mTopic.getId()).child("chat");
because mTopic.getId() is null. Any help?
This question already has answers here:
Firebase Android ListView not being displayed
(1 answer)
FireBase Realtime Database : Recycler View not populating
(1 answer)
W/Firestore: [CustomClassMapper]: No setter/field for class Android
(2 answers)
"No setter/field for field found on class"
(2 answers)
Closed 1 year ago.
I am trying to fetch a students data from Firestore Collection and then display it in Recycler view
My Firestore Collection and Document :
Collection Name is School Code, Document contains Student Info
Model Class :(Student_Model_Class)
package com.example.firestooredemo;
import java.sql.Timestamp;
import java.util.HashMap;
public class sdm {
private HashMap<String, String> QnA;
private String formname;
private String schoolid;
private String standard;
private String studentname;
private String subject;
private Timestamp timestamp;
private sdm(){}
private sdm(HashMap qna,String formname,String schoolid,String standard,String studentname,String subject,Timestamp timestamp){
this.QnA=qna;
this.formname=formname;
this.schoolid=schoolid;
this.standard=standard;
this.studentname=studentname;
this.subject=subject;
this.timestamp=timestamp;
}
public HashMap<String, String> getQnA() {
return QnA;
}
public void setQnA(HashMap<String, String> qnA) {
QnA = qnA;
}
public String getFormname() {
return formname;
}
public void setFormname(String formname) {
this.formname = formname;
}
public String getSchoolid() {
return schoolid;
}
public void setSchoolid(String schoolid) {
this.schoolid = schoolid;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getTimestamp() {
return timestamp.toString();
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
}
Activity.java :
package com.example.firestooredemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
public class DisplayRecord extends AppCompatActivity {
TextView Record_Title,DemoD;
private FirebaseFirestore Fs;
private RecyclerView FSList;
private FirestoreRecyclerAdapter<sdm,Student_View_Holder> F_Adapter;
String S_ID,Student;
List<sdm> stud;
int S_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_record);
FSList=(RecyclerView) findViewById(R.id.RCView);
FSList.setHasFixedSize(true);
FSList.setLayoutManager(new LinearLayoutManager(this));
Intent intent = getIntent();
Fs=FirebaseFirestore.getInstance();
Record_Title= (TextView) findViewById(R.id.RecordTitle);
S_ID = intent.getStringExtra("School ID");
Record_Title.setText("Records of "+S_ID);
Log.d("Datacheck","School :"+S_ID);
S_id=Integer.parseInt(S_ID);
String TAG="Datacheck";
Fs.collection("EM_DEMO2").document("10th_STD").collection(S_ID)
.whereEqualTo("formname","Tourism, Transport and Communication3")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData().toString());
Student=Student+document.getLong("standard")+"\n"+document.get("subject")+"\n"+document.get("formname")+"\n-----\n";
// stud.add(document.toObject(s1));
Log.d("IMOP",Student);
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
//Query Part
Query Q=Fs.collection("EM_DEMO2").document("10th_STD").collection(S_ID).whereEqualTo("formname","Tourism, Transport and Communication3");
// Recycler view Display
FirestoreRecyclerOptions<sdm> Opt=new FirestoreRecyclerOptions.Builder<sdm>()
.setQuery(Q,sdm.class)
.build();
F_Adapter = new FirestoreRecyclerAdapter<sdm, Student_View_Holder>(Opt) {
#NonNull
#Override
public Student_View_Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View V= LayoutInflater.from(parent.getContext()).inflate(R.layout.student_data,parent,false);
return new Student_View_Holder(V);
}
#Override
protected void onBindViewHolder(#NonNull Student_View_Holder holder, int position, #NonNull sdm model) {
holder.StudentName.setText(model.getStudentname());
holder.Standard.setText(model.getStandard());
holder.SchoolID.setText(model.getSchoolid()+"");
holder.Subject.setText(model.getSubject());
holder.FormName.setText(model.getFormname());
// holder.Time.setText(model.getTs()+"");
}
};
FSList.setAdapter(F_Adapter);
//View Holder
}
private class Student_View_Holder extends RecyclerView.ViewHolder {
private TextView StudentName,Standard,Subject,SchoolID,FormName,Time;
public Student_View_Holder(#NonNull View itemView) {
super(itemView);
StudentName = itemView.findViewById(R.id.StudentName);
Standard = itemView.findViewById(R.id.Std);
Subject = itemView.findViewById(R.id.Sub);
SchoolID = itemView.findViewById(R.id.SchoolID);
FormName = itemView.findViewById(R.id.FormName);
Time = itemView.findViewById(R.id.Timestamp);
}
}
#Override
protected void onStart() {
super.onStart();
F_Adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if(F_Adapter!= null){
F_Adapter.stopListening();
}
}
}
Student_data design :
XML Design Screenshot
But In app Recycler view only display fetched values of Subject,
App Output
I put some log messages in Student Data Model Class,to check if data is being fetched or not. But those logs doesn't even show up
Log Messages :
Logs with Tag : Datacheck
Log with Tag : IMOP
Kindly please help with this,
thanks in advance.
Facing an error.
I am making a chat application with firebase. where i am sending and printing the data from Firebase Realtime Database. the issue is that whenever i am adding or sending a data into the Firebase Realtime Database, its not only printing the currently added data but also printing the whole data from node Chats again and again wherever any data added into the Firebase Realtime Database.
how can i fix this?
Whats my think to solve the error?
I think removing of event listener which are being attached on call of
getMessage(); can fix the error.
This is my ChatActivity
package com.socialcodia.sherewatan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.socialcodia.sherewatan.adapter.ChatAdapter;
import com.socialcodia.sherewatan.model.ChatModel;
import com.socialcodia.sherewatan.storage.Constants;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
Toolbar toolbar;
private EditText inputMessage;
private ImageButton btnSendMessage;
private TextView toolbarUserName, toolbarUserStatus;
private ImageView toolbarUserImage;
//Firebase
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
DatabaseReference chatDatabaseReference;
FirebaseUser firebaseUser;
RecyclerView chatRecyclerView;
Intent intent;
String toUid;
String myUid;
List<ChatModel> chatList;
ChatAdapter chatAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
//init Chat Recycler View
chatRecyclerView = findViewById(R.id.chatRecyclerView);
//set layout manager at chatRecyclerview
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
chatRecyclerView.setLayoutManager(layoutManager);
//Firebase Init
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
chatDatabaseReference = firebaseDatabase.getReference("Chats");
firebaseUser =firebaseAuth.getCurrentUser();
//Init
inputMessage = findViewById(R.id.inputMessage);
btnSendMessage = findViewById(R.id.btnSendMessage);
toolbarUserName = findViewById(R.id.toolbarUserName);
toolbarUserStatus = findViewById(R.id.toolbarUserStatus);
toolbarUserImage = findViewById(R.id.toolbarUserImage);
toolbar = findViewById(R.id.chat_toolbar);
setSupportActionBar(toolbar);
intent = getIntent();
//Data From intent
toUid = intent.getStringExtra("uid");
//Click listener on btn send message
btnSendMessage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
ValidateAndSendMessage();
}
});
getMessage();
}
private void ValidateAndSendMessage()
{
String message = inputMessage.getText().toString().trim();
if (message.isEmpty())
{
Toast.makeText(this, "Can't send empty message", Toast.LENGTH_SHORT).show();
}
else
{
sendMessage(message);
}
}
private void sendMessage(String message)
{
HashMap<String, Object> map = new HashMap<>();
map.put("msg",message);
map.put(Constants.TIMESTAMP,System.currentTimeMillis()/1000);
map.put("fromUid",myUid);
map.put("toUid",toUid);
DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.push().setValue(map);
inputMessage.setText("");
}
private void getMessage()
{
chatList = new ArrayList<>();
final DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren())
{
ChatModel chatModel = ds.getValue(ChatModel.class);
if (chatModel.getFromUid().equals(myUid) && chatModel.getToUid().equals(toUid) ||
chatModel.getFromUid().equals(toUid) && chatModel.getToUid().equals(myUid))
{
chatList.add(chatModel);
}
chatAdapter = new ChatAdapter(chatList,getApplicationContext());
chatAdapter.notifyDataSetChanged();
chatRecyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
This is my ChatAdapter.class
package com.socialcodia.sherewatan.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.socialcodia.sherewatan.R;
import com.socialcodia.sherewatan.model.ChatModel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
List<ChatModel> modelClassList;
Context context;
private static final int MSG_TYPE_RIGHT = 0;
private static final int MSG_TYPE_LEFT = 1;
FirebaseUser firebaseUser;
public ChatAdapter(List<ChatModel> modelClassList, Context context) {
this.modelClassList = modelClassList;
this.context = context;
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType==MSG_TYPE_RIGHT)
{
View view = LayoutInflater.from(context).inflate(R.layout.chat_right,parent,false);
ChatViewHolder viewHolder = new ChatViewHolder(view);
return viewHolder;
}
else
{
View view = LayoutInflater.from(context).inflate(R.layout.chat_left,parent,false);
ChatViewHolder viewHolder = new ChatViewHolder(view);
return viewHolder;
}
}
#Override
public void onBindViewHolder(#NonNull ChatViewHolder holder, int position) {
String msg = modelClassList.get(position).getMsg();
Long timestamp = modelClassList.get(position).getTimestamp();
holder.tvChatMessage.setText(msg);
holder.tvChatTime.setText(getTime(timestamp));
}
private String getTime(Long timestamp) {
Long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public int getItemCount() {
return modelClassList.size();
}
#Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (modelClassList.get(position).getFromUid().equals(firebaseUser.getUid()))
{
return MSG_TYPE_RIGHT;
}
else
{
return MSG_TYPE_LEFT;
}
}
public class ChatViewHolder extends RecyclerView.ViewHolder
{
private TextView tvChatMessage, tvChatTime;
public ChatViewHolder(#NonNull View itemView) {
super(itemView);
tvChatMessage = itemView.findViewById(R.id.tvChatMessage);
tvChatTime = itemView.findViewById(R.id.tvChatTime);
}
}
}
This is my ChatModel.class
package com.socialcodia.sherewatan.model;
public class ChatModel {
public String fromUid, toUid, msg;
Long timestamp;
public ChatModel() {
}
public ChatModel(String fromUid, String toUid, String msg, Long timestamp) {
this.fromUid = fromUid;
this.toUid = toUid;
this.msg = msg;
this.timestamp = timestamp;
}
public String getFromUid() {
return fromUid;
}
public void setFromUid(String fromUid) {
this.fromUid = fromUid;
}
public String getToUid() {
return toUid;
}
public void setToUid(String toUid) {
this.toUid = toUid;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
You forgot to clear the modelClassList.
private void getMessage()
{
chatList = new ArrayList<>();
final DatabaseReference chatRef = firebaseDatabase.getReference("Chats");
chatRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatList.clear(); // Clear list
for (DataSnapshot ds : dataSnapshot.getChildren())
{
ChatModel chatModel = ds.getValue(ChatModel.class);
if (chatModel.getFromUid().equals(myUid) && chatModel.getToUid().equals(toUid) ||
chatModel.getFromUid().equals(toUid) && chatModel.getToUid().equals(myUid))
{
chatList.add(chatModel);
}
chatAdapter = new ChatAdapter(chatList,getApplicationContext());
chatAdapter.notifyDataSetChanged();
chatRecyclerView.setAdapter(chatAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
That will clear the list as well fix your problem.
Declare HashMap or ArrayList globally and write this code map.clear() or arrayList.clear() at the very beginning of the method from which you are retreiving your data. Hopefully the problem will be solved.
This question already has an answer here:
android save object in firebase
(1 answer)
Closed 5 years ago.
Here is the class where i intend to read a Location type data item from firebase database and store it in a Location type Object. I even tried to store the datasnapshot in an object of the class that had a Location type argument in the constructor, i got the same error saying :
" com.google.firebase.database.DatabaseException: Class android.location.Location is missing a constructor with no arguments"
package com.example.aadi.sarthi_;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ActiveNotifications extends Fragment{
public static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
public RecyclerView recyclerView;
String user_mac;
public List<notifyListRowItem> result;
public UserAdapter userAdapter;
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
private DatabaseReference eventRef = reference.child("Events");
// Create a Intent send by the notification
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent( context, ActiveNotifications.class );
intent.putExtra( NOTIFICATION_MSG, msg );
return intent;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_active_notifications, container, false);
getMac();
result = new ArrayList<>();
recyclerView = (RecyclerView) view.findViewById(R.id.notification_list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager rlm = new LinearLayoutManager(getActivity());
rlm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(rlm);
/*
createNotifyListRowItem();*/
userAdapter = new UserAdapter(result);
recyclerView.setAdapter(userAdapter);
updateList();
return view;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case 0:
break;
case 1:
break;
}
return super.onContextItemSelected(item);
}
public void updateList(){
final DatabaseReference locationRef = reference.child(String.valueOf(user_mac)).child("location");
final Location userLoc = null;
final Location eventLoc = null;
locationRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Location location = dataSnapshot.getValue(Location.class);
userLoc.set(location);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
eventRef.limitToFirst(2).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
eventRef.push().child("location");
Location location = dataSnapshot.getValue(Location.class);
eventLoc.set(location);
if(eventLoc.distanceTo(userLoc)<=1000) {
result.add(dataSnapshot.getValue(notifyListRowItem.class));
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.w("asd", "In onChildChanged");
notifyListRowItem notifyListRowItem = dataSnapshot.getValue(notifyListRowItem.class);
int index = getItemIndex(notifyListRowItem);
result.set(index,notifyListRowItem);
userAdapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.w("In ", "OnchildRemoved");
notifyListRowItem model = dataSnapshot.getValue(notifyListRowItem.class);
int index = getItemIndex(model);
result.remove(index);
userAdapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.w("IN", "onChildMoved");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("IN", "onChildCancelled");
return;
}
});
}
private int getItemIndex(notifyListRowItem item){
int index = -1;
for (int i=0;i<result.size();i++){
if(result.get(i).key.equals(item.key)){
index = i;
break;
}
}
return index;
}
protected void getMac(){
GettingMac gettingMac = new GettingMac(getActivity());
user_mac = gettingMac.Mac();
}
}
You need to have an empty constructor for your Location class.
public Location () {}
You should need to add a constructor of your Location Class.
public Location() {
}