2

I facing an issue with my android project. I already have a fragment with a facebook button for login, and it works well. It displays a greeting message and user profile thumbnail. I have a second activity that contains a navigation drawer, with different items.

I want to retrieve user's informations (like profile thumbnail, name, email), to display inside my drawer header.

I tried with intent, and with Picasso, but no one works (or maybe i'm doing something wrong).

Here is my drawer activity :

public class DrawerActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private ImageView profilePicture;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);

    ImageView profilePicture = findViewById(R.id.profilePicture);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

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

    if (savedInstanceState == null) {
        showFragment(new WelcomeActivity());
    }
}

@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 onNavigationItemSelected(@NonNull MenuItem item) {

    int id = item.getItemId();

    switch (id) {
        case R.id.nav_accueil:
            showFragment(new WelcomeActivity());
            break;
        case R.id.nav_tools:
            showFragment(new LifeCounterActivity());
            break;
        case R.id.nav_videos:
            showFragment(new ChannelActivity());
            break;
        case R.id.nav_connexion:
            showFragment(new LoginActivity());
            break;
        default:
            return false;
    }

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

private void showFragment(Fragment fragment) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.content_main, fragment)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
            .commit();
}
}

Here is my facebook fragment :

public class FacebookFragment extends Fragment{

private LoginButton loginButton;
private Button getUserInterests;
private boolean postingEnabled = false;

private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY =
        "com.example.hellofacebook:PendingAction";

private Button postStatusUpdateButton;
private Button postPhotoButton;
private ImageView profilePicImageView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private boolean canPresentShareDialog;

private boolean canPresentShareDialogWithPhotos;
private CallbackManager callbackManager;
private ProfileTracker profileTracker;
private ShareDialog shareDialog;
private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
    @Override
    public void onCancel() {
        Log.d("FacebookFragment", "Canceled");
    }

    @Override
    public void onError(FacebookException error) {
        Log.d("FacebookFragment", String.format("Error: %s", error.toString()));
        String title = getString(R.string.error);
        String alertMessage = error.getMessage();
        showResult(title, alertMessage);
    }

    @Override
    public void onSuccess(Sharer.Result result) {
        Log.d("FacebookFragment", "Success!");
        if (result.getPostId() != null) {
            String title = getString(R.string.success);
            String id = result.getPostId();
        }
    }

    private void showResult(String title, String alertMessage) {
        new AlertDialog.Builder(getActivity())
                .setTitle(title)
                .setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null)
                .show();
    }
};

private enum PendingAction {
    NONE,
    POST_PHOTO,
    POST_STATUS_UPDATE
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getActivity());
    // Other app specific specialization
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_facebook, parent, false);
    loginButton = (LoginButton) v.findViewById(R.id.loginButton);
    // If using in a fragment
    loginButton.setFragment(this);
    callbackManager = CallbackManager.Factory.create();
    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Toast toast = Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_SHORT);
            postingEnabled = true;

            toast.show();
            //handlePendingAction();
            updateUI();

        }

        @Override
        public void onCancel() {
            // App code
            if (pendingAction != PendingAction.NONE) {
                showAlert();
                pendingAction = PendingAction.NONE;
            }
            updateUI();
        }

        @Override
        public void onError(FacebookException exception) {
            if (pendingAction != PendingAction.NONE
                    && exception instanceof FacebookAuthorizationException) {
                showAlert();
                pendingAction = PendingAction.NONE;
            }
            updateUI();

        }

        private void showAlert() {
            new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null)
                    .show();
        }

    });
    shareDialog = new ShareDialog(this);
    shareDialog.registerCallback(
            callbackManager,
            shareCallback);

    if (savedInstanceState != null) {
        String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
        pendingAction = PendingAction.valueOf(name);
    }


    profileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
            updateUI();
            //handlePendingAction();
        }
    };


    profilePicImageView = (ImageView) v.findViewById(R.id.profilePicture);
    greeting = (TextView) v.findViewById(R.id.greeting);

    // Can we present the share dialog for regular links?
    canPresentShareDialog = ShareDialog.canShow(
            ShareLinkContent.class);

    // Can we present the share dialog for photos?
    canPresentShareDialogWithPhotos = ShareDialog.canShow(
            SharePhotoContent.class);


    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));

        }
    });

    return v;
}

@Override
public void onResume() {
    super.onResume();

    // Call the 'activateApp' method to log an app event for use in analytics and advertising
    // reporting.  Do so in the onResume methods of the primary Activities that an app may be
    // launched into.
    AppEventsLogger.activateApp(getActivity());

    updateUI();
}

@Override
public void onPause() {
    super.onPause();

    // Call the 'deactivateApp' method to log an app event for use in analytics and advertising
    // reporting.  Do so in the onPause methods of the primary Activities that an app may be
    // launched into.
    AppEventsLogger.deactivateApp(getActivity());
}

@Override
public void onDestroy() {
    super.onDestroy();
    profileTracker.stopTracking();
}

private void updateUI() {
    boolean enableButtons = AccessToken.getCurrentAccessToken() != null;

    //postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
    //postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos);

    Profile profile = Profile.getCurrentProfile();
    if (enableButtons && profile != null) {
        String profileUserID = profile.getId();
        new LoadProfileImage(profilePicImageView).execute(profile.getProfilePictureUri(200, 200).toString());
        greeting.setText(getString(R.string.hello_user, profile.getFirstName()));
    } else {
        Bitmap icon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_default);
        profilePicImageView.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(), icon, 200, 200, 200, false, false, false, false));
        greeting.setText(null);
    }
}


@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}

/**
 * Background Async task to load user profile picture from url
 * */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public LoadProfileImage(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... uri) {
        String url = uri[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(url).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {

        if (result != null) {

            Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true);
            bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false));

        }
    }
}
}

And, if needed, the LoginActivty, which is launched when we click on "connexion" in the drawer :

public class LoginActivity extends Fragment {

public LoginActivity() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    final View loginFragment = inflater.inflate(R.layout.activity_login, container, false);

    FragmentManager fm = getFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);

    if (fragment == null) {
        fragment = new FacebookFragment();
        fm.beginTransaction()
                .add(R.id.fragment_container, fragment)
                .commit();
    } else {
        fragment = new FacebookFragment();
        fm.beginTransaction()
                .add(R.id.fragment_container, fragment)
                .commit();

    }

    return loginFragment;
}
}

Any help would be greatly appreciated :).

I can post more code if needed.

Thank's

Neandril
  • 122
  • 9

2 Answers2

2

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);
Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
  • Thank's for ansewer, but It doesn't really match what i wonder... How can you retrieve the facebook profile from my fragment, to display it in my drawer activity ? – Neandril May 30 '18 at 13:08
  • Refer my answer https://stackoverflow.com/a/50509851/8089770 let me know still any errors – Vidhi Dave May 31 '18 at 03:53
  • Just get data from facebook as activity and for fragment just use context instead this. Add this data to shared preferences as you will need this credentials through your application. and get from shared preferences in drawer activity and show this way.. At logout clear all shared preferences and call facebook logout as well – Vidhi Dave May 31 '18 at 03:56
  • 1
    Thank's, i will check this out, and I let you know. – Neandril May 31 '18 at 12:41
0
private void setNavigationHeaderView() {
        try {
            txtHeaderUserName.setText(SP.getPreferences(mContext, SP.USER_FIRST_NAME));
            txtHeaderUserEmail.setText(SP.getPreferences(mContext, SP.USER_EMAIL));
            txtHeaderUserMobile.setText(SP.getPreferences(mContext, SP.USER_MOBILE))); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Mohsinali
  • 543
  • 7
  • 14