Shared Preferences in Android. Save Data


<?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout 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="com.arham.csdevbin.downloadimagefrominternet.SharedPreferencesDemo">
    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="103dp"
        android:layout_marginStart="103dp"
        android:layout_marginTop="136dp"
        android:text="CheckBox" />
</RelativeLayout>



package com.arham.csdevbin.downloadimagefrominternet;

  import android.content.SharedPreferences;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.widget.CheckBox;
  import android.widget.CompoundButton;
  import android.widget.Toast;

  public class SharedPreferencesDemo extends AppCompatActivity implements
 CompoundButton.OnCheckedChangeListener {
    CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);
        checkBox = findViewById(R.id.checkBox);
        checkBox.setOnCheckedChangeListener(this);
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            checkBox.setText("The CheckBox is Checked");
        } else {
            checkBox.setText("The CheckBox is not Checked");
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
        SharedPreferences sharedPreferences = getPreferences(0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("CHECK_BOX_VALUE", checkBox.getText().toString());
        editor.putBoolean("CH", checkBox.isChecked());
        editor.commit();
    }
    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
        SharedPreferences sharedPreferences = getPreferences(0);
        boolean checkBoxValue = sharedPreferences.getBoolean("CH", false);
        String chBoxString = sharedPreferences.getString("CHECK_BOX_VALUE", "This is my CheckBox");
        checkBox.setChecked(checkBoxValue);
        checkBox.setText(chBoxString);
    }
}


Comments :

Post a Comment