Java how to pass a float between activities in android studio

Java how to pass a float between activities in android studio

To pass a float value between activities in Android, you can use an Intent object and the putExtra method to put the float value in the Intent object as an extra.

Here is an example of how you can pass a float value between activities in Android:

refer to:‮uttual‬ri.com
import android.content.Intent;

public class MainActivity extends AppCompatActivity {
    private float value;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        value = 1.23f;
    }
    
    public void openActivity(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putExtra("VALUE", value);
        startActivity(intent);
    }
}

In this example, the MainActivity activity has a float field called value, and a method called openActivity that is called when a button is clicked. The openActivity method creates an Intent object and puts the value field in the Intent object as an extra using the putExtra method. The SecondActivity class is specified as the target activity, and the Intent object is used to start the SecondActivity.

To get the float value from the Intent object in the SecondActivity class, you can use the getFloatExtra method of the Intent class:

import android.content.Intent;

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        
        Intent intent = getIntent();
        float value = intent.getFloatExtra("VALUE", 0.0f);
        // Do something with the value...
    }
}

In this example, the SecondActivity class gets the Intent object in the onCreate method using the getIntent method and retrieves the float value from the Intent object using the getFloatExtra method. The getFloatExtra method takes two arguments: the name of the extra and a default value. If the extra is not found, the default value is returned.

Keep in mind that this is just one way to pass a float value between activities in Android. You can use different methods and techniques to achieve the same result, such as using a Bundle object to store the float value and pass it to the Intent object, or using a global variable to store the float value and access it from any activity.

Created Time:2017-11-03 23:27:11  Author:lautturi