Как сохранять данные, введенные в EditText, при выходе из приложения
У меня есть приложение - расчёт дневной нормы калорий. Ввожу значения и по формуле рассчитываю. Так вот, хотелось бы, чтобы при выходе из приложения сохранялась хотя бы рассчитанная норма калорий. В идеале конечно, чтобы сохранялись все введенные значения, но и просто рассчитанной нормы мне будет достаточно. Буду рад любой помощи. Есть ещё проблема, у меня в коде есть проверка, пустые ли поля. Так вот, если я сначала заполню поля, а потом удалю в любом поле введенные значения, то при нажатии на кнопку вместо получения предупреждения о том, что поля не заполнены, приложение вылетает. Код ошибки прилагаю.
Код java-класса с выполнением всех действий:
public class FragmentFirst extends Fragment {
EditText editTextAge, editTextWeight, editTextHeight;
RadioGroup radioGroupGender;
RadioButton radioButtonMale, radioButtonFemale;
Spinner spinnerActivity;
Button buttonCalculate;
TextView textViewResult;
public FragmentFirst() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_first, container, false);
}
@Override
public void onStart()
{
super.onStart();
editTextAge = (EditText)getActivity().findViewById(R.id.edit_text_age);
editTextWeight = (EditText)getActivity().findViewById(R.id.edit_text_weight);
editTextHeight = (EditText)getActivity().findViewById(R.id.edit_text_height);
radioGroupGender = (RadioGroup)getActivity().findViewById(R.id.radio_group_gender);
radioButtonMale = (RadioButton)getActivity().findViewById(R.id.radio_button_male);
radioButtonFemale = (RadioButton)getActivity().findViewById(R.id.radio_button_female);
spinnerActivity = (Spinner)getActivity().findViewById(R.id.spinner_activity_level);
buttonCalculate = (Button)getActivity().findViewById(R.id.button_calculate);
textViewResult = (TextView)getActivity().findViewById(R.id.textViewResult);
buttonCalculate.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Context context = getActivity();
String heightText = editTextHeight.getText().toString();
String weightText = editTextHeight.getText().toString();
String ageText = editTextHeight.getText().toString();
int genderId = radioGroupGender.getCheckedRadioButtonId();
if(heightText.equals("") || weightText.equals("") || ageText.equals("") || genderId == -1)
{
Toast.makeText(context, "Не все поля заполнены", Toast.LENGTH_SHORT).show();
} else
{
calculateDailyCalorieIntake();
}
}
});
}
private void calculateDailyCalorieIntake()
{
double activity = 0;
int age = Integer.parseInt(editTextAge.getText().toString());
double weight = Double.parseDouble(editTextWeight.getText().toString());
double height = Double.parseDouble(editTextHeight.getText().toString());
int gender = radioGroupGender.getCheckedRadioButtonId();
int activityLevel = spinnerActivity.getSelectedItemPosition();
switch (activityLevel)
{
case 0:
activity = 1.2;
break;
case 1:
activity = 1.375;
break;
case 2:
activity = 1.55;
break;
case 3:
activity = 1.725;
break;
case 4:
activity = 1.9;
break;
}
double bmr;
if (gender == radioButtonMale.getId())
{
bmr = 88.36 + (13.4 * weight) + (4.8 * height) - (5.7 * age);
} else
{
bmr = 447.6 + (9.2 * weight) + (3.1 * height) - (4.3 * age);
}
double dailyCalorieIntake = bmr * activity;
DecimalFormat decimalFormat = new DecimalFormat("#.#");
String result = decimalFormat.format(dailyCalorieIntake);
textViewResult.setText(result + " кк");
}
}
Код xml-разметки, вдруг пригодится:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:textSize="24dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/calc_title" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="@string/rost_text"/>
<EditText
android:id="@+id/edit_text_height"
android:layout_width="match_parent"
android:layout_height="48dp"
android:inputType="number"
android:hint="Рост (в сантиметрах)" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="@string/ves_text"/>
<EditText
android:id="@+id/edit_text_weight"
android:layout_width="match_parent"
android:layout_height="48dp"
android:inputType="number"
android:hint="Вес (в килограммах)" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="@string/age_text"/>
<EditText
android:id="@+id/edit_text_age"
android:layout_width="match_parent"
android:layout_height="48dp"
android:inputType="number"
android:hint="Возраст"
android:layout_marginBottom="40dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/phys_act"
android:textSize="18dp"
android:layout_marginBottom="10dp"/>
<Spinner
android:id="@+id/spinner_activity_level"
android:layout_width="match_parent"
android:layout_height="48dp"
android:entries="@array/activity_levels"
android:prompt="@string/activity_level_prompt" />
<RadioGroup
android:id="@+id/radio_group_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radio_button_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Мужской" />
<RadioButton
android:id="@+id/radio_button_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Женский" />
</RadioGroup>
<Button
android:id="@+id/button_calculate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:background="@android:drawable/editbox_background"
android:padding="10dp"
android:text="Рассчитать" />
<TextView
android:layout_width="match_parent"
android:layout_height="41dp"
android:textAlignment="center"
android:textSize="18dp"
android:text="@string/sut_norm"/>
<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="41dp"
android:text=""
android:textAlignment="center"
android:textSize="32dp"
android:textStyle="bold" />
</LinearLayout>
Код ошибки:
FATAL EXCEPTION: main
Process: com.example.recipe, PID: 15259
java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.example.recipe.fragments.FragmentFirst.calculateDailyCalorieIntake(FragmentFirst.java:87)
at com.example.recipe.fragments.FragmentFirst.access$000(FragmentFirst.java:29)
at com.example.recipe.fragments.FragmentFirst$1.onClick(FragmentFirst.java:76)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16222)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1211)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8653)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)