android - 无法将变量值分配给 extra.getString() 中的字符串;

标签 android string android-intent

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代替==,并将receiver写成

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

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

感谢大家的帮助!

最佳答案

试试这个

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

关于android - 无法将变量值分配给 extra.getString() 中的字符串;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30124320/

相关文章:

c# - 如何使用 Regex.Split 拆分字符串并保留所有分隔符?

android - 通过 list 注册时广播接收器不工作

Android:安排剩余事件

java - 如何将调用 Request.callback onCompleted() 方法时从 Facebook 返回的数据传递到我在 Android 中的 fragment ?

string - 测试字符串是否为有效整数

android - 如何选择带有 ACTION_SENDTO 的电子邮件应用程序也支持附件?

android - Intent.getStringExtra() 总是返回 null

android - Uncaught ReferenceError : AFMA_getSdkConstants is not defined

android - Resources.NotFoundException 在 res/color/secondary_text_dark.xml 上抛出

javascript - 为什么 "String.prototype={}"不起作用?