๐ What is it?
User preferences are small pieces of data (like username, theme settings, or app preferences) that an app saves and loads using SharedPreferences.
๐ Why use it?
Stores simple key-value data (e.g., user settings).
Data is saved even after the app is closed.
Easy to implement and efficient.
Example: Save and Load Username
๐ก What this app does?
โ
User enters their name in a text box.
โ
Click “Save Name” โ Name is stored in SharedPreferences.
โ
Click “Load Name” โ Saved name is displayed.
Step 1: XML Layout (res/layout/activity_main.xml
)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="@+id/buttonSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Name" />
<Button
android:id="@+id/buttonLoad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load Name" />
<TextView
android:id="@+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Name Found"
android:textSize="18sp"
android:paddingTop="10dp"/>
</LinearLayout>
Step 2: Java Code (MainActivity.java
)
public class MainActivity extends AppCompatActivity {
private EditText nameInput;
private TextView nameDisplay;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameInput = findViewById(R.id.editTextName);
nameDisplay = findViewById(R.id.textViewName);
Button saveButton = findViewById(R.id.buttonSave);
Button loadButton = findViewById(R.id.buttonLoad);
sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", nameInput.getText().toString());
editor.apply();
Toast.makeText(getApplicationContext(), "Saved!", Toast.LENGTH_SHORT).show();
}
});
loadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = sharedPreferences.getString("username", "No Name Found");
nameDisplay.setText(name);
}
});
}
}
How This Works ?
Saving Data
- When you enter a name and click “Save Name,” the app stores it in SharedPreferences.
editor.putString("username", name);
โ Saves the name under the key"username"
.editor.apply();
โ Saves it in the background.
Loading Data
- When you click “Load Name,” the app retrieves the saved name.
sharedPreferences.getString("username", "No Name Saved");
- If no name is saved, it shows
"No Name Saved"
.
Summary
Feature | Description |
Where is data stored? | Inside the appโs internal storage (SharedPreferences) |
When to use it? | For saving simple settings (username, theme, preferences) |
Data persistence? | Yes, even after the app is closed |
Security? | Not encrypted (not for sensitive data) |
Accessing the Internal File system
Similar to the user preferences, we can also develop and android app which allows the user to store the app’s data in a file which could be later used to read or write the local data. This can be done by writing a function to read and write.
// FUNCTION TO WRITE THE data INTO THE FILE
private void writeToFile(String data) {
try (FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE)) {
fos.write(data.getBytes());
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} // End of writeToFile(data)
// FUNCTION TO READ THE FILE AND DISPLAY THE CONTENT
private void readFromFile() {
try (FileInputStream fis = openFileInput(FILE_NAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
outputText.setText(sb.toString());
} catch (IOException e) {
e.printStackTrace();
outputText.setText("Error reading file");
}
} // End of readFromFile()
Accessing the SD card
Similar to the accessing the internal file system, we can also develop and android app which allows the user to store the app’s data in a file located on an external SD card which could be later used to read or write the local data. This can be done by writing a function to read and write.
๐ External Storage (SD Card) allows files to be accessed by other apps.
โ ๏ธ Requires Permissions in AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
public class MainActivity extends AppCompatActivity {
private EditText inputText;
private TextView outputText;
private static final String FILE_NAME = "sdcardfile.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputText = findViewById(R.id.editText);
outputText = findViewById(R.id.textView);
Button saveButton = findViewById(R.id.buttonSave);
Button loadButton = findViewById(R.id.buttonLoad);
saveButton.setOnClickListener(v -> writeToSDCard(inputText.getText().toString()));
loadButton.setOnClickListener(v -> readFromSDCard());
}
private void writeToSDCard(String data) {
if (isExternalStorageWritable()) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), FILE_NAME);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data.getBytes());
Toast.makeText(this, "Saved to SD Card!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "SD Card not writable!", Toast.LENGTH_SHORT).show();
}
}
private void readFromSDCard() {
if (isExternalStorageReadable()) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), FILE_NAME);
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
outputText.setText(sb.toString());
} catch (IOException e) {
e.printStackTrace();
outputText.setText("Error reading file");
}
} else {
Toast.makeText(this, "SD Card not readable!", Toast.LENGTH_SHORT).show();
}
}
private boolean isExternalStorageWritable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
private boolean isExternalStorageReadable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ||
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
}