【问题标题】:Send a variable between classes through the Intent通过 Intent 在类之间发送变量
【发布时间】:2011-03-17 18:28:46
【问题描述】:

我在使用 Intent 浏览屏幕时遇到问题。我想发送一个变量并在其他类中使用它。

我正在使用一种方法,该方法采用变量,但我不知道如何将其与意图一起发送到新屏幕,新屏幕将使用它来做一些事情。

主类调用方法:

private void pantallaDetalles(final int identificador)
{
     startActivityForResult(new Intent(this,MostrarDetalles.class),REQST_CODE);
}

MostrarDetalles.class 是 *.java,它将接受变量。我是这样开始的:

public class MostrarDetalles extends Activity {

    SQLiteDatabase db;

    public void onCreate(Bundle savedInstanceState)
        {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.detalles);


         //more code...


         Cursor c = db.rawQuery("SELECT * FROM table WHERE _id="+ identificador, null);

        }

你看到了吗?我正在谈论这个。我不知道如何通过Intent将“identificador”变量从主类发送到第二类。

你能帮我解决这个问题吗?非常感谢您的建议。

JMasia。

【问题讨论】:

标签: android class variables android-intent


【解决方案1】:

在 Intent 中使用 extras 包。

Intent i = new Intent(...);
i.putExtra("name_of_extra", myObject);

然后在 onCreate:

getIntent.getIntExtra("name_of_extra", -1);

【讨论】:

  • 这是正确的。如果你想在意图中加入任何东西,你的变量必须实现 Parcelable。
  • 如果我发送一个 int 变量:private void pantallaDetalles(final int identificador) { Intent i; startActivityForResult(i = new Intent(this,MostrarDetalles.class),REQST_CODE); i.putExtra("identificador", identificador); } 我如何读取第二类中的变量?我使用了 getIntegerExtra,但它不起作用。
  • @eternalmatt 您还可以发送原始类型或可序列化类型。
  • @JMasia 它实际上是 getIntExtra,已更新。请参阅文档:developer.android.com/reference/android/content/…, int)
  • @Mayra。我真的要感谢你给我的所有帮助,但我会做错事。该应用程序始终显示默认值。你怎么看?
【解决方案2】:

屏幕 1:

Intent i=new Intent("com.suatatan.app.Result");
                i.putExtra("VAR_RESULT", "Added !");
                startActivity(i);

屏幕 2:(接收者):

TextView tv_sonuc = (TextView) findViewById(R.id.tv_sonuc);

Bundle bundle = getIntent().getExtras();

String var_from_prev_intent = bundle.getString("VAR_RESULT");
tv_sonuc.setText(var_from_prev_intent);

【讨论】:

    【解决方案3】:

    您可以使用Intent.putExtra() 将您要发送的数据与意图捆绑在一起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多