制定意图,活动的一部分?

时间:2014-03-31 05:26:23

标签: java android string android-intent integer

我是android新手。我想从MainActivity.class接收整数和字符串,并将其打印在DisplayMessageActivity.class中。从我在网上找到的所有解决方案中,他们说我应该使用setContentView(TextView);。 但问题是,我的整个xml布局消失了。 我不想只打印文本,我希望它在第二个活动中是一个简单的文本视图。

    //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);
}

第二项活动:

    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);

   }

2 个答案:

答案 0 :(得分:1)

在调用setContentView(R.layout.activity_display_message);之前,只需将Intent设置在顶部即可。

更改您的第二个活动,如下所示:

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);


}

答案 1 :(得分:0)

 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.