Use the Bundle and / or just putExtra?

7

To pass data between activity , I have 2 forms:


1. Use 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. DO NOT use Bundle :

    public void teste2(View v) {

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

Questions:

  • Why should use the Bundle ?
  • Have " particularities / reasons " for the use of Bundle ?
asked by anonymous 09.11.2017 / 17:11

1 answer

6

In both examples you are using a Bundle.

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

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

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

You can use the putExtras() method and then the putExtra() method, or vice versa, to add new values.

A possible reason to use a bundle created by you is to have the need for the values to be added to it at different stages of running the application.

For example if 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);
}
    
09.11.2017 / 17:30