在Android上传递bundle,每个键都为null

时间:2015-10-12 21:13:45

标签: android android-intent android-activity null bundle

我尝试使用以下代码将某些值从活动传递到另一个:

    Bundle bundle = new Bundle();

    bundle.putInt("x_element",xElementBar.getProgress());
    bundle.putInt("y_element",yElementBar.getProgress());
    bundle.putInt("frames",framesBar.getProgress());

    bundle.putInt("radioID", radioGroup.getCheckedRadioButtonId());

    bundle.putBoolean("sound", soundCheck.isChecked());
    bundle.putBoolean("vibrate",vibrateCheck.isChecked());

    Intent intent = new Intent(MainActivity.this,GameActivity.class);
    intent.putExtras(bundle);

    startActivity(intent);

使用此代码在另一个活动上显示值:

    Bundle bundle = getIntent().getExtras();

    columnsText.setText("El número de columnas es: " + bundle.getString("x_element"));
    rowText.setText("El número de filas es: " + bundle.getString("y_element"));
    optionsText.setText("El número de opciones es: " + bundle.getString("frames"));

    styleText.setText("Se mostrarán: " + (bundle.getInt("radioID") == R.id.radioNumbers?"números":"colores"));

    soundText.setText("El sonido esta: " + (bundle.getBoolean("sound")?"activado":"desactivado"));
    vibrateText.setText("La vibración esta: " + (bundle.getBoolean("vibrate")?"activada":"desactivada"));

但是每个bundle.getX(ID)返回一个null,在与R.id.radioNumbers的比较中崩溃并在其余部分显示null。

在第二个活动上创建包之前,声明并链接了TextViews(columnsText等)。

1 个答案:

答案 0 :(得分:2)

这是因为您将字段保存为一种类型并将其作为另一种类型检索:

发信人:

bundle.putInt("x_element",xElementBar.getProgress());

接收器:

columnsText.setText("El número de columnas es: " + bundle.getString("x_element"));

类型必须匹配,因此将接收器更改为bundle.getInt("x_element")以获取数据,然后将其转换为String

相关问题