Add data fromEeditText to double

44 views Asked by At

I have an app where the user can enter an amount into an EditText but then I want to be able to add or subtract this to/from a double then be able to display this double with a TextView within another activity.

I'm not sure how to go about this and would appreciate some help. Thanks in advance!

Edit: I forgot to mention that I also want this data to be kept between app launches/closes.

2

There are 2 answers

0
Jazzer On BEST ANSWER

In your activity that accepts the input from the EditText:

double value = Double.parseDouble(yourEditText.getText().toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (adding) {
    value = prefs.getFloat("your.float.key", 0f) + value;
} else {
    value = prefs.getFloat("your.float.key", 0f) - value;
}
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("your.float.key", value);
editor.apply();

In your activity that shows the value:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Double value = prefs.getFloat("your.float.key", 0f);
yourTextView.setText(value.toString());
0
Galax On

Firstly you will need to parse the data from your EditText, you can get a String from an EditText using

EditText.getText().toString()

and then use some form of

Double.parseDouble(String)
Integer.parseInt(String)

to get a numeric value from the string, with which you can then use for whatever math you need. After you calculate this value you will want to send it to another Activity via intent

Intent i = new Intent(this, ActivityTwo.class);
        i.putExtra("KEY", myDouble);
        startActivity(i);

to receive the intent in your next activity use

Bundle extras = getIntent().getExtras();
if (extras != null) {
    Double myDouble = extras.getDouble("KEY");
}

and then if you want to save the value you will want to look into SharedPreferences

to save

SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("KEY", myFloat);
editor.commit();

to get

SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
myFloat = prefs.getFloat("KEY", myFloat);