0

我正在试用面向 Android 开发人员的 Facebook 教程,但在第2 步遇到问题 - 个性化

我试图通过打字而不是复制和粘贴教程中的代码来学习,所以我可能打错了一些东西。我似乎找不到它。

我的 profilePicture 和用户名没有显示,因为即使我已授权该应用程序,用户似乎也为空。所以我的选择屏幕显示,但它显示的是一个空的用户配置文件。即使在上一个教程中,当我创建一个 LoginFragment 时,我的用户也没有显示在那里。有什么我做错了吗?

以下是我的完整代码减去导入语句和类声明

private static final int SPLASH = 0;
private static final int SELECTION = 1;
private static final int SETTINGS = 2;
private static final int FRAGMENT_COUNT = SETTINGS + 1;

private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
private static final String FRAGMENT_PREFIX = "fragment";

private static final String TAG = "MyFirstApp_FacebookMain.java";
private boolean isResumed = false;
private boolean restoredFragment = false;

private MenuItem settings;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_facebook_main);

    for(int i=0; i < fragments.length; i++) {
        restoreFragment(savedInstanceState, i);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    FragmentManager manager = getSupportFragmentManager();

    // Since we are only adding one fragment at a time, we can only save one.
    Fragment f = manager.findFragmentById(R.id.body_frame);
    for(int i=0; i < fragments.length; i++) {
        if(fragments[i] == f) {
            manager.putFragment(outState, getBundleKey(i), fragments[i]);
        }
    }
}

@Override
public void onResume() {
    super.onResume();
    isResumed = true;
}

@Override
public void onPause() {
    super.onPause();
    isResumed = false;
}

@Override
protected void onSessionStateChange(SessionState state, Exception exception) {
    if(isResumed) {
        FragmentManager manager = getSupportFragmentManager();
        int backStackSize = manager.getBackStackEntryCount();
        for(int i=0; i < backStackSize; i++) {
            manager.popBackStack();
        }
        if(state.isOpened()) {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.body_frame, fragments[SELECTION]).commit();
        } else if (state.isClosed()) {
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.body_frame, fragments[SPLASH]).commit();
        }
    }
}

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    Session session = Session.getActiveSession();
    if (session == null || session.getState().isClosed()) {
        session = new Session(this);
        Session.setActiveSession(session);
    }

    FragmentManager manager = getSupportFragmentManager();

    if (restoredFragment) {
        return;
    }

    // If we already have a valid token, then we can just open the session silently,
    // otherwise present the splash screen and ask the user to login.
    if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        // no need to add any fragments here since it will be 
        // handled in onSessionStateChange
        session.openForRead(this);
    } else if (session.isOpened()) {
        // if the session is already open, try to show the selection fragment
        Fragment fragment = manager.findFragmentById(R.id.body_frame);
        if (!(fragment instanceof SelectionFragment)) {
            manager.beginTransaction().replace(R.id.body_frame, 
                    fragments[SELECTION]).commit();
        }
    } else {
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.body_frame, 
              fragments[SPLASH]).commit();
    }
}

private String getBundleKey(int index) {
    return FRAGMENT_PREFIX + Integer.toString(index);
}

private void restoreFragment(Bundle savedInstanceState, int fragmentIndex) {
    Fragment fragment = null;
    if(savedInstanceState != null) {
        FragmentManager manager = getSupportFragmentManager();
        fragment = manager.getFragment(savedInstanceState, getBundleKey(fragmentIndex));
    }
    if(fragment != null) {
        fragments[fragmentIndex] = fragment;
        restoredFragment = true;
    } else {
        switch(fragmentIndex) {
            case SPLASH:
                fragments[SPLASH] = new SplashFragment();
                break;
            case SELECTION:
                fragments[SELECTION] = new SelectionFragment();
                break;
            case SETTINGS:
                fragments[SETTINGS] = new LoginFragment();
                break;
            default:
                Log.w(TAG, "invalid fragment index");
                break;
        }
    }
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    FragmentManager manager = getSupportFragmentManager();
    Fragment currentFragment = manager.findFragmentById(R.id.body_frame);
    // only add the menu when the selection fragment is showing
    if (currentFragment == fragments[SELECTION]) {
        if (menu.size() == 0) {
            settings = menu.add(R.string.settings);
        }
        return true;
    } else {
        menu.clear();
        settings = null;
    }
    return false;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.equals(settings)) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.body_frame, fragments[SETTINGS]).addToBackStack(null).commit();
        return true;
    }
    return false;
}

在 SelectionFragment.java 中

public class SelectionFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView userNameView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.selection, container, false);

    // Find the user's profile picture custom view
    profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
    profilePictureView.setCropped(true);

    // Find the user's name view
    userNameView = (TextView) view.findViewById(R.id.selection_user_name);

    // Get the active session
    final Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
        // if the session is open, make an API call to get user data
        // and define a callback to handle the response
        Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {

            @Override
            public void onCompleted(GraphUser user, Response response) {
                // if the response is successful
                if (session == Session.getActiveSession()) {
                    if (user != null) {
                        // set the userid for the ProfilePictureView
                        // view that in turn displays the profile picture
                        profilePictureView.setProfileId(user.getId());
                        // set the textview to the user's name
                        userNameView.setText(user.getName());
                    }
                }
            }
        });
        Request.executeBatchAsync(request);
    }
    return view;
}
}

最后是 SplashFragment.java

public class SplashFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.splash, container, false);
    return view;
}
}
4

4 回答 4

5

user1258600,我有同样的问题,我解决了!!

您的代码没有任何问题...

您只是缺少 Android 清单中的 INTERNET 权限!

尝试添加

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

到你的 Android 清单,你会没事的!!

为了弄清楚这一点,我进入了发现用户为空的语句,并打印了错误,这表明我将 INTERNET 权限添加到我的 android 清单中。

@Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
    if (session == Session.getActiveSession()) {
    System.out.println("user: " + user);
                if (user != null) {
                    // Set the id for the ProfilePictureView
                    // view that in turn displays the profile picture.
                    profilePictureView.setProfileId(user.getId());
                    // Set the Textview's text to the user's name.
                    userNameView.setText(user.getName());
                }
            }
            if (response.getError() != null) {
                // Handle errors!!
                System.out.println("response error: " + response.getError());
            }
        }
于 2013-09-15T15:45:38.543 回答
1

使用此代码登录 facebook

mFacebook = new Facebook(APP_ID);
SessionStore.restore(mFacebook, getApplicationContext());
mAsyncRunner = new AsyncFacebookRunner(mFacebook);

这使用此功能获取个人资料图片注释根据您的需要修改它:)

void update_user_image() {
    Bundle params = new Bundle();
    params.putString("fields", "id,picture");
    mAsyncRunner.request("me", params, new AsyncRequestListener(this) {

        @Override
        public void onComplete(JSONObject obj, Object state) {
            try {
                String Image_url = obj.optString("picture");
                if (Image_url.contains("_q.jpg"))
                    Image_url = Image_url.replace("_q.jpg", "_n.jpg");
                if (Image_url.contains("_s.jpg"))
                    Image_url = Image_url.replace("_s.jpg", "_n.jpg");
                if (userImage != null && userImage.getImageUrl() != null)
                    if (!userImage.getImageUrl().equals(Image_url)) {
                        Editor editor = mActivity.getSharedPreferences("userInformation", Context.MODE_PRIVATE).edit();
                        editor.putString("ImageURL", Image_url);
                        editor.commit();
                        final String latest_image_url = Image_url;
                        main.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                userImage.setImageUrl(latest_image_url);                                
                                userImage.loadImage();

                            }
                        });
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
于 2012-11-30T17:58:05.200 回答
1

出于绝望,我再次重新启动了整个项目,它现在可以工作了。我想我永远不会发现出了什么问题。:(

于 2012-12-17T10:07:37.197 回答
1

作为 satoukum 帖子的后续内容,请确保将 INTERNET 权限标签放在 <application>标签之外。对于经验丰富的 Android 开发人员来说,这可能是轻而易举的事,但 Facebook 文档并未明确说明此标签不应驻留在<application>标签内

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.blah.blah" >

 <uses-permission android:name="android.permission.INTERNET"/>

<application>
</application>

</manifest>
于 2014-11-04T01:20:16.903 回答