0

Всем привет! Помогите начинающему! Нужно чтобы при выходе из приложения результат сохранялся.

Мы водим цифру и в нескольких TextView выводится разный результат. Необходимо сохранить цифру которую вводим и результаты.

Вот код, который нам считает

public void onButtonClick2(View v) {


    EditText gymres = (EditText) findViewById(R.id.gymres);
    ok = (Button) findViewById(R.id.ok);
    TextView resText = (TextView) findViewById(R.id.text1);
    TextView resText2 = (TextView) findViewById(R.id.text2);
    TextView resText3 = (TextView) findViewById(R.id.text3);
    TextView resText4 = (TextView) findViewById(R.id.text4);
    TextView resText5 = (TextView) findViewById(R.id.text5);


    int num = Integer.parseInt(gymres.getText().toString());
    double res = num * 0.3;
    double res2 = num * 0.4;
    double res3 = num * 0.5;
    double res4 = num * 0.6;
    double res5 = num * 0.6;
    resText.setText (Integer.toString((int) res ));
    resText2.setText(Integer.toString((int) res2));
    resText3.setText(Integer.toString((int) res3));
    resText4.setText(Integer.toString((int) res4));
    resText5.setText(Integer.toString((int) res5));


}

SharedPreference пробую, но сохраняет только один результат и выводит одно значение в разные TextView. Спасибо за любую полезную помощь.

3
  • 1
    Надо в вопрос не код, который считает, а код, который сохраняет... И который выводит. 30 мар 2020 в 17:22
  • А зачем вы переводите дробное число в целое? 30 мар 2020 в 17:32
  • Если мой код не будет у вас работать, то я не знаю, как вам ещё помочь 31 мар 2020 в 13:17

1 ответ 1

1

Простите, пожалуйста, но вы уверены, что правильно используете SharedPreferences?

package com.example.andrey;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    Context context = MainActivity.this;
    SharedPreferences prefer;
    Editor editor;
    EditText gymres;
    TextView resText, resText2, resText3, resText4, resText5;
    int num = 0;
    Button ok;
    double res, res2, res3, res4, res5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       //Назначаем SharedPreferences
        prefer = getSharedPreferences("STORAGE_NAME", Context.MODE_PRIVATE);
        editor = prefer.edit();
        gymres = (EditText) findViewById(R.id.gymres);
        ok = (Button) findViewById(R.id.ok);
        resText = (TextView) findViewById(R.id.text1);
        resText2 = (TextView) findViewById(R.id.text2);
        resText3 = (TextView) findViewById(R.id.text3);
        resText4 = (TextView) findViewById(R.id.text4);
        resText5 = (TextView) findViewById(R.id.text5);

        public void onButtonClick2(View v) {
            num = Integer.parseInt(gymres.getText().toString());
            res = num * 0.3;
            res2 = num * 0.4;
            res3 = num * 0.5;
            res4 = num * 0.6;
            res5 = num * 0.6;

            resText.setText(Integer.toString((int) res));
            resText2.setText(Integer.toString((int) res2));
            resText3.setText(Integer.toString((int) res3));
            resText4.setText(Integer.toString((int) res4));
            resText5.setText(Integer.toString((int) res5));

            //Кладём и сохраняем значения
            editor.putInt("RES", (int) res);
            editor.putInt("RES2", (int) res2);
            editor.putInt("RES3", (int) res3);
            editor.putInt("RES4", (int) res4);
            editor.putInt("RES5", (int) res5);
            editor.apply();
        };
    };
}

Я вынес нахождения элементов интерфейса из метода, потому что сомневаюсь, что это нужно делать каждое нажатие.

А вот так их брать.

 res = prefer.getInt("RES", 0);
 res1 = prefer.getInt("RES1", 0);
 res2 = prefer.getInt("RES2", 0);
 res3 = prefer.getInt("RES3", 0);
 res4 = prefer.getInt("RES4", 0);
 res5 = prefer.getInt("RES5", 0);

Дополнение (просто распишу всё)

Я считаю, разбиение кода на отдельные методы помогут иногда решить лишь эстетические проблемы. Поэтому, если не работает так, то и по-другому работать не станет. Лучше я распишу всё поподробнее.

0.0. Объявим необходимые для сохранения и получения данных переменные:

SharedPreferences prefer;
Editor editor;
final String STORAGE_NAME = "STORAGE_NAME", RES_NAME = "res", RES2_NAME = "res2", RES3_NAME = "res3", RES4_NAME = "res4", RES5_NAME = "res5";
int old_res, old_res2, old_res3, old_res4, old_res5;
double res, res2, res3, res4, res5;

0.1. Присвоим им значения:

prefer = getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE);
editor = prefer.edit();

1.1. Сохраним полученные значения:

//Пусть это будет метод saveData
void saveData() {
    editor.putInt(RES_NAME, (int) res);
    editor.putInt(RES2_NAME, (int) res2);
    editor.putInt(RES3_NAME, (int) res3);
    editor.putInt(RES4_NAME, (int) res4);
    editor.putInt(RES5_NAME, (int) res5);
    editor.apply();
};
//ВНИМАНИЕ! Убедитесь, что вы утвердили изменения (написали «editor.apply()»)

1.2. Получаем нужные данные:

//Пусть это будет метод getData
void getData() {
    old_res = prefer.getInt(RES_NAME, 0);
    old_res1 = prefer.getInt(RES2_NAME, 0);
    old_res3 = prefer.getInt(RES3_NAME, 0);
    old_res4 = prefer.getInt(RES4_NAME, 0);
    old_res5 = prefer.getInt(RES5_NAME, 0);
};

Теперь о том, как их расположить в коде. Выше я описал только "каркас", ниже приведу код готовой активности (простите, но я предположил, что вся работа должна быть в методе onClick).

package com.example.andrey;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;

public class MainActivity extends Activity {

    SharedPreferences prefer;
    Editor editor;
    String value;
    final String STORAGE_NAME = "STORAGE_NAME", RES_NAME = "res", RES2_NAME = "res2", RES3_NAME = "res3", RES4_NAME = "res4", RES5_NAME = "res5";
    int old_res, old_res2, old_res3, old_res4, old_res5;
    double res, res2, res3, res4, res5;
    EditText gymres;
    TextView resText, resText2, resText3, resText4, resText5;
    int num = 0;
    Button ok;

    void saveData() {
        editor.putInt(RES_NAME, (int) res);
        editor.putInt(RES2_NAME, (int) res2);
        editor.putInt(RES3_NAME, (int) res3);
        editor.putInt(RES4_NAME, (int) res4);
        editor.putInt(RES5_NAME, (int) res5);
        editor.apply();
        resText.setText(Integer.toString((int) res));
        resText2.setText(Integer.toString((int) res2));
        resText3.setText(Integer.toString((int) res3));
        resText4.setText(Integer.toString((int) res4));
        resText5.setText(Integer.toString((int) res5)); 
    };

    void getData() {
        old_res = prefer.getInt(RES_NAME, 0);
        old_res2 = prefer.getInt(RES2_NAME, 0);
        old_res3 = prefer.getInt(RES3_NAME, 0);
        old_res4 = prefer.getInt(RES4_NAME, 0);
        old_res5 = prefer.getInt(RES5_NAME, 0);
        resText.setText(Integer.toString(old_res));
        resText2.setText(Integer.toString(old_res2));
        resText3.setText(Integer.toString(old_res3));
        resText4.setText(Integer.toString(old_res4));
        resText5.setText(Integer.toString(old_res5)); 

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gymres = (EditText) findViewById(R.id.gymres);
        ok = (Button) findViewById(R.id.ok);
        resText = (TextView) findViewById(R.id.text1);
        resText2 = (TextView) findViewById(R.id.text2);
        resText3 = (TextView) findViewById(R.id.text3);
        resText4 = (TextView) findViewById(R.id.text4);
        resText5 = (TextView) findViewById(R.id.text5); 
        prefer = getSharedPreferences(STORAGE_NAME, Context.MODE_PRIVATE);
        editor = prefer.edit();

        getData();

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((value = gymres.getText().toString()).length() > 0) {
                    num = Integer.parseInt(value);
                    res = num * 0.3;
                    res2 = num * 0.4;
                    res3 = num * 0.5;
                    res4 = num * 0.6;
                    res5 = num * 0.6;

                    saveData();
                };
            };
        });
    };
}

И макет, если вдруг что-нибудь не сойдётся.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent" >

    <EditText
        android:id="@+id/gymres"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/ok"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout >

Работу этого кода я проверил, он полностью рабочий.

7
  • 2
    Не надо сохранять double через putInt(). 30 мар 2020 в 18:04
  • Спасибо, попробую )) 30 мар 2020 в 18:41
  • Вася Воронцов, спасибо за ответ, но не совсем понимаю, возможно что то не правильно делаю. Все прописал, как Вы сказали, но как то не работает. Может нужно создать отдельно методы на сохранение и загрузку данных. Подскажите плз 31 мар 2020 в 9:28
  • Спасибо огроооомное за помощь! Все ок))) 31 мар 2020 в 16:25
  • Вася Воронцов, подскажите еще такую вещь, как сохранять значение нескольких checkbox. есть на пример 5 чеков, и при выходе нужно сохранить их состояние. У меня получается, но только один чекбокс сохранить нажатым и если добавляю в код еще несколько, то они все зависят от последнего.(Буду благодарен и если не сложно) 31 мар 2020 в 18:45

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.