在我的应用程序的第二个 activity 中显示 "Happy birthday null"

Displaying "Happy birthday null" in the second activity of my app

主要Activity `public class MainActivity extends AppCompatActivity {

private Object Context;
public static final String MSG="com.mp.exampleapp.ORDER";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

public void createBirthdayCard(View view) {
    EditText text = (EditText)findViewById(R.id.nameInput);
    String str = text.getText().toString();

    Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
    getIntent().putExtra(MSG,str);
    startActivity(new Intent(this,birthdaygreeting.class)) ;

    ImageView image=(ImageView) findViewById(R.id.cake);
    image.setImageResource(R.drawable.wish);
}

`第二个activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_birthdaygreeting);


     Intent intent = getIntent();
    String msg = "HAPPY BIRTHDAY "+intent.getStringExtra(MainActivity.MSG);
    // receive the value by getStringExtra() method
    // and key must be same which is send by first activity
    TextView textView= (TextView)findViewById(R.id.textView2);
   textView.setText(msg);

}

在 运行 这个程序之后 - 单击按钮后 - 显示的消息是“HAPPY BIRTHDAY null”。不知道怎么回事。

创建一个意图,然后像下面的代码一样在其中添加您的数据。

public void createBirthdayCard(View view) {
    EditText text = (EditText)findViewById(R.id.nameInput);
    String str = text.getText().toString();

    Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
    Intent intent = new Intent(this,birthdaygreeting.class);
    intent.putExtra(MSG,str);
    startActivity(intent) ;

    ImageView image=(ImageView) findViewById(R.id.cake);
    image.setImageResource(R.drawable.wish);
}

怎么了?


你传递 put extra 的地方在 getIntent()。这意味着你在之前的 activity.In 这种情况下给出了 intent extra,当你返回时,然后得到那个额外的,你会得到 it.But 而不是下一个 activity。现在你得到空值,因为那个 activity.So 的额外内容不存在,它变成空值。

如何解决?


而不是使用这个

public void createBirthdayCard(View view) {
    EditText text = (EditText)findViewById(R.id.nameInput);
    String str = text.getText().toString();
    Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
    getIntent().putExtra(MSG,str);
    startActivity(new Intent(this,birthdaygreeting.class)) ;

    ImageView image=(ImageView) findViewById(R.id.cake);
    image.setImageResource(R.drawable.wish);
}

使用这个

public void createBirthdayCard(View view) {
    EditText text = (EditText)findViewById(R.id.nameInput);
    String str = text.getText().toString();
    Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
    startActivity(new Intent(this,birthdaygreeting.class).putExtra(MSG,str)) ;

    ImageView image=(ImageView) findViewById(R.id.cake);
    image.setImageResource(R.drawable.wish);
}

我怎么知道它会对我有帮助?


它会对你有所帮助,因为在你给出的新意图中,那里给出了额外的东西。因此,正在发送该值。