如何获取Facebook用户个人资料(ID,名称,电子邮件和图片)并通过sharedpreferences在其他活动中使用 [英] How to get Facebook user Profile (id,name,email and picture) and use in other activity by sharedpreferences

查看:187
本文介绍了如何获取Facebook用户个人资料(ID,名称,电子邮件和图片)并通过sharedpreferences在其他活动中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an app that uses Facebook for login and then, go to another activity.

首先,我检查正确的登录名并可以正常工作.

First of all, I check the correct login and works fine.

然后,我将配置文件的日期保存在字符串数组列表中,然后保存在sharedpreferences中.

Then, I saved the dates of my profile on a Arraylist of string and then, save on sharedpreferences.

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

This is the code of my First Activity (login activity)

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);
}

}

这是下一个活动的代码.它是一个导航抽屉活动. 首先,我创建一个视图并分配一个headerview,然后将sharedpreferences的日期加载到string的arraylist上. 最后,在左侧菜单中分配一个textviews和imageview

And this is the code of the next Activity.Its a Navigation Drawer Activity. First, I create a view and asign a headerview.Then, load the dates of sharedpreferences on arraylist of string. Finally, asign to a textviews and imageview on the left menu

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);
}

}

推荐答案

Facebook登录:

Facebook login :

 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方法:

And onActivityResult method :

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

        callbackManager.onActivityResult(requestCode, resultCode, data);

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

要将数据从一项活动转移到另一项活动,可以使用共享的首选项.由于此登录凭据将需要通过应用程序.因此您可以将它们存储在共享的首选项中.

To transfer data from one activity to other can use Shared preferences. As this login credentials will be needed through the application. so you can store them in 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的引用. (参考号:图像登录注册按钮)

This way you will get the references of imageview and textview in the left menu on top (in header view). ( Ref : image login register buttons )

要加载图像,可以使用 Glide

To load the image can use Glide

还使用如何使用android sdk 4.7在android中实现facebook登录来验证您的facebook登录

这篇关于如何获取Facebook用户个人资料(ID,名称,电子邮件和图片)并通过sharedpreferences在其他活动中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆