Use Bundle and/or only putExtra?

Asked

Viewed 3,429 times

6

To pass data between activity, have 2 forms:

1. Using Bundle:

public void teste(View v) {

    Intent i = new Intent(this,Teste.class);

    Bundle bd = new Bundle();
    bd.putString("site","google.com");

    i.putExtras(bd);
    startActivity(i);
}

2. Not to be used Bundle:

public void teste2(View v) {

    Intent i = new Intent(this,Teste.class);
    i.putExtra("site","site2.com");
    startActivity(i);
}

Doubts:

  • Why then should you use the Bundle?
  • Would have "particularities/reasons" for the use of Bundle?

1 answer

6


In the two examples you are using a Bundle.

The difference is that in the first example it is you who create it, while in the second it is created internment by the Intent class.

The method putExtras() receives an externally created Bundle.
When used, the internal Bundle is "merged" with the past to the method.

The method putExtra() is used to add values to the internal Bundle.

It is possible to use the method putExtras() and then the method putExtra(), or vice versa, to add new values.

A possible reason to use a Bundle created by you is to have values added to it at different stages of application execution.

For example. in case you want to pass the values passed to Activity to another Activity:

private Bundle extras;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    extras = getIntent().getExtras();

    if (extras != null) {
        // Obter valores individualmente
    }else{
        extras = new Bundle();
    }
}

Later when calling the other Activity

public void startActivityXXX(View v) {

    Intent i = new Intent(this,Teste.class);

    //Eventualmente adicionar mais valores
    extras.putString("site","google.com");

    i.putExtras(extras);
    startActivity(i);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.