Sharedpreferences
Sharedpreferences
// MainActivity.java
package com.example.sharedpreferencesdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = findViewById(R.id.editTextName);
buttonSave = findViewById(R.id.buttonSave);
textViewName = findViewById(R.id.textViewName);
buttonLoad = findViewById(R.id.buttonLoad);
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editTextName.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name);
editor.apply(); // or editor.commit();
Toast.makeText(MainActivity.this, "Name saved!", Toast.LENGTH_SHORT).show();
}
});
buttonLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", "No Name"); // default value "No
Name"
textViewName.setText("Saved Name: " + name);
}
});
}
}
XML
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:inputType="textPersonName" />
<Button
android:id="@+id/buttonSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Name" />
<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Saved Name: "
android:textSize="18sp" />
<Button
android:id="@+id/buttonLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Name" />
</LinearLayout>
Explanation: