Android getIntent error

Asked

Viewed 162 times

0

Hello,

I have an application that I need to send data of a Activity to another Activity. I tested several ways however all failed, but in another project one code worked normally, but in my current one did not. Can it be a logic or sequence error of the codes? I need to send the value of Byte 1 or 2, of Activity Main to the DemE. Follow 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 the Toast to test if the values were being received, however the value was returned as null.

Thank you!

2 answers

1

You don’t need to put one Bundle as an extra to your Intent, since, the extra of his Intent is already a Bundle (according to the documentation).

So, you just 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 inside a Bundle Bundle and want to access it several times. Only for good practices):

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

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

...   
if(getIntent().hasExtra("valor")){
    Byte valor = getIntent().getByteExtra("valor", 0);
}
...

0

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

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

Apparently when you don’t initialize the Bundle it can’t get the values..

Browser other questions tagged

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