Instructions: 1.apply The Shared Preferences Concepts. 2.create The Field Like in Given Task
Instructions: 1.apply The Shared Preferences Concepts. 2.create The Field Like in Given Task
Instructions: 1.apply The Shared Preferences Concepts. 2.create The Field Like in Given Task
Main Activity.java
package com.example.sharedpreferences;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.edit1);
age = findViewById(R.id.edit2);
}
// Fetch the stored data in onResume() Because this is what will be called
when the app opens again
@Override
protected void onResume() {
super.onResume();
// Fetching the stored data from the SharedPreference
SharedPreferences sh = getSharedPreferences("MySharedPref",
MODE_PRIVATE);
String s1 = sh.getString("name", "");
int a = sh.getInt("age", 0);
// write all the data entered by the user in SharedPreference and apply
myEdit.putString("name", name.getText().toString());
myEdit.putInt("age", Integer.parseInt(age.getText().toString()));
myEdit.apply();
}
}
Activitymain.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="Shared Preferences Demo"
android:textColor="@android:color/black"
android:textSize="24sp" />
<!--EditText to take the data from the user and save the data in
SharedPreferences-->
<EditText
android:id="@+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textview"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:hint="Enter your Name"
android:padding="10dp" />
<!--EditText to take the data from the user and save the data in
SharedPreferences-->
<EditText
android:id="@+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edit1"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:hint="Enter your Age"
android:inputType="number"
android:padding="10dp" />
</RelativeLayout>
Output: