2014-11-09 75 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);