How to get Facebook user Profile (id,name,email and picture) and use in other activity by sharedpreferences [closed]

扶醉桌前 提交于 2020-01-06 06:28:29

问题


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.

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

}

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

}


回答1:


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

            }
        });

    }

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.

Try this:

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

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 )

To load the image can use Glide

Also verify your facebook login with how to implement facebook login in android using facebook sdk 4.7




回答2:


Try this code..

   /**
 * 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) {
        }
    });
}


来源:https://stackoverflow.com/questions/50509753/how-to-get-facebook-user-profile-id-name-email-and-picture-and-use-in-other-ac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!