Post Top Ad

Post Top Ad

Saturday 8 July 2017

Android Shared Preferences



1.activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.kiran.lesson12_sharedpreferences.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textStyle="normal|bold"
        android:text="0"
        android:hint="Count"
        android:textSize="30sp"
        android:textAlignment="center" />

    <Button
        android:text="Count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_marginTop="68dp"
        android:id="@+id/button" />
</RelativeLayout>




2.MainActivity.java:

package com.example.kiran.lesson12_sharedpreferences;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button mCountBtn;
    TextView mCountTv;
    int mCount;
    private SharedPreferences mSP;
    private SharedPreferences.Editor mEditor;

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

        mCountBtn = (Button) findViewById(R.id.button);
        mCountTv = (TextView) findViewById(R.id.textView);
        mSP = getPreferences(MODE_PRIVATE);
        mEditor = mSP.edit(); //for editing preferences
        mCount = mSP.getInt("count",0);
        mCountTv.setText(String.valueOf(mCount));
        mCountBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCount = Integer.parseInt(mCountTv.getText().toString());
                mCount++;
                mCountTv.setText(String.valueOf(mCount));
                mEditor.putInt("count",mCount);
                mEditor.commit();
            }
        });



    }
}

No comments:

Post a Comment