Very new to Android, and I'm honestly stumped by this.
So I have my MainActivity
receiving some strings from a second activity, CallAnActivity
.
I've made an intent to pass the strings back to the main activity, and they are displayed in a TextView
. But before I enter any information, I would like for this text view to contain nothing and look blank.
But when the MainActivity
is first launched, the text view, displayMessageActivity
, is displaying multiple null
values. As there are three strings being sent, it just repeats the word null three times.
The code for the MainActivity
is:
//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);
The code for the second activity, CallAnActivity
, is:
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();
}
});
}
Just surround your setText
call with an if
block:-
if (intent.getStringExtra("emailAddress") != null) {
displayMessageText.setText(emailAddress + emailSubject + emailBody);
}