将字符串从片段传递到活动

时间:2014-05-19 18:16:28

标签: android android-fragments

在SelectionFragment中, user.getId()获取当前登录用户的Facebook ID。

MainActivity.java 中,我有意开始另一项活动。

我试图找出如何在 MainActivity.java 中的意图中使用来自 user.getId()的数据:

Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
i.putExtra("EXTRA_FACEBOOK_ID","FB_ID_VALUE_GOES_HERE");
startActivity(i);

我已经尝试了很多关于堆栈溢出的事情,到目前为止它们都没有工作过。任何帮助表示赞赏!!

SelectionFragment的相关代码:

收集Facebook ID:

private void makeMeRequest(final Session session) {
    // Make an API call to get user data and define a 
    // new 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 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());

                 // Set the Textview's text to the user's name.
                    userIdView.setText(user.getId());

                }
            }
            if (response.getError() != null) {
                // Handle errors, will do so later.
            }
        }
    });
    request.executeAsync();
} 

-

private TextView userIdView;

-

userIdView = (TextView) view.findViewById(R.id.selection_user_id);

-

userIdView.setText(user.getId());

MainActivity的相关代码:

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;

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

    FragmentManager fm = getSupportFragmentManager();
    fragments[SPLASH] = fm.findFragmentById(R.id.splashFragment);
    fragments[SELECTION] = fm.findFragmentById(R.id.selectionFragment);
    fragments[SETTINGS] = fm.findFragmentById(R.id.userSettingsFragment);

}

修改

在查看google文档后,我将以下内容添加到我的MainActivity中:

SelectionFragment fragment = (SelectionFragment) getSupportFragmentManager().findFragmentById(R.id.selectionFragment);

我的理解是,这允许我连接到片段,但我无法弄清楚如何从片段中获取facebook id。我试过这个,但应用程序崩溃了。我在这一行得到一个空指针异常:

String fbID = fragment.userIdView.getText().toString();

1 个答案:

答案 0 :(得分:0)

如果您想将Fragment中的数据传回其持有Activity,您可以使用Otto等事件总线。然后,您可以从定义为接收事件的Activity方法开始新的@Subscribe。我更喜欢使用事件总线而不是接口方法,因为组件真的会松散耦合。