Instructions:
[Link] the shared preferences concepts.
[Link] the field like in given task.
Main [Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private EditText name, age;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
name = findViewById([Link].edit1);
age = findViewById([Link].edit2);
}
// Fetch the stored data in onResume() Because this is what will be called
when the app opens again
@Override
protected void onResume() {
[Link]();
// Fetching the stored data from the SharedPreference
SharedPreferences sh = getSharedPreferences("MySharedPref",
MODE_PRIVATE);
String s1 = [Link]("name", "");
int a = [Link]("age", 0);
// Setting the fetched data in the EditTexts
[Link](s1);
[Link]([Link](a));
}
// Store the data in the SharedPreference in the onPause() method
// When the user closes the application onPause() will be called and data
will be stored
@Override
protected void onPause() {
[Link]();
// Creating a shared pref object with a file name "MySharedPref" in
private mode
SharedPreferences sharedPreferences =
getSharedPreferences("MySharedPref", MODE_PRIVATE);
[Link] myEdit = [Link]();
// write all the data entered by the user in SharedPreference and apply
[Link]("name", [Link]().toString());
[Link]("age", [Link]([Link]().toString()));
[Link]();
}
}
[Link]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
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: