Question

I am new to android. I want to receive and integer and string from the MainActivity.class and print it in the DisplayMessageActivity.class . From all the solutions that I found online, they said I should use setContentView(TextView); . But the problem with that is, my whole xml layout vanishes. I dont want to print just the text, i want it to be a simple textview in the second activity.

    //onClick function in the MainActivity

    public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText1 = (EditText) findViewById(R.id.name);
    EditText editText2 = (EditText) findViewById(R.id.ma);
    String message = "Hi ! " + editText1.getText().toString();
    int i = Integer.parseInt(editText2.getText().toString());
    intent.putExtra("lol",message);
    intent.putExtra("lol1", i);
    startActivity(intent);
}

Second Activity:

    public class DisplayMessageActivity extends Activity {
    TextView mTextview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    String lol = intent.getStringExtra("lol");
    int lol1 = intent.getIntExtra("lol1",1);
    mTextview = (TextView) findViewById(R.id.textView1);
    mTextview.setText(lol+"@"+lol1);
    setContentView(R.layout.activity_display_message);

   }
Was it helpful?

Solution

Just set your setContentView(R.layout.activity_display_message); at the top before calling Intent.

Change your secondactivity as below:

public class DisplayMessageActivity extends Activity {
TextView mTextview;
@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    Intent intent = getIntent();
    String lol = intent.getStringExtra("lol");
    int lol1 = intent.getIntExtra("lol1",1);
    mTextview = (TextView) findViewById(R.id.textView1);
    mTextview.setText(lol+"@"+lol1);


}

OTHER TIPS

 Because your pblm in second Activity is you made a mistake in this line 
 setContentView(R.layout.activity_display_message); 

you put this line is after setting a text in your activity.
so thats why you getting error like null pointer exception right. 
Because you must bind your xml element in your activity then only use that elements.  
setContentView(R.layout.activity_display_message); 
this line is used to bind the view in your application of this activity then only you have to  
access that element scope.

 setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String lol = intent.getStringExtra("lol");
int lol1 = intent.getIntExtra("lol1",1);
mTextview = (TextView) findViewById(R.id.textView1);
mTextview.setText(lol+"@"+lol1);

    thank you.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top