如何防止null在TextView中显示?

时间:2018-11-05 01:40:59

标签: java android android-intent null textview

这是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();
        }
    });
}

2 个答案:

答案 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");