0

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
    _“but don't work”_ - that is not a proper problem description. Please go read [ask]. – CBroe May 24 '18 at 14:23

2 Answers2

0

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

Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
  • I just edit my code. I try a new way to get the user profile, following the final link in your answer, but still without working. First of all, I try too with headerView but the app crash. Then, I try only in the same activity (mainactivity), but when Im doing a sucessfull login, the textview and imageview don't change. It`s like the way to get the profile by Json, don`t work... Thanks for your help!!! – Pedro Cañibano Zuñiga May 24 '18 at 19:09
  • @PedroCañibanoZuñiga Try updated answer. Hope it works! – Vidhi Dave May 25 '18 at 04:09
  • IT WORKS!!! Thankyou! Now I just try to transfer to the header view into the next Activity! Thankyou again! – Pedro Cañibano Zuñiga May 26 '18 at 10:08
  • Happy to help :) if this answers had solved your problem then you can mark this as correct by clicking on right for future visitors... – Vidhi Dave May 26 '18 at 15:47
  • and for header view make sure you are first finding reference of navigation view and then adding this code..also in this answer mentioned all ids are from the layout of your header layout make sure all ids and references are correct.. otherwise it will cause NPE ..if still any errors then you can post errors in comment – Vidhi Dave May 26 '18 at 15:51
  • hello again! I declarate a variable View headerView. Then, I copy your code NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); headerView = navigationView.getHeaderView(0); tvUsername = (Textview) headerView.findViewById(R.id.username_textview_id); And link to my (R.id.textviews) but the app crash and show me the next error: – Pedro Cañibano Zuñiga May 28 '18 at 17:12
  • Unable to start activity ComponentInfo{com.pjcdev.loginrrss/com.pjcdev.loginrrss.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.NavigationView.getHeaderView(int)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.design.widget.NavigationView.getHeaderView(int)' on a null object reference – Pedro Cañibano Zuñiga May 28 '18 at 17:17
  • Try https://stackoverflow.com/a/33194816/8089770 – Vidhi Dave May 29 '18 at 02:45
  • @PedroCañibanoZuñiga as you can see this code https://stackoverflow.com/a/31825141/8089770 this will be your navigation drawer code.. and you need to define this two lline : `app:headerLayout="@layout/drawer_header" app:menu="@menu/menu_drawer"` make sure this is correct layout and correct ids – Vidhi Dave May 29 '18 at 03:56
  • Thanyou a lot! My app works! I edited the title and the code to help other people but I don`t know How I change the "On hold"... – Pedro Cañibano Zuñiga May 29 '18 at 18:57
  • @PedroCañibanoZuñiga :D :D you can't remove that "On hold" it is there because your question is off topic for this site.. – Vidhi Dave May 30 '18 at 04:00
0

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