首页 > 解决方案 > 检索 Facebook 信息并将其放在导航抽屉标题中

问题描述

我的 android 项目遇到问题。我已经有一个带有 facebook 登录按钮的片段,并且效果很好。它显示问候消息和用户配置文件缩略图。我有一个包含导航抽屉的第二个活动,其中包含不同的项目。

我想检索用户的信息(如个人资料缩略图、姓名、电子邮件),以显示在我的抽屉标题中。

我有意识地尝试了毕加索,但没有人工作(或者我做错了什么)。

这是我的抽屉活动:

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

这是我的 Facebook 片段:

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

        }
    }
}
}

并且,如果需要,当我们单击抽屉中的“连接”时启动 LoginActivty:

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

任何帮助将不胜感激 :)。

如果需要,我可以发布更多代码。

谢谢

标签: androidfacebooknavigation-drawer

解决方案


尝试这个:

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

推荐阅读