Android getIntent error

0

Hello,

I have an application that I need to send data from a Activity to another Activity . I tested it in several ways however all failed, but in another project a code worked normally, but in my current one it did not. Can it be a logic or sequence error of the codes? I need to send the value of Byte 1 or 2, from Activity Main to DemE . Here is the code below.

ActivityMain :

public void onClick(View arg0) {
    Byte valor = 1;
    Intent intent = new Intent(Main.this, DemE.class);
    Bundle params = new Bundle();
    params.putByte("dado", valor);
    intent.putExtras(params);
    startActivity(intent);
}

ActivityDemE :

Intent intent = getIntent();
Bundle params = intent.getExtras();

Byte valor = params.getByte("dado");
Toast.makeText(DemE.this, "valor" + valor, Toast.LENGTH_LONG).show();

I used Toast to test whether values were being received, but the value was returned as null .

Thank you!

    
asked by anonymous 05.03.2015 / 14:01

2 answers

1

You do not need to put Bundle as an extra of your Intent , since the extra of your Intent is already a Bundle (in accordance with the documentation ).

So, you simply need to do the following:

...
Byte valor = 1;
Intent intent = new Intent(Main.this, DemE.class);
intent.putExtras("valor", valor);
startActivity(intent);
...

To recover this value, you can:

1) Put inside a Bundle as you are already doing (this is advantageous if you have multiple objects within a Bundle and want to access it several times.

...
Bundle bundle = getIntent().getExtras();
if (bundle != null){
    Byte valor = bundle.getByte("valor");
} 
...

2) Retrieve directly from your getIntent (). getExtras ():

...   
if(getIntent().hasExtra("valor")){
    Byte valor = getIntent().getByteExtra("valor", 0);
}
...
    
05.03.2015 / 15:07
0

I tried to do a similar implementation today and to solve, in the second Activity I did

Intent intent = getIntent();
Bundle bundle =new Bundle();
bundle= intent.getExtras();
Byte valor = bundle.getByte("valor");

Apparently when you do not initialize the bundle it can not get the values ..

    
06.03.2015 / 10:50