无法将变量值分配给来自 extra.getString() 的字符串;

Cannot assign variable value to a string from extra.getString();

android 的新手,我目前正在尝试将 String 值从一个 Activity 发送到另一个。我已经查看了 How to use putExtra() and getExtra() for string data 等几个主题的答案,但我无法让它工作。

我要发送的字符串是:

public void golf(View view)  {
    Intent intent = new Intent(SearchSport.this, EventList.class);
    intent.putExtra("type", "golf");
    startActivity(intent);

我的接收器看起来像

String type;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_event_list);

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if ( extras != null)
        type = extras.getString("type");

    if (type == "golf"){
        TextView eventName      = (TextView) findViewById(R.id.EOName);
        TextView eventTime      = (TextView) findViewById(R.id.EOTime);
        TextView eventLocation  = (TextView) findViewById(R.id.EOLocation);

        DatabaseOperations dop = new DatabaseOperations(ctx);
        Cursor CR = dop.getInformation(1);
        CR.moveToFirst();

        eventName.setText(CR.getString(1));
        eventTime.setText(CR.getString(7) + " " + CR.getString(8) + ". " + CR.getString(9) + " kl. " + CR.getString(10) + ":" + CR.getString(11));
        eventLocation.setText(CR.getString(4));}

    else {Toast toast = Toast.makeText(this, "Error in Type.", Toast.LENGTH_LONG);
                toast.show();}

我不知道这里出了什么问题。每次我测试该应用程序时都会显示 toast,而不是用我的数据库条目中的数据填写 TextViews

编辑:代码已根据答案更改,但问题尚未解决。写 if (type.equals("golf")){} 而不是 if (type == "golf"){} 会使应用程序崩溃。

编辑 2:问题已解决!固定区分大小写,使用 .equals 而不是 ==,并将接收者写为

if(getIntent().hasExtra("Type"))
    type = getIntent().getStringExtra("Type");

最后,事实证明是我使用的虚拟设备导致应用程序崩溃,原因尚不清楚。在实际 android phone 上进行测试时,该应用程序按预期运行。

感谢大家的帮助!

更改密钥区分大小写:

  type = extras.getString("Type");

尝试从 Intent Extra 获取 String 时密钥错误:

type = extras.getString("type");

替换为:

type = extras.getString("Type");

注意:也使用 equals() 而不是 == 来比较 String

 if (type.equals("golf")){

试试这个

if(getIntent().hasExtra("Type"))
        type = getIntent().getStringExtra("Type");

当您使用 Extra 传递值时。您必须使用 getStringExtra(); 捕捉到它并且密钥必须区分大小写。

Intent i = getIntent();
type = i.getStringExtra("Type");

1) 首键区分大小写

2) 传递为

Bundle bundle = new Bundle() 
bundle.putString("type","golf");

intent.putExtras(bundle);

之后使用

获取它
Bundle received = i.getExtras();
received.getString("type");