Change variable from another class

Asked

Viewed 970 times

1

I have two Activity/classes, follow the boot of my first Activity where when I click goes to the second Activity:

    public void onButtonClick(View v){
    if(v.getId() == R.id.Busuarios){
        Intent i = new Intent(Velocimetro.this,Usuarios.class);
        i.putExtra("vel",maxima);
        startActivity(i);
    }

Now within my second Activity I have the following:

        Intent i = getIntent();
    velm = i.getDoubleExtra("vel",Math.round(vel.maxima));

What I need: In this second Activity I need to CHANGE the value of the MAXIMUM variable (there from the first Activity).

How I do?

  • I don’t understand well, you want to change the variable that is in the other Activity?

  • I gave an Edit to better answer.

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

1 answer

4

Two forms. The first is to set the variable maxima as public Static and change it directly from any other class: Velocimetro.maxima = value;

Or

Activityforresult method() Your first Activity calls the second and awaits a result.

For example:

Intent i = new Intent(Velocimetro.this, 
Usuarios.class);
startActivityForResult(i, 1);

In your second Activity you select the data you want to return to the first Activity.

For example, in Activity Usuarios.class:

Intent returnIntent = new Intent();
returnIntent.putExtra("resultado", resultado);
 setResult(Activity.RESULT_OK, returnIntent);
finish();

Not to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent); 
finish();

Receiving the result

Now in your first Activity write the following code in the method onActicityResult():

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (requestCode == 1) { 
    if(resultCode == Activity.RESULT_OK){
         String result = data.getStringExtra("resultado");
     }
     if (resultCode == Activity.RESULT_CANCELED) { 
//vazio
    }
 }
 }//onActivityResult

Browser other questions tagged

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