繁体   English   中英

facebook sdk Graphrequest对象在android中返回null

[英]facebook sdk Graphrequest object returns null in android

我正在尝试获取Facebook用户详细信息,例如姓名,用户ID,电子邮件,位置,性别。 我在日志中收到带有用户信息的响应,但无法存储在会话中或发送给其他活动,例如从“登录活动”到“主活动”的表单,下面是我在“登录活动”中的代码

public class LoginActivity extends AppCompatActivity {

    LoginButton fbloginbtn;
    CallbackManager callbackManager;
    private EditText username_login,password_login;

    Typeface tf;
    ProfilePictureView profilePictureView;

    AccessTokenTracker accessTokenTracker;
    ProfileTracker mprofileTracker;

    private ProgressDialog progressDialog;
    private Session session;
    private Button loginbtn;
    private TextView register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        session = new Session(LoginActivity.this);

        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        username_login = (EditText) findViewById(R.id.login_username);
        password_login = (EditText) findViewById(R.id.login_password);
        loginbtn = (Button) findViewById(R.id.login_btn);
        register = (TextView) findViewById(R.id.register);

        tf= Typeface.createFromAsset(getAssets(),"fonts/Roboto-Thin.ttf");
        username_login.setTypeface(tf);
        password_login.setTypeface(tf);

        fbloginbtn = (LoginButton) findViewById(R.id.fb_login_btn);
        callbackManager = CallbackManager.Factory.create();

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(),RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = username_login.getText().toString();
                String password = password_login.getText().toString();

                if(username.trim().length() > 0 && password.trim().length() > 0){

                    checkLogin(username,password);
                }else{
                    Toast.makeText(LoginActivity.this,"Please Enter The Credentials!", Toast.LENGTH_LONG).show();
                }
            }
        });

        callbackManager = CallbackManager.Factory.create();
        LoginManager loginManager = LoginManager.getInstance();
        fbloginbtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                AccessToken accessToken = AccessToken.getCurrentAccessToken();
                //Profile profile = Profile.getCurrentProfile();

                getProfileInformationFacebook(accessToken);
                Log.e("login res", loginResult.toString());


                session.setFblogin(true);
               //Intent fblogin = new Intent(LoginActivity.this,MainActivity.class);
               //startActivity(fblogin);
               //finish();
            }

            @Override
            public void onCancel() {

                Toast.makeText(LoginActivity.this, "Your Login is Cancel ", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(LoginActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();

            }
        });

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        callbackManager.onActivityResult(requestCode,resultCode,data);
    }

    private void checkLogin(final String username, final String password) {
        String tag_string_req = "req_login";

        progressDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppURLs.URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    String userId = jObj.getString("user_id");
                    String uname = jObj.getString("uname");

                    //JSONObject subObj = new JSONObject("user");
                    //String userName = subObj.getString("name");

                    if (userId != null) {
                        session.setLogin(true);
                        session.setMember(userId , uname);
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        intent.putExtra("user_id", userId);
                        intent.putExtra("uname", uname);
                        startActivity(intent);
                        finish();
                    } else {
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Post params to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "login");
                params.put("username", username);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to  queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }


//Exit on press twice
    boolean doubleBackToExitPressedOnce = false;

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);
    }

   // fb user informaiton
    public void getProfileInformationFacebook(AccessToken accToken) {
        GraphRequest request = GraphRequest.newMeRequest(
                accToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        Log.e("object", object.toString());
                        String fbId = null;
                        String fbBirthday = null;
                        String fbLocation = null;
                        String fbEmail = null;
                        String fbName = null;
                        String fbGend = null;
                        String fbPropic = null;

                        try {
                            fbId = object.getString("id");
                           fbEmail = object.getString("email");
                           fbName = object.getString("name");
                           fbGend = object.getString("gender");
                            fbBirthday = object.getString("birthday");
                           JSONObject jsonObject = object.getJSONObject("location");
                           fbLocation = jsonObject.getString("name");

                            //fbPropic = "https://graph.facebook.com/\"+ fbId +\"/picture?type=small";

                            session.FbLogindata(fbId, fbName, fbPropic, fbLocation, fbGend, fbEmail);


                                Intent fbdata = new Intent(LoginActivity.this, MainActivity.class);
                                fbdata.putExtra("fbid",object.getString("id"));
                                fbdata.putExtra("fbname",object.getString("name"));
                                fbdata.putExtra("email",object.getString("email"));
                                fbdata.putExtra("gender",object.getString("gender"));
                                fbdata.putExtra("location",jsonObject.getString("name"));

                               // main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
                                startActivity(fbdata);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,location,gender,birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }


}

获取NullPointerException

在我的主要活动中

fbuname = (TextView) mHeaderView.findViewById(R.id.user_name);
        fbuemail = (TextView) mHeaderView.findViewById(R.id.user_email);


        Bundle inBundle = getIntent().getExtras();
        if (inBundle != null){
            String Fbid = inBundle.getString("fbid");
            String Fbname = inBundle.getString("fbname");


        fbuname.setText(Fbname);
        fbuemail.setText(Fbid);
    }

在我的logcat中

E/object: {"id":"1913429202227853","gender":"female","name":"Asesha George"}

我的进口

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;

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


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

如果您有任何疑问,请发表评论

试试这个你更新的方法

 public void getProfileInformationFacebook(AccessToken accToken) {
        GraphRequest request = GraphRequest.newMeRequest(
                accToken,
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        Log.e("object", object.toString());
                        String fbId = null;
                        String fbBirthday = null;
                        String fbLocation = null;
                        String fbEmail = null;
                        String fbName = null;
                        String fbGend = null;
                        String fbPropic = null;

                        try {
                            if(object.has("id")){
                                fbId = object.getString("id");
                            }
                            else {
                                fbId = "";
                            }
                            if(object.has("email")){
                                fbEmail = object.getString("email");
                            }
                            else {
                                fbEmail = "";
                            }if(object.has("name")){
                                fbName = object.getString("name");
                            }
                            else {
                                fbName ="";
                            }if(object.has("gender")){
                                fbGend = object.getString("gender");
                            }
                            else {
                                fbGend = "";
                            }if(object.has("birthday")){
                                fbBirthday = object.getString("birthday");
                            }
                            else {
                                fbBirthday = "";
                            }if(object.has("location")){
                                 JSONObject jsonObject = object.getJSONObject("location");
                                 if(object.has("name"))
                                fbLocation = jsonObject.getString("name");
                                else
                                    fbLocation ="";
                            }
                            else {
                                fbLocation ="";
                            }

                            //fbPropic = "https://graph.facebook.com/\"+ fbId +\"/picture?type=small";

                            session.FbLogindata(fbId, fbName, fbPropic, fbLocation, fbGend, fbEmail);


                                Intent fbdata = new Intent(LoginActivity.this, MainActivity.class);
                                fbdata.putExtra("fbid",fbId);
                                fbdata.putExtra("fbname",fbName);
                                fbdata.putExtra("email",fbEmail);
                                fbdata.putExtra("gender",fbGend);
                                fbdata.putExtra("location",fbLocation);

                               // main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
                                startActivity(fbdata);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,location,gender,birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }

compile 'org.jsoup:jsoup:1.10.2'添加compile 'org.jsoup:jsoup:1.10.2'并更改import org.json.JSONObject; 而不是import com.google.gson.JsonObject; 在您登录活动,则has法正常工作

您最好从响应对象获取信息

                    String email = response.getJSONObject().getString("email");
                    String firstName = response.getJSONObject().getString("first_name");
                    String lastName = response.getJSONObject().getString("last_name");
                    String gender = response.getJSONObject().getString("gender");

或创建配置文件对象

                    Profile profile = Profile.getCurrentProfile();
                    String id = profile.getId();
                    String link = profile.getLinkUri().toString();
                    Log.d("Link",link);
                    if (Profile.getCurrentProfile()!=null)
                    {
                        Log.d("Login", "ProfilePic" + Profile.getCurrentProfile().getProfilePictureUri(200, 200));
                    }

                    Log.d("Login" + "Email", email);
                    Log.d("Login"+ "FirstName", firstName);
                    Log.d("Login" + "LastName", lastName);
                    Log.d("Login" + "Gender", gender);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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