2016-02-17 57 views
1

我有兩個活動。在第一個中,我要求用戶輸入他們的名字,我想在第二個活動中通過這個名字。 我的第一個活動代碼:顯示一個editText

name=(EditText)findViewById(R.id.editText); 
String str = name.getText().toString(); 

Intent intent = new Intent(WelcomeActivity.this, ResultActivity.class); 
intent.putExtra("str", str); 

和我的第二個活動代碼:

Intent intent = getIntent(); 
String name = intent.getExtras().getString("str"); 
TextView t = (TextView) findViewById(R.id.textResult); 
t.setText(name); 

的問題是,沒有顯示在我的第二次活動。

+0

你是否開始與該意圖或與其他? –

+0

@Victoria你確定R.id.textResult是正確的ID嗎? – IgorB

回答

0

在您的第一項活動把你額外在你的意圖後,你必須開始第二項活動是這樣的:

Intent intent = new Intent(WelcomeActivity.this, ResultActivity.class); 
intent.putExtra("str", str); 
startActivityForResult(intent, 1); 

我模擬你的代碼,它工作得很好。

+0

但我有我的WelcomeActivity和我的ResultActivity之間的其他活動。我無法在「歡迎」活動中放入開始活動,該應用程序崩潰。這個想法是在應用程序開始時獲取用戶的姓名,並在遊戲結束時顯示他的姓名和結果。 – Vitoria

+0

然後你必須在整個活動中進行價值。 PutExtra在調用startActivityForResult之前的活動之間的每個意圖 –

2

我沒有看到startActivity()任何地方......所以我把你的代碼應該如何和你實現它。

name=(EditText)findViewById(R.id.editText); 
String str = name.getText().toString(); 

Intent intent = new Intent(WelcomeActivity.this, ResultActivity.class); 
intent.putExtra("str", str); 
startActivity(intent); 

然後在你的ResultActivity你這樣做:

TextView t = (TextView) findViewById(R.id.textResult); 
Intent intent = getIntent(); 
Bundle b = intent.getExtras(); 
if(b!=null){ 
    String name =(String) b.get("str"); 
    t.setText(name); 
} 

好了,你可以使用SharedPreferences做到這一點:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 
SharedPreferences.Editor editor = sharedPreferences.edit(); 
editor.putString("NamePlayer", name); //Here you save the text of your edittext 
editor.commit(); 

然後在你的結果的活動做到這一點:

SharedPreferencessharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext)); 
String name =sharedPreferences.getString("NamePlayer", "NoName")); 
+0

但我有我的WelcomeActivity和我的ResultActivity之間的其他活動。我無法在「歡迎」活動中放入開始活動,該應用程序崩潰。這個想法是在應用程序開始時獲取用戶的姓名,並在遊戲結束時顯示他的姓名和結果。 – Vitoria

+0

我編輯了我的答案,對不起我在手機上,所以我不能讓它看起來好幾分鐘,我會編輯它,但應該工作。 –

+0

@Vitoria它適合你嗎? –

1

在第二次活動中使用下面的代碼,那麼你的應用程序將完美運行:

Intent intent = getIntent(); 
    String name = intent.getStringExtra("str"); 
    TextView t = (TextView) findViewById(R.id.tv_text); 
    t.setText(name); 
+0

但我有我的WelcomeActivity和我的ResultActivity之間的其他活動。我無法在「歡迎」活動中放入開始活動,該應用程序崩潰。這個想法是在應用程序開始時獲取用戶的姓名,並在遊戲結束時顯示他的姓名和結果。 – Vitoria