Reputation: 9299
I'm learning how to use the intent to open a new activity and also pass a message, but when the new activity start, it needs to close down! What have I done wrong? Help is preciated! Thanks!
package test.intent;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn1;
String message;
public final static String EXTRA_MESSAGE = "test.intent.MESSAGE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
message = "Message via an intent";
Intent intent = new Intent(MainActivity.this, Activity1.class);
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
}
}
The activity that recieve the message:
package test.intent;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class Activity1 extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TextView display = (TextView) findViewById(R.id.txtv1);
setContentView(R.layout.activity1);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
display.setText(message);
}
}
Upvotes: 0
Views: 97
Reputation: 20155
Edit: You've the null pointer exception because you haven't set contentView before getting the TextView so it returns null
setContentView(R.layout.activity1)
TextView display = (TextView) findViewById(R.id.txtv1);
Instead of this intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
use
intent.getExtras().getString(MainActivity.EXTRA_MESSAGE);
Upvotes: 1