这是Android的新手,老实说,我为此感到困惑。
因此,我的MainActivity
从第二个活动CallAnActivity
接收了一些字符串。
我已经打算将字符串传递回主活动,它们显示在TextView
中。但是在输入任何信息之前,我希望此文本视图不包含任何内容并显示为空白。
但是,当第一次启动MainActivity
时,文本视图displayMessageActivity
将显示多个null
值。由于要发送三个字符串,所以它只会重复单词null三次。
MainActivity
的代码是:
//callAnActivityButton to open second activity of app
Button callAnActivityButton = findViewById(R.id.callActivityButton);
callAnActivityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick( View v ) {
Intent intent = new Intent(MainActivity.this, CallAnActivity.class);
startActivity(intent);
}
});
Intent intent = getIntent();
String emailAddress = intent.getStringExtra("emailAddress") + "\n";
String emailSubject = intent.getStringExtra("emailSubject") + "\n";
String emailBody = intent.getStringExtra("emailBody");
//TextView to display text from second activity
TextView displayMessageText = findViewById(R.id.displayMessageText);
displayMessageText.setText(emailAddress + emailSubject + emailBody);
第二个活动CallAnActivity
的代码是:
public void sendText(){
String emailAddress = mEditTextAddress.getText().toString();
String emailSubject = mEditTextSubject.getText().toString();
String emailBody = mEditTextBody.getText().toString();
Intent intent = new Intent(CallAnActivity.this, MainActivity.class);
intent.putExtra("emailAddress", emailAddress);
intent.putExtra("emailSubject", emailSubject);
intent.putExtra("emailBody", emailBody);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_an);
mEditTextAddress = findViewById(R.id.emailAddressText);
mEditTextSubject = findViewById(R.id.emailSubjectText);
mEditTextBody = findViewById(R.id.emailBodyText);
Button sendTextButton = findViewById(R.id.sendMailButton);
sendTextButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick (View v) {
sendText();
}
});
}
答案 0 :(得分:1)
只需在setText
块周围加上if
呼叫:-
if (intent.getStringExtra("emailAddress") != null) {
displayMessageText.setText(emailAddress + emailSubject + emailBody);
}
答案 1 :(得分:0)
按如下所示更改您的内容。您的getExtra语法错误
String emailAddress = intent.getExtras().getStringExtra("emailAddress") + "\n";
String emailSubject = intent.getExtras().getStringExtra("emailSubject") + "\n";
String emailBody = intent.getExtras().getStringExtra("emailBody");