通过Intent在类之间传递变量

6

我遇到了使用Intent在屏幕间导航方面的问题。我想发送一个变量并在另一个类中使用它。

我正在使用一个方法,这个方法接受变量,但我不知道如何通过Intent将它发送到新屏幕,在新屏幕中使用它来执行一些操作。

Main类调用该方法:

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);

        }

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

您能帮助我解决这个问题吗?非常感谢。

JMasia。


几乎是与https://dev59.com/m3I95IYBdhLWcg3w1BdN相同的问题。 - Andrew White
3个回答

13

使用intent中的extras bundle。

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

然后在 onCreate 方法中:

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

这是正确的。如果您想将任何东西放入意图中,您的变量必须实现Parcelable。 - eternalmatt
如果我发送一个int变量:private void pantallaDetalles(final int identificador) { Intent i; startActivityForResult(i = new Intent(this,MostrarDetalles.class),REQST_CODE); i.putExtra("identificador", identificador); }在第二个类中如何读取这个变量?我使用了getIntegerExtra,但它不起作用。 - JMasia
@JMasia,实际上是getIntExtra,已经更新了。请参阅文档:http://developer.android.com/reference/android/content/Intent.html#getIntExtra(java.lang.String, int) - Cheryl Simon
@Mayra。非常感谢您给我的所有帮助,但我可能做错了什么。应用程序始终显示默认值。您对此有何看法? - JMasia
是的,那就是问题所在。多么愚蠢的错误啊!非常感谢你,你太棒了。 :-) - JMasia
显示剩余2条评论

6

屏幕 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);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接