无法传递捆绑字符串

时间:2014-11-09 03:53:07

标签: android android-intent android-activity bundle username

我正在尝试获取用户名并将用户名传递给下一个活动,如下所示,但我未能在下一次活动中获得该用户名。

public void onConnected(Bundle connectionHint) {
    // Reaching onConnected means we consider the user signed in.

    /*Toast.makeText(GoogleLogin.this, 
            currentUser.getDisplayName(), Toast.LENGTH_LONG).show();*/


    Intent i = new Intent(GoogleLogin.this,MainActivity.class);

    //Create the bundle
    Bundle bundle = new Bundle();

    // Retrieve some profile information to personalize our app for the user.
    Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
    //Add your data from getFactualResults method to bundle
    bundle.putString("Google", "Logged in using Google Account");
    bundle.putString("GoogleUsername", currentUser.getDisplayName());
    //Add the bundle to the intent
    i.putExtras(bundle);
    startActivity(i);


    // Indicate that the sign in process is complete.
    mSignInProgress = STATE_DEFAULT;
}

在我的下一个活动中,我试图获得如下所示:

    // 1. get passed intent 
    Intent googleintent = getIntent();

    // 2. get message value from intent
    String UserName = googleintent.getStringExtra("GoogleUsername");

    // 3. get bundle from intent
    Bundle googlebundle = googleintent.getExtras();

    // 4. get status value from bundle
    String googlestatus = googlebundle.getString("Google");


    if (googlestatus.equals("Logged in using Google Account")){ 

    // 5. show message on textView 
        ((TextView)findViewById(R.id.txtUser)).setText("Hello" + " " + UserName);
    } 

我没有在下次活动中收到用户名而应用程序崩溃没有任何错误。但是当我尝试使用吐司时,它会显示用户名。

谁能说我哪里出错?

2 个答案:

答案 0 :(得分:1)

第一个活动中的

        Intent nextScreen = new Intent(getApplicationContext(),
                    next_activity.class);
            nextScreen.putExtra("value", "some value");
            startActivity(nextScreen);

在第二项活动中

     Intent x = getIntent();                
    String value = x.getStringExtra("value");

答案 1 :(得分:0)

这是错误的

String UserName = googleintent.getStringExtra("GoogleUsername");

应该是userName。此外,不要忘记纠正这一行:

((TextView)findViewById(R.id.txtUser)).setText("Hello" + " " + UserName);

同样,userName需要以小写字母开头。大写单词是为类/类型保留的,而不是实例。

此外,如果您的代码仍无法正常工作,请尝试撤消以下两行。

i.putExtras(bundle);
startActivity(i);

反而写(再次,只有在你的代码在我的初步修正后没有工作时才这样做)

startActivity(i);    
i.putExtras(bundle);