如何获取Facebook用户个人资料(ID,姓名,电子邮件和图片)以及通过共享偏好在其他活动中使用

时间:2018-05-24 12:41:09

标签: android sharedpreferences facebook-login

我有一个使用Facebook登录的应用程序,然后转到另一个活动。

首先,我检查正确的登录并正常工作。

然后,我将我的个人资料的日期保存在字符串的Arraylist上,然后保存在共享偏好中。

这是我的第一个活动(登录活动)的代码

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
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.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

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

import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.util.Arrays;



  public class MainActivity extends AppCompatActivity {

  LoginButton loginButtonfb;
  CallbackManager callbackManager;
  List<String> profile=new ArrayList<>();;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);

    LoginManager.getInstance().logOut();
    loginButtonfb=(LoginButton)findViewById(R.id.login_button);

    // initiate callbackmanager
    callbackManager = CallbackManager.Factory.create();

    //get permision to get public profile,email,id,and friends
    loginButtonfb.setReadPermissions(Arrays.asList("public_profile","user_friends","email"));

    //register response of button
    loginButtonfb.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {

                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {

                    Log.d("res", object.toString());
                    Log.d("res_obj", response.toString());
                    try {

                        String id = object.getString("id");
                        try {
                            URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?type=large");
                            Log.i("profile_pic", profile_pic + "");

                            String f_name = object.getString("first_name");
                            String l_name = object.getString("last_name");
                            String name = f_name + " " + l_name;

                            String email = object.getString("email");
                            String image = profile_pic.toString();


                            Log.d("data", email + name + image+id);
                            String type = "facebook";

                            //Save the data into the arraylist
                            profile.add(id);
                            profile.add(name);
                            profile.add(email);
                            profile.add(image);

                            //save into sharedpreferences
                            StringBuilder stringBuilder = new StringBuilder();

                            for (String s:profile){
                                stringBuilder.append(s);
                                stringBuilder.append(",");
                            }

                            SharedPreferences sharpref = getSharedPreferences("ProfileList",0);
                            SharedPreferences.Editor editor = sharpref.edit();
                            editor.putString("ProfileList", stringBuilder.toString());
                            editor.commit();


                            if (email == null) {

                            }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }


                    } catch (JSONException e) {

                        e.printStackTrace();

                    }

                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, first_name, last_name, email,gender");
            request.setParameters(parameters);
            request.executeAsync();
        goIndexScreen();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(),"Has cancelado el inicio de sesión",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(FacebookException error) {
            Toast.makeText(getApplicationContext(),"Error al conectar con Facebook",Toast.LENGTH_LONG).show();
        }
    });
}


//method necesary to correct callback
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}

//method to go to next activity
private void goIndexScreen() {
    Intent intent=new Intent(this,Index.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

}

这是下一个Activity的代码。它是一个导航抽屉活动。 首先,我创建一个视图并对标题视图进行设置。然后,在字符串的arraylist上加载共享偏好的日期。 最后,在左侧菜单中指向textviews和imageview

public class Index extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

   private ImageView ivprofile;
   private TextView tvname;
   private TextView tvemail;
   private TextView tvidnumber;
   private String picprofile;
   private String name;
   private String idnumber;
   private String email;
   final List<String> profile = new ArrayList<String>();
   private View headerview;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_index);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

   //create a headerview to conect to header of left menu
    headerview=navigationView.getHeaderView(0);

    ivprofile=(ImageView)headerview.findViewById(R.id.imageProfile);
    tvname=(TextView)headerview.findViewById(R.id.fullName);
    tvemail=(TextView)headerview.findViewById(R.id.email);
    tvidnumber=(TextView) headerview.findViewById(R.id.idNumber);


    //check if session is already connected
    if(AccessToken.getCurrentAccessToken()==null){
        goLoginScreen();
    }

    //Load file saved by sharedpreferences into a new arraylist
    final SharedPreferences sharpref = getSharedPreferences("ProfileList",0);
    String Items = sharpref.getString("ProfileList","");
    String [] listItems = Items.split(",");
    for (int i=0;i<listItems.length;i++){
        profile.add(listItems[i]);
    }

    //get the profile

    idnumber=profile.get(0);
    name=profile.get(1);
    email=profile.get(2);
    picprofile=profile.get(3);

   tvname.setText(name);
   tvidnumber.setText(idnumber);
   tvemail.setText(email);
   Glide.with(this).load(picprofile).into(ivprofile);


Log.d("ArrayPerfil", name+email+idnumber+picprofile);


}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.index, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }else if (id == R.id.nav_logout) {
        LoginManager.getInstance().logOut();
        goLoginScreen();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

private void goLoginScreen() {
    Intent intent=new Intent(this,MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

}

2 个答案:

答案 0 :(得分:0)

Facebook登录:

 public void setFacebookConnection() {

        LoginManager.getInstance().logOut();


        List<String> permissionNeeds = Arrays.asList("public_profile, email");

        LoginManager.getInstance().logInWithReadPermissions(mActivity, permissionNeeds);

        FacebookSdk.sdkInitialize(mActivity);

        callbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {


            @Override
            public void onSuccess(LoginResult loginResult) {

                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {

                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {

                        Log.d("res", object.toString());
                        Log.d("res_obj", response.toString());
                        try {

                            String id = object.getString("id");
                            try {
                                URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=150");
                                Log.i("profile_pic", profile_pic + "");

                                String f_name = object.getString("first_name");
                                String l_name = object.getString("last_name");
                                String name = f_name + " " + l_name;
                                String email = object.getString("email");
                                String image = profile_pic.toString();


                                Log.d("data", email + name + image);
                                String type = "facebook";

                                if (email == null) {

                                }
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }


                        } catch (JSONException e) {

                            e.printStackTrace();

                        }

                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, first_name, last_name, email,gender");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {

                Log.d("fb_exception", "cancel by user");
            }

            @Override
            public void onError(FacebookException exception) {

                Log.d("fb_exception", exception.toString());

            }
        });

    }

onActivityResult方法:

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

        callbackManager.onActivityResult(requestCode, resultCode, data);

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

要将数据从一个活动传输到另一个活动,可以使用Shared preferences。因为应用程序需要此登录凭据。所以你可以将它们存储在共享的首选项中。

试试这个:

  NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

     headerView = navigationView.getHeaderView(0);

     tvUsername = (Textview) headerView.findViewById(R.id.username_textview_id);

     profile_image = (Textview) headerView.findViewById(R.id.profile_image);

这样,您将在左侧菜单中获得imageview和textview的引用(在标题视图中)。 (参考:image登录注册按钮)

要加载图片,可以使用Glide

同时使用how to implement facebook login in android using facebook sdk 4.7

验证您的Facebook登录信息

答案 1 :(得分:0)

试试这段代码..

   /**
 * this method used to user login with facebook.
 */
private void loginWithFacebook() {

    mLoginFbButton.setReadPermissions("public_profile", "email");
    mLoginFbButton.setFragment(this);
    mLoginFbButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            if (Profile.getCurrentProfile() == null) {
                mProfileTracker = new ProfileTracker() {
                    @Override
                    protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                 // here getting fb user profile object.       
                }
                };
            } else {
                registerUsingFaceBook(Profile.getCurrentProfile());
            }

        }

        @Override
        public void onCancel() {

         }

        @Override
        public void onError(FacebookException exception) {
        }
    });
}