2014-11-09 38 views
0

我想获取用户名并将用户名传递给下一个活动,如下所示,但我无法在下一个活动中获得该名称。无法传递包字符串

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

我没有收到关于下一个活动和应用程序崩溃的用户名没有任何error..But当我试着用烤面包给我看用户名。

任何人都可以说我哪里错了?

+0

至于我的理解是concerened你要到下一个活动的一些数据对? – 2014-11-09 04:03:52

+0

是的正是我想要做的。 – coder 2014-11-09 04:04:44

+0

尝试使用'intent.PutExtra(“GoogleUsername”,currentUser.getDisplayName());' – 2014-11-09 04:05:47

回答

1
在第一个活动

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

在第二个活动

 Intent x = getIntent();     
    String value = x.getStringExtra("value"); 
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);