Send a variable between classes through the Intent

2019-06-20 03:35发布

问题:

I'm getting problems using the Intent for navigate through the screens. I want to send a variable and use it in the other class.

I'm using a method, the method takes the variable but i don't know how to send it with the intent to the new screen, which will use it to do some things.

Main class calls the metod:

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

MostrarDetalles.class is the *.java which will take the variable. I'm begining it like this:

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

        }

Did you see? I'm talking about this. I don't know how to send the "identificador" variable from the main class to the second class through the Intent.

Can you help me with this? Thank you very much in advice.

JMasia.

回答1:

Use the extras bundle in the intent.

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

Then on onCreate:

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


回答2:

Screen 1:

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

Screen 2: (Receiver):

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:

You can use Intent.putExtra() to bundle the data you want to send with the intent.