How to get value from pushed data in Firebase? - java

In my firebase I have questions and their answers stored. Each answer has an id, which it got from push(). But I am unable to show the list of all the users who have answered the question. Please help.
Here is the code:
ListView listView;
ArrayList<String> answerers = new ArrayList<>();
ArrayAdapter arrayAdapter;
String askedBy, question, likes;
FirebaseAuth mAuth;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_answers);
listView = findViewById(R.id.answersListView);
Intent intent = getIntent();
askedBy = intent.getStringExtra("askedBy");
question = intent.getStringExtra("question");
likes = intent.getStringExtra("numberOfLikes");
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("questions").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
if (dataSnapshot.child("question").getValue().toString().equals(question) && dataSnapshot.child("askedBy").getValue().toString().equals(askedBy)
&& dataSnapshot.child("likes").getValue().toString().equals(likes)) {
dataSnapshot.child("answers").getRef().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
arrayAdapter = new ArrayAdapter<>(ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent1 = new Intent(ViewAnswersActivity.this, AnswerActivity.class);
intent1.putExtra("askedBy", askedBy);
intent1.putExtra("answeredBy", answerers.get(i));
intent1.putExtra("question", question);
intent1.putExtra("numberOfLikes", likes);
startActivity(intent1);
}
});
}
When I am running the app, the listView is coming empty, indicating value hasn't been stored.

Try to set adapter within onDataChange()
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
arrayAdapter = new ArrayAdapter<> (ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}

Related

Android Firebase query return Null

I'm working on a project where there's an activity which contains 3 spinners( Nested). I need the 2nd spinner to have the data based on the selected item of the 1st spinner and the data is retrieved from Firebase
The 1st spinner is going to have all "Gouv" values , the 2nd one is going to have the "Deleg" values where "Gouv" value is equal to the selected item "Gouv" of the 1st spinner .
Here is the code that i tried and i keep get in the log Null .
public class RechCode extends AppCompatActivity {
DatabaseReference spinnerRef;
Query spinnerRefG;
Spinner spinnerG;
Spinner spinnerD;
Spinner spinnerL;
ArrayAdapter<String> adapterG;
ArrayAdapter<String> adapterL;
ArrayAdapter<String> adapterD;
ArrayList<String> spinnerDList;
ArrayList<String> spinnerGList;
ArrayList<String> spinnerLOList;
Query spinnerRefD;
private String ChoixG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rech_code);
spinnerG = findViewById(R.id.SpinnerGouv);
spinnerD = findViewById(R.id.SpinnerDeleg);
spinnerL = findViewById(R.id.SpinnerLoc);
spinnerRef = FirebaseDatabase.getInstance().getReference().child("CodePostale");
//Query queryD = spinnerG.("state", "CA");
spinnerGList = new ArrayList<>();
spinnerDList = new ArrayList<>();
spinnerLOList = new ArrayList<>();
adapterD= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerDList);
adapterL= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerLOList);
adapterG= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerGList);
spinnerG.setAdapter(adapterG);
spinnerD.setAdapter(adapterD);
spinnerL.setAdapter(adapterL);
ShowdataGouv();
spinnerRefG= FirebaseDatabase.getInstance().getReference("CodePostale").child("Deleg").orderByChild("Gouv").equalTo(ChoixG);
ShowdataDeleg();
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ChoixG = spinnerGList.get(i);
Toast.makeText(getApplicationContext(), "Gouvernorat:" + ChoixG, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
Button retour = (Button) findViewById(R.id.return_btn);
retour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetourMenu();
}
});
}
private void ShowdataLoc(String text) {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot item:snapshot1.getChildren()){
spinnerLOList.add(item.child("Loc").getValue().toString());
}
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataDeleg() {
spinnerRefG.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot2) {
for (DataSnapshot item:snapshot2.getChildren()){
spinnerDList.add(item.child("Deleg").getValue().toString());
}
Log.d("Value","BBBBBBBB"+ snapshot2);
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataGouv() {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot3) {
for (DataSnapshot item:snapshot3.getChildren()){
spinnerGList.add(item.child("Gouv").getValue().toString());
Log.d("Value","AAAAAAAAA"+ snapshot3);
}
adapterG.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void RetourMenu() {
Intent intent = new Intent(getApplicationContext(), Menus.class);
startActivity(intent);
}
}
The problem is in the way you construct the query here:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.child("Deleg")
.orderByChild("Gouv")
.equalTo(ChoixG);
You're asking to load child nodes of /CodePostale/Deleg that have a Gouv property with a value of ChoixG. But if we check the screenshot of the data, there is no /CodePostale/Deleg, so no data is returned.
What you want instead is to check the child nodes of /CodePostale and return the ones where their Deleg/Gouv property has a value of ChoixG, which you can do with:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.orderByChild("Deleg/Gouv")
.equalTo(ChoixG);

Firebase database set objects in favorite list

I have a problem clearing list in fragments. I need to clear the list when happening update in fragment. I already put it in different places but it does not help me.
When an update happens in fragment it shows the same list but that list also add elements from the previous list. If I put list.clear(); in the moment when it rakes arguments from firebase it did not give me needed effect, when I put it in onCreate() method then app gives me error.
public class Favourite extends Fragment {
private RecyclerView recyclerView;
private ArrayList<TourReader1> artistList;
private ToursAdapter1 adapter1;
private DatabaseReference reference,reference2;
String uid;
public Favourite() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Get current user id
uid = user.getUid();
//Connect to specific point in database Tours
reference = FirebaseDatabase.getInstance().getReference("Tours");
//Create add to method valuelistener or reference which is specific point in database
reference2 = FirebaseDatabase.getInstance().getReference("user").child(uid);
reference.addValueEventListener(valueEventListener);
reference.keepSynced(true);
}
ValueEventListener valueEventListener = (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
//get all information from specific point of database
for (DataSnapshot datasnapshot : snapshot1.getChildren()) {
//get current name of starting point from where we recive information from database
String firstname = datasnapshot.getKey();
//valuelistener for another point from database
reference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dSnapshot2:snapshot.getChildren()){
String seconame = dSnapshot2.getKey();
Boolean control = dSnapshot2.child("like").getValue(Boolean.class);
if(control != null&&firstname.equals(seconame) &&control.equals(true)) {
TourReader1 artist = datasnapshot.getValue(TourReader1.class);
artistList.add(artist);
}
}
adapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
artistList = new ArrayList<>();
View rootview = inflater.inflate(R.layout.favourite, container, false);
recyclerView = rootview.findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter1 = new ToursAdapter1(getContext(), artistList);
recyclerView.setAdapter(adapter1);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mGridLayoutManager);
return rootview;
}
}
You should clear the artistList using artistList.clear() before your for loop in onDataChangeas this list is having the data from the last callback triggered.
Ok, I found the answer myself, I clear my list in the adapter by tourlist.clear() and remove userpoints.keepSynced(true); when like icon is false.
holder.sparkButton.setEventListener(new SparkEventListener() {
#Override
public void onEvent(ImageView button, boolean buttonState) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference userpoints = FirebaseDatabase.getInstance().getReference("user").child(uid);
ToursLike registerDatabase = new ToursLike(true);
if(buttonState){
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(tour.Name)) {
userpoints.child(tour.Name).setValue(registerDatabase);
userpoints.keepSynced(true);
tourList.clear();
}
else{
userpoints.child(tour.Name).child("like").setValue(true);
userpoints.keepSynced(true);
tourList.clear();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else{
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userpoints.child(tour.Name).child("like").setValue(false);
tourList.clear();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onEventAnimationEnd(ImageView button, boolean buttonState) {
}
#Override
public void onEventAnimationStart(ImageView button, boolean buttonState) {
}
});
}

Chat messages saved in firebase database but not able to view in listview

For my chat application, I have saved EditText data to firebase but not I am not able to display the same in ListView. I am able to see the EditText data in Firebase database and I want to retrieve it in a ListView. Anybody can help me?
public class Chatbox extends AppCompatActivity {
private DatabaseReference databaseReference;
private Button btnsend;
private EditText editText;
private ListView listView;
private ArrayList<String> arrayList = new ArrayList<>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbox);
databaseReference = FirebaseDatabase.getInstance().getReference();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
btnsend = findViewById(R.id.sendbutton);
editText = findViewById(R.id.typemessage);
listView = findViewById(R.id.listmessages);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.child("Chat").child("Name").push().setValue(editText.getText().toString());
}
});
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getKey();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
catch (Exception ex)
{
Toast.makeText(Chatbox.this, "Error " + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try this
FirebaseDatabase.getInstance()
.getReference("Chat")
.child("Name")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> chatMessages = new ArrayList<>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
try {
String chatMessage = String.valueOf(dataSnapshot.child(dataSnapshot1.getKey()).getValue());
chatMessages.add(chatMessage);
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
callback.onFailure(null);
}
});
i guess you want to retrive data not the key:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getValue();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
or want you to store both in a array list key and value together?
You're adding the messages to the database with:
databaseReference.child("Chat").child("Name")
That means you must also read the messages from the same path:
databaseReference.child("Chat").child("Name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.getValue(String.class);
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()l
}
});
The changes:
Listen to the same node as you're adding the messages to.
Removed the nested listener, which is not needed.
Get the value from each child snapshot, instead of trying to read a non-existing Name property.
Removed the try...catch as the default behavior is to write messages to logcat, which is more useful than showing them in a toast.
Implemented onCancelled, because you should never ignore errors.

Adding values from Firebase to RecycleView adapter won't show in app

I'm trying to return the key and value from my Firebase Database and insert it into a RecycleView adapter but the values won't show up in the app.
I can't wrap my head around this whatsoever.
I tried to show the values in a Toast and it worked but why won't the values be inserted into the RecycleView adapter?
This is the code.
public class test extends AppCompatActivity {
TextView textView;
Button button;
String phone;
String n;
String a;
FirebaseAuth mAuth;
MyRecyclerViewAdapter adapter;
ArrayList<String> info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Bundle b = new Bundle();
b = getIntent().getExtras();
phone = b.getString("number");
textView = findViewById(R.id.textV);
button = findViewById(R.id.signoutButton);
mAuth = FirebaseAuth.getInstance();
textView.setText(textView.getText().toString() + " as " + phone);
info = new ArrayList<>();
FirebaseDatabase myRef = FirebaseDatabase.getInstance();
DatabaseReference sRef = myRef.getReference("users");
sRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnap : dataSnapshot.getChildren()) {
if (childSnap.getKey().equals(phone)) {
for (DataSnapshot c : childSnap.getChildren()) {
n = c.getKey();
a = c.getValue().toString();
info.add(n);
info.add(a);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RecyclerView recyclerView = findViewById(R.id.rvInfo);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, info);
adapter.setClickListener(new MyRecyclerViewAdapter.ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(test.this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
});
recyclerView.setAdapter(adapter);
}
}
You can get this using following code
sRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnap : dataSnapshot.getChildren()) {
if (childSnap.getKey().equals(phone)) {
for (DataSnapshot c : childSnap.getChildren()) {
n = c.getKey();
a = c.getValue().toString();
info.add(n);
info.add(a);
}
}
}
notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You have to add notifyDataSetChanged(); after you fill ArrayList from firebase. Because it's take time to load data from firebase. And your adapter initialised before fill ArrayList from firebase.

Can't convert object of type java.lang.String to type In DatabaseReferance

I'm building a simple chat application. In user fragment, if we click on user it get crashed and go to previous activity if there is previous chat. While there is no chat with that user fragment works fine, but when we type message and click send message store on Firebase and app crashes, similarly if there is chat, chat fragment get crashed.
I think problem is in mReference.addValueEventListener(new ValueEventListener()) method. Code and error is given below. I saw other answers but didn't understand with my code.
MessageActivity.java
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username;
FirebaseUser mFirebaseUser;
DatabaseReference mDatabaseReference;
ImageView btn_send;
EditText send_msg;
Intent mIntent;
MessageAdapter mMessageAdapter;
List<Chat> mChats;
RecyclerView mRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
profile_image = findViewById(R.id.profile_image);
username = findViewById(R.id.username);
btn_send = findViewById(R.id.img_btn_send);
send_msg = findViewById(R.id.text_send);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mIntent = getIntent();
final String userid = mIntent.getStringExtra("userid");
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = send_msg.getText().toString();
if (!msg.equals("")){
sendMessage(mFirebaseUser.getUid(), userid, msg);
}
send_msg.setText("");
}
});
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
assert user != null;
username.setText(user.getUsername());
if ( user.getImageURL().equals("default")){
profile_image.setImageResource(R.mipmap.ic_launcher_round);
}else {
Glide.with(MessageActivity.this).load(user.getImageURL()).into(profile_image);
}
readMessage(mFirebaseUser.getUid(), userid, user.getImageURL());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
mDatabaseReference.child("Chats").setValue(hashMap);
}
private void readMessage(final String myId, final String userID, final String imageURL){
mChats = new ArrayList<>();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Chats");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChats.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Chat chat = dataSnapshot1.getValue(Chat.class);
assert chat != null;
if (chat.getReceiver().equals(myId) && chat.getSender().equals(userID) || chat.getReceiver().equals(userID) && chat.getSender().equals(myId)){
mChats.add(chat);
}
mMessageAdapter = new MessageAdapter(MessageActivity.this, mChats, imageURL);
mRecyclerView.setAdapter(mMessageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
ChatsFragment.java
public class ChatsFragment extends Fragment {
private RecyclerView mRecyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
FirebaseUser fUser;
DatabaseReference mReference;
private List<String> userList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chats, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fUser = FirebaseAuth.getInstance().getCurrentUser();
userList = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Chats");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getSender().equals(fUser.getUid())){
userList.add(chat.getReceiver());
}
if (chat.getReceiver().equals(fUser.getUid())){
userList.add(chat.getSender());
}
}
readChats();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
private void readChats() {
mUsers = new ArrayList<>();
mReference = FirebaseDatabase.getInstance().getReference("Users");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
for (String id : userList){
if (user.getId().equals(id)){
if (mUsers.size() != 0){
for ( User user1 : mUsers){
if ( !user.getId().equals(user1.getId()));
mUsers.add(user);
}
}
else{
mUsers.add(user);
}
}
}
}
mUserAdapter = new UserAdapter(getContext(), mUsers);
mRecyclerView.setAdapter(mUserAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Error is :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.4:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.4:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.4:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.4:212)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6228)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

Categories