简体   繁体   中英

How to save value of counter when onDestroy callback is called?

I'm working on a small and simple android app where I increase or decrease a counter on button click. When the app goes onStop , I'm saving the current counter value in the text file and when I come back to the app, I'm reading the written value and showing it on screen in the TextView . The problem is that when I come back to the app and receive the value and try to increment it, it starts to count from 0. However, the problem happens if I leave the app and onDestroy callback is called, but if I rotate the phone and the same onDestroy are called the counter works as it is expected to work. My question is how to continue increasing the counter from the latest saved value?

Here is my code:

MainActivity

public class MainActivity extends AppCompatActivity {
    private static final String FILE_NAME = "test.txt";
    TextView textView;
    private int count;

    private static final String TAG = "MainActivity";

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

        textView = findViewById(R.id.text1);

        readTextFile();


        if (savedInstanceState != null){

            count = savedInstanceState.getInt("count");
            textView.setText(String.valueOf(count));

        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt("count", count);

    }

    public void decrement(View view) {

        count --;
        textView.setText(String.valueOf(count));
    }

    public void increment(View view) {
        count++;
        textView.setText(String.valueOf(count));
    }



    @Override
    protected void onStop() {
        super.onStop();

        String text = String.valueOf(count);
        FileOutputStream fos = null;

        try {
            fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
            try {
                fos.write(text.getBytes());
                Toast.makeText(this, "Saved to " + getFilesDir() + FILE_NAME, Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        count = Integer.parseInt(text);

        Log.i(TAG,"onStop");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,"onPause");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");
    }

    public void readTextFile(){

        FileInputStream fis = null;

        try {
            fis = openFileInput(FILE_NAME);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String text;

            while ((text = br.readLine()) != null){
                sb.append(text);
            }
            textView.setText(sb.toString());


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:screenOrientation="sensorLandscape"


    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text1"
        android:layout_width="167dp"
        android:layout_height="45dp"
        android:gravity="center"
        android:text="0"
        android:textColor="#0C0C0C"
        android:textSize="36sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.603" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="decrement"
        android:text="-"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="increment"
        android:text="+"
        app:layout_constraintBottom_toTopOf="@+id/text1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

You don't set value for count in readTextFile() so it's 0. It works when you rotate your phone because you saved value at savedInstanceState .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM