Урок 12N/SharedPreferences

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
private SharedPreferences pref;
private TextView tvResult;
private int counter = 0;
private final static String KEY = "key";

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

pref = getSharedPreferences("TABLE",MODE_PRIVATE);

counter = pref.getInt(KEY,0);
tvResult.setText(String.valueOf(counter));

}

public void onClickAdd(View view) {
counter++;
tvResult.setText(String.valueOf(counter));
saveData(counter);
}
private void saveData(int dataToSave)
{
SharedPreferences.Editor editor = pref.edit();
editor.putInt(KEY, dataToSave);
editor.apply();
}
private void deletKey()
{
SharedPreferences.Editor editor = pref.edit();
editor.remove(KEY)
editor.apply();
}

public void onClickDeleteAll(View view) {
deletKey();
}

activity_main.xml

<?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"
tools:context=".MainActivity">

<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.153" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="124dp"
android:onClick="onClickAdd"
android:text="Add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:onClick="onClickDeleteAll"
android:text="Delete All"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *