简体   繁体   中英

Firebase DatabaseException: Can't convert object of type java.lang.String to type

Getting this error in my LapitChat App. I am not able to solve this i try to figure out many ways to solve but I am not able to solve this. I added my class code with model and db image.

My firebase structure is

数据库 IMG

Error I am getting when i click on Friends Fragment.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.divyanshi.chatapp, PID: 29577
    com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.divyanshi.chatapp.model.Friends
        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.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29)
        at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:15)
        at com.firebase.ui.common.BaseCachingSnapshotParser.parseSnapshot(BaseCachingSnapshotParser.java:36)
        at com.firebase.ui.common.BaseObservableSnapshotArray.get(BaseObservableSnapshotArray.java:52)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:109)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:149)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1897)
        at androidx.recyclerview.widget.RecyclerView$1.run(RecyclerView.java:414)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:693)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 29577 SIG: 9

FriendsFragment.java

package com.divyanshi.chatapp.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.divyanshi.chatapp.R;
import com.divyanshi.chatapp.model.Friends;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
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 com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class FriendsFragment extends Fragment {

    private RecyclerView mFriendList;
    private FirebaseAuth mAuth;
    private DatabaseReference mFriendDatabase;
    private DatabaseReference mUserDatabase;
    String mCurrent_user_id;
    private View mMainView;

    public FriendsFragment(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mMainView = inflater.inflate(R.layout.friends_fragment, container, false);
        mFriendList = mMainView.findViewById(R.id.friends_list);
        mAuth = FirebaseAuth.getInstance();

        mCurrent_user_id = mAuth.getCurrentUser().getUid();

        mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);
        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("users");

        mFriendList.setHasFixedSize(true);
        mFriendList.setLayoutManager(new LinearLayoutManager(getContext()));

        return mMainView;
    }

    @Override
    public void onStart() {
        super.onStart();

        FirebaseRecyclerOptions<Friends> friendsFirebaseRecyclerOptions =
                new FirebaseRecyclerOptions.Builder<Friends>()
                        .setQuery(mFriendDatabase, Friends.class)
                        .build();

        FirebaseRecyclerAdapter<Friends, FriendsViewHolder> adapter = new FirebaseRecyclerAdapter
                <Friends, FriendsFragment.FriendsViewHolder>(friendsFirebaseRecyclerOptions) {

            @Override
            protected void onBindViewHolder(final FriendsViewHolder holder, int position, @NonNull Friends model) {

                String list_user_id = getRef(position).getKey();
                mUserDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {

                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        String username = dataSnapshot.child("name").getValue().toString();
                        String status = dataSnapshot.child("status").getValue().toString();
                        String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

                        holder.tv_usersSingle_username.setText(username);
                        holder.tv_usersSingle_status.setText(status);

                        if (!thumb_image.equals("default")) {
                            Picasso.with(getContext()).load(thumb_image).placeholder(R.mipmap.ic_launcher_round).into(holder.iv_usersSingle_image);
                        }

                        Log.d("Special", "I am log name" );
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
            }

            @Override
            public FriendsFragment.FriendsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.users_single_layout, parent, false);

                return new FriendsViewHolder(view);
            }
        };

        mFriendList.setAdapter(adapter);
        adapter.startListening();
    }

    public static class FriendsViewHolder extends RecyclerView.ViewHolder {
        private TextView tv_usersSingle_username, tv_usersSingle_status;
        private CircleImageView iv_usersSingle_image;

        public FriendsViewHolder(@NonNull View itemView) {
            super(itemView);

            tv_usersSingle_username = itemView.findViewById(R.id.user_single_name);
            tv_usersSingle_status = itemView.findViewById(R.id.user_single_status);
            iv_usersSingle_image = itemView.findViewById(R.id.user_single_image);

        }



    }
}


Friends.java Model

package com.divyanshi.chatapp.model;

public class Friends {


    public String name, image, status, date;

    public Friends() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

ProfileActivity.java

package com.divyanshi.chatapp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.Bundle;

import java.text.DateFormat;

import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
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.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ProfileActivity extends AppCompatActivity {

    private ImageView mProfileImage;
    private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
    private Button mProfileSendReqBtn, nDeclineBtn;

    private DatabaseReference mUserDatabase;

    private ProgressDialog mProgressDialog;

    private DatabaseReference mFriendReqDatabase;
    private DatabaseReference mFriendsDatabase;
    private DatabaseReference mNotificationDatabase;
    private DatabaseReference mRootRef;

    private FirebaseUser mCurrent_user;

    private String mCurrent_State;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        final String user_id = getIntent().getStringExtra("user_id");

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(user_id);
        mFriendReqDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req");
        mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("notification");
        mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();
        mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends");
        mRootRef=FirebaseDatabase.getInstance().getReference();
        mProfileImage = (ImageView) findViewById(R.id.profile_image);
        mProfileName = (TextView) findViewById(R.id.profile_display_name);
        mProfileStatus = (TextView) findViewById(R.id.profile_status);
        mProfileFriendsCount = (TextView) findViewById(R.id.Profile_totalFrnds);
        mProfileSendReqBtn = (Button) findViewById(R.id.profile_SendReq);
        nDeclineBtn = (Button) findViewById(R.id.profile_Decline_reqBtn);


        mCurrent_State = "not_friends";


        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("Loading UserData");
        mProgressDialog.setMessage("Please wait while we load the data.");
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();

        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String display_name = snapshot.child("name").getValue().toString();
                String status = snapshot.child("status").getValue().toString();
                String image = snapshot.child("image").getValue().toString();

                mProfileName.setText(display_name);
                mProfileStatus.setText(status);

                Picasso.with(ProfileActivity.this).load(image).placeholder(R.drawable.default_avatar).into(mProfileImage);


                //-------FRIEND LIST /REQUEST FEATURE--------//

                mFriendReqDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        if (snapshot.hasChild(user_id)) {

                            String req_type = snapshot.child(user_id).child("request_type").getValue().toString();
                            if (req_type.equals("received")) {
                                mCurrent_State = "req_received";
                                mProfileSendReqBtn.setText("Accept Friend Request");
                                nDeclineBtn.setVisibility(View.VISIBLE);
                                nDeclineBtn.setEnabled(true);

                            } else if (req_type.equals("sent")) {
                                mCurrent_State = "Req_sent";
                                mProfileSendReqBtn.setText("Cancel Friend Request");

                                nDeclineBtn.setVisibility(View.INVISIBLE);
                                nDeclineBtn.setEnabled(false);
                            }
                            mProgressDialog.dismiss();


                        } else {
                            mFriendsDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    if (snapshot.hasChild(user_id)) {

                                        mCurrent_State = "friends";
                                        mProfileSendReqBtn.setText("Unfriend this Person");

                                        nDeclineBtn.setVisibility(View.INVISIBLE);
                                        nDeclineBtn.setEnabled(false);
                                    }
                                    mProgressDialog.dismiss();

                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {


                                }
                            });
                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });


            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProfileSendReqBtn.setEnabled(false);

                // NOT FRIEND STATE//

                if (mCurrent_State.equals("not_friends")) {

                    mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).child("request_type").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).child("request_type").setValue("received").addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {

                                        HashMap<String, String> notificationData = new HashMap<>();
                                        notificationData.put("from", mCurrent_user.getUid());
                                        notificationData.put("type", "request");

                                        mNotificationDatabase.child(user_id).push().setValue(notificationData).addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {
                                                mCurrent_State = "Req_sent";

                                                mProfileSendReqBtn.setText("Cancel Friend Request");

                                                nDeclineBtn.setVisibility(View.INVISIBLE);
                                                nDeclineBtn.setEnabled(false);
                                            }
                                        });


                                        //   Toast.makeText(ProfileActivity.this, "Request Sent Successfully.", Toast.LENGTH_SHORT).show();
                                    }


                                });

                            } else {
                                Toast.makeText(ProfileActivity.this, "Failed to send the Request, Please try again.", Toast.LENGTH_SHORT).show();
                            }
                            mProfileSendReqBtn.setEnabled(true);
                        }
                    });

                }

                // Cancel the request //

                if (mCurrent_State.equals("Req_sent")) {

                    mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {

                            mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    mProfileSendReqBtn.setEnabled(true);
                                    mCurrent_State = "not_friends";

                                    mProfileSendReqBtn.setText("Send Friend Request");
                                    nDeclineBtn.setVisibility(View.INVISIBLE);
                                    nDeclineBtn.setEnabled(false);


                                }
                            });


                        }
                    });
                }


                if (mCurrent_State.equals("req_received")){

                    final String currentDate=DateFormat.getDateTimeInstance().format(new Date());
                    Map friendMap = new HashMap();
                    friendMap.put("Friends/"+mCurrent_user.getUid()+"/"+user_id+"/date",currentDate);
                    friendMap.put("Friends/"+user_id+"/"+mCurrent_user.getUid()+"/date",currentDate);
                    friendMap.put("Friend_req/"+mCurrent_user.getUid()+"/"+user_id,null);
                    friendMap.put("Friend_req/"+user_id+"/"+mCurrent_user.getUid(),null);

                    mRootRef.updateChildren(friendMap, new DatabaseReference.CompletionListener() {
                        @Override
                        public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
                            mProfileSendReqBtn.setEnabled(true);
                            mCurrent_State = "friends";
                            mProfileSendReqBtn.setText("UnFriend this person");
                        }
                    });

                }
            }
        });

    }
}

    com.google.firebase.database.DatabaseException: Can't convert object of
    type java.lang.String to type com.divyanshi.chatapp.model.Friends

The exception tells you that you are trying to convert an object of type String into Friends

Looking into code, where you receive firebase dataSanpshot object, you are trying this conversion in below snippet:

String username = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

dataSnapshot.child("name").getValue() should be returning a Friends object, and Because you call toString() , you are trying to convert it to a String, and hence the exception is raised.

To solve this, you can iterate over dataSnapshot children, get a Friends object each time, and extract its data using its getters.

So, to solve this, change onBindViewHolder to below:

@Override
protected void onBindViewHolder(final FriendsViewHolder holder, int position, @NonNull Friends model) {

    String list_user_id = getRef(position).getKey();
    mUserDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            
            for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
                Friends friend = singleSnapshot.getValue(Friends.class);
                String username = friend.getName();
                String status = friend.getStatus();
                String thumb_image = friend.getImage();

                holder.tv_usersSingle_username.setText(username);
                holder.tv_usersSingle_status.setText(status);

                if (!thumb_image.equals("default")) {
                    Picasso.with(getContext()).load(thumb_image).placeholder(R.mipmap.ic_launcher_round).into(holder.iv_usersSingle_image);
                }

                Log.d("Special", "I am log name" );                 
            }
            
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

The problem is that your database structure returns a string not an object. You are essentially trying to convert the single key value pair "sd7f57sf7s6sd89f79s":"your_date_here" to Friends.class which is impossible.

You should check out the following link. it should help you know how to save an object into RTdB. Make sure to follow along.

Saving and Retrieving data from Realtime Database

Convert

mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("Friends").child(mCurrent_user_id);

into

mFriendDatabase = FirebaseDatabase.getInstance().getReference("/Friends");

The data that you have under each /Friends/$uid/$otheruid node is a key with a single string value. This does not match the fields/properties of the Friends class, so that's why you get an error.

My guess is that you have the JSON with the properties for each user under /users , and want the recycler view to show the properties from there. If that's the case you have to tell the adapter to look up the data for each, as shown in the FirebaseUI documentation on showing indexed data .

FirebaseRecyclerOptions<Friends> friendsFirebaseRecyclerOptions =
        new FirebaseRecyclerOptions.Builder<Friends>()
                .setIndexedQuery(mFriendDatabase, mUserDatabase, Friends.class)
                .build();

I was putting wrong pair of userid:date. that's why error is coming. I solved it by putting date in next row. Below code I used to solve.

package com.divyanshi.chatapp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.Bundle;

import java.text.DateFormat;

import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
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.ValueEventListener;
import com.squareup.picasso.Picasso;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ProfileActivity extends AppCompatActivity {

    private ImageView mProfileImage;
    private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
    private Button mProfileSendReqBtn, nDeclineBtn;
    private DatabaseReference mUserDatabase;
    private ProgressDialog mProgressDialog;
    private DatabaseReference mFriendReqDatabase;
    private DatabaseReference mFriendsDatabase;
    private DatabaseReference mNotificationDatabase;
    private DatabaseReference mRootRef;

    private FirebaseUser mCurrent_user;

    private String mCurrent_State;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        final String user_id = getIntent().getStringExtra("user_id");

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("users").child(user_id);
        mFriendReqDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req");
        mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("notification");
        mCurrent_user = FirebaseAuth.getInstance().getCurrentUser();
        mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("Friends");
        mRootRef = FirebaseDatabase.getInstance().getReference();
        mProfileImage = (ImageView) findViewById(R.id.profile_image);
        mProfileName = (TextView) findViewById(R.id.profile_display_name);
        mProfileStatus = (TextView) findViewById(R.id.profile_status);
        mProfileFriendsCount = (TextView) findViewById(R.id.Profile_totalFrnds);
        mProfileSendReqBtn = (Button) findViewById(R.id.profile_SendReq);
        nDeclineBtn = (Button) findViewById(R.id.profile_Decline_reqBtn);

        mCurrent_State = "not_friends";

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("Loading UserData");
        mProgressDialog.setMessage("Please wait while we load the data.");
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();

        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String display_name = snapshot.child("name").getValue().toString();
                String status = snapshot.child("status").getValue().toString();
                String image = snapshot.child("image").getValue().toString();

                mProfileName.setText(display_name);
                mProfileStatus.setText(status);

                Picasso.with(ProfileActivity.this).load(image).placeholder(R.drawable.default_avatar).into(mProfileImage);


                //-------FRIEND LIST /REQUEST FEATURE--------//

                mFriendReqDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        if (snapshot.hasChild(user_id)) {

                            String req_type = snapshot.child(user_id).child("request_type").getValue().toString();
                            if (req_type.equals("received")) {
                                mCurrent_State = "req_received";
                                mProfileSendReqBtn.setText("Accept Friend Request");
                                nDeclineBtn.setVisibility(View.VISIBLE);
                                nDeclineBtn.setEnabled(true);

                            } else if (req_type.equals("sent")) {
                                mCurrent_State = "Req_sent";
                                mProfileSendReqBtn.setText("Cancel Friend Request");

                                nDeclineBtn.setVisibility(View.INVISIBLE);
                                nDeclineBtn.setEnabled(false);
                            }
                            mProgressDialog.dismiss();


                        } else {
                            mFriendsDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    if (snapshot.hasChild(user_id)) {

                                        mCurrent_State = "friends";
                                        mProfileSendReqBtn.setText("Unfriend this Person");

                                        nDeclineBtn.setVisibility(View.INVISIBLE);
                                        nDeclineBtn.setEnabled(false);
                                    }
                                    mProgressDialog.dismiss();

                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {


                                }
                            });
                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });


            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProfileSendReqBtn.setEnabled(false);

                // NOT FRIEND STATE//
                if (mCurrent_State.equals("not_friends")) {

                    mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).child("request_type").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).child("request_type").setValue("received").addOnSuccessListener(new OnSuccessListener<Void>() {
                                    @Override
                                    public void onSuccess(Void aVoid) {

                                        HashMap<String, String> notificationData = new HashMap<>();
                                        notificationData.put("from", mCurrent_user.getUid());
                                        notificationData.put("type", "request");

                                        mNotificationDatabase.child(user_id).push().setValue(notificationData).addOnSuccessListener(new OnSuccessListener<Void>() {
                                            @Override
                                            public void onSuccess(Void aVoid) {
                                                mCurrent_State = "Req_sent";

                                                mProfileSendReqBtn.setText("Cancel Friend Request");

                                                nDeclineBtn.setVisibility(View.INVISIBLE);
                                                nDeclineBtn.setEnabled(false);
                                            }
                                        });


                                    }


                                });

                            } else {
                                Toast.makeText(ProfileActivity.this, "Failed to send the Request, Please try again.", Toast.LENGTH_SHORT).show();
                            }
                            mProfileSendReqBtn.setEnabled(true);
                        }
                    });

                }

                // Cancel the request //
                if (mCurrent_State.equals("Req_sent")) {

                    mFriendReqDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {

                            mFriendReqDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    mProfileSendReqBtn.setEnabled(true);
                                    mCurrent_State = "not_friends";

                                    mProfileSendReqBtn.setText("Send Friend Request");
                                    nDeclineBtn.setVisibility(View.INVISIBLE);
                                    nDeclineBtn.setEnabled(false);


                                }
                            });


                        }
                    });
                }

                if (mCurrent_State.equals("req_received")) {

                    final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
                    Map friendMap = new HashMap();
                    friendMap.put("Friends/" + mCurrent_user.getUid() + "/" + user_id + "/date", currentDate);
                    friendMap.put("Friends/" + user_id + "/" + mCurrent_user.getUid() + "/date", currentDate);
                    friendMap.put("Friend_req/" + mCurrent_user.getUid() + "/" + user_id, null);
                    friendMap.put("Friend_req/" + user_id + "/" + mCurrent_user.getUid(), null);

                    mRootRef.updateChildren(friendMap, new DatabaseReference.CompletionListener() {
                        @Override
                        public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
                            mProfileSendReqBtn.setEnabled(true);
                            mCurrent_State = "friends";
                            mProfileSendReqBtn.setText("UnFriend this person");
                        }
                    });
                }
            }

        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM