0

I am trying to get the birthday of a facebook test user from the login Button and then passing it to a firestore document. So, i have made a UserInfo class that holds both of the birthday and the id as strings so that i can get and set their values anytime. However when i get the birthday value from the facebook JSON and set it to userinfo it works but when i try to get this value from the getter i get a null object. this my code: Note, that i have initialize the UserInfo onStar. this my code:

package com.example.saif.dammi;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.firebase.auth.FirebaseAuth;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SignupActivity extends AppCompatActivity {

    private TextInputLayout mFullName;
    private RadioGroup mRadioButton;
    private Button mRegister;
    private FirebaseAuth mAuth;
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        // Access a Cloud Firestore instance from your Activity
       final FirebaseFirestore db = FirebaseFirestore.getInstance();
//        final String[] bD = new String[1];
        userInfo = new UserInfo();
        mAuth = FirebaseAuth.getInstance();
        mFullName = (TextInputLayout)findViewById(R.id.name_edittext);
        mRadioButton = (RadioGroup) findViewById(R.id.bloodGroup);
        mRegister = (Button)findViewById(R.id.register_btn);
        mRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int selectedId = mRadioButton.getCheckedRadioButtonId();
                final RadioButton mBloodGroup = (RadioButton)findViewById(selectedId);
                if(mBloodGroup.getText() == null){
                    Toast.makeText(SignupActivity.this, "Please select your Blood Group!", Toast.LENGTH_SHORT).show();
                    return;
                }

               final String name = mFullName.getEditText().getText().toString();
                if (mAuth.getCurrentUser().getUid()!=null) {
                    String userId = mAuth.getCurrentUser().getUid();
                    String userEmail = mAuth.getCurrentUser().getEmail();
                    Uri userPid = mAuth.getCurrentUser().getPhotoUrl();

                    /* make the API call */

                    GraphRequest request = GraphRequest.newMeRequest(
                            AccessToken.getCurrentAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                public void onCompleted(JSONObject object,GraphResponse response) {
                                    /* handle the result */
                                    try{
                                        userInfo.setBirthday(object.getString("birthday"));
//                                        bD[0] = object.getString("birthday");
                                        Log.d("Birthday", ""+ userInfo.getBirthday());
//
                                    }catch (JSONException e){
                                        e.printStackTrace();
                                    };
                                }
                            }
                    );
                    Bundle parameters = new Bundle();
                    parameters.putString("fields","id,email,friends,birthday");
                    request.setParameters(parameters);
                    request.executeAsync();

                    Log.d("Birthday1", ""+ userInfo.getBirthday());
                    final Map<String, Object> dataToAdd = new HashMap<>();
//                    dataToAdd.put("Birthday", bD[0]);
                    dataToAdd.put("name", name);
                    dataToAdd.put("id", userId);
                    dataToAdd.put("Pid", userPid.toString());
                    dataToAdd.put("email", userEmail);
                    dataToAdd.put("bloodGroup", mBloodGroup.getText().toString());
                    dataToAdd.put("registered", true);
                    db.collection("Users").document(mAuth.getCurrentUser().getUid()).set(dataToAdd).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(SignupActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

//                    DatabaseReference currentUserId = FirebaseDatabase.getInstance().getReference().child("Users").child(mBloodGroup.getText().toString()).child(userId).child("Name").child("Registred");
//                    currentUserId.setValue(name);
//                    currentUserId.child("Registred").setValue(true);
                    Intent startIntent = new Intent(SignupActivity.this, MainActivity.class);
                    startActivity(startIntent);
                    finish();
                }
            }
        });
    }
}

UserInfo.class

package com.example.saif.dammi;

/**
 * Created by Saif on 3/18/2018.
 */

public class UserInfo {
    String Birthday;
    String id;

//    public UserInfo(String birthday, String id) {
//        Birthday = birthday;
//        this.id = id;
//    }

    public String getBirthday() {
        return Birthday;
    }

    public void setBirthday(String birthday) {
        Birthday = birthday;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

Logs: Logs

1 Answers1

0

First of all, you need to add the no-argument constructor into your model class like this:

public UserInfo() {}

All JavaBean type objects should have one, so that reflection can be used to create an instance of it without having to guess how to pass parameters to it correctly.

Second, you cannot declare a variable of type UserInfo as global and simply use it outside the onCompleted() method. This is happening because this method has an asynchronous behaviour, which means that is called even before you are getting the data from the database. A quick fix would be to use the UserInfo object only inside the onCompleted() method or if you want to use it outside, please use the last part of my answer from this post. You can also take a look at this video.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • i have declared UserInfo in onCreate method like so : final FirebaseFirestore db = FirebaseFirestore.getInstance(); But i still get null object :/ – Saif eddine Mar 18 '18 at 19:26
  • I see how you have created. See my answer from that post for a better understanding. – Alex Mamo Mar 18 '18 at 19:30
  • I have followed your video tutorial on custom callbacks but the problem persists here the updated code: UploadData(new UserInfoCallback() { @Override public void onCallback(String data) { dataToAdd.put("Birthday", data); } }); – Saif eddine Mar 18 '18 at 21:44
  • Alex thanks a lot mate!! i have moved all of the firestore data update into that call back and it works! – Saif eddine Mar 18 '18 at 21:53
  • Good to hear that! Cheers! – Alex Mamo Mar 18 '18 at 22:29