0% found this document useful (0 votes)
14 views4 pages

Mad Unit 4

The document explains two methods for data storage in Android: Shared Preferences and application-specific files. Shared Preferences is used for storing small key-value pairs persistently, while application-specific files can be stored in internal or external storage for larger data needs. It also covers how to create, save, retrieve, and manage data using both methods, along with considerations for security and permissions.

Uploaded by

sonusurepally
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Mad Unit 4

The document explains two methods for data storage in Android: Shared Preferences and application-specific files. Shared Preferences is used for storing small key-value pairs persistently, while application-specific files can be stored in internal or external storage for larger data needs. It also covers how to create, save, retrieve, and manage data using both methods, along with considerations for security and permissions.

Uploaded by

sonusurepally
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Shared Preferences:
### Shared Preferences in Android

#### Overview
Shared Preferences in Android is a simple mechanism to store and retrieve key-value pairs of
primitive data types such as `int`, `float`, `boolean`, `String`, and `Set<String>`. It is primarily
used for storing small amounts of data that needs to persist across user sessions, such as
user settings, preferences, or simple state information.

#### Creating Shared Preferences


To create or access Shared Preferences, you use the `getSharedPreferences()` method in the
context of an Activity or Application. You need to provide a name for the preferences file
and the mode, which defines the access permissions.

```java
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
```

#### Saving Data to Shared Preferences


To save data in Shared Preferences, you use the `SharedPreferences.Editor` class. You can
put data into the editor and then commit the changes.

```java
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.putInt("age", 25);
editor.putBoolean("isLoggedIn", true);
editor.commit(); // Alternatively, use apply() for asynchronous saving
```

The `commit()` method writes the changes synchronously, whereas `apply()` saves the
changes asynchronously without returning a Boolean value.

#### Retrieving Data from Shared Preferences


To retrieve data, you use the corresponding getter methods. Each getter method requires
the key of the preference and a default value to return if the key doesn't exist.

```java
String username = sharedPreferences.getString("username", "defaultUsername");
int age = sharedPreferences.getInt("age", 0);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
```

#### Example Usage


Here is a complete example demonstrating how to create, save, and retrieve data using
Shared Preferences:

```java
// Creating or accessing Shared Preferences
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);

// Saving data
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.putInt("age", 25);
editor.putBoolean("isLoggedIn", true);
editor.apply(); // or editor.commit();

// Retrieving data
String username = sharedPreferences.getString("username", "defaultUsername");
int age = sharedPreferences.getInt("age", 0);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

// Displaying retrieved data


Log.d("SharedPreferences", "Username: " + username);
Log.d("SharedPreferences", "Age: " + age);
Log.d("SharedPreferences", "Is Logged In: " + isLoggedIn);
```

#### Considerations
- **Data Size**: Shared Preferences is not suitable for storing large amounts of data. It is
ideal for small configuration settings.
- **Security**: For sensitive data, consider using encryption before storing it in Shared
Preferences.
- **Lifecycle**: Data stored in Shared Preferences is persistent across application restarts,
but it can be cleared when the app is uninstalled or explicitly cleared by the user.

Using Shared Preferences is a straightforward way to handle simple persistence needs in


Android applications, ensuring user preferences and small data sets are retained across
sessions.

2. Files:
### Application-Specific Folders and Files in Android

#### Overview
In Android, applications can store files in their own specific directories within the device's
internal or external storage. These directories are isolated to each application, ensuring that
the data is secure and private. Common uses include storing user data, configuration files,
cache files, or any other data that needs to persist between sessions.

#### Application-Specific Directories


1. **Internal Storage**: Data stored here is private to the application and not accessible by
other apps. It is the recommended place for storing sensitive data.
2. **External Storage**: Data stored here can be accessed by other apps and the user, but it
requires permissions. It is suitable for larger, non-sensitive files.

#### Creating Files


To create files in the internal storage, you can use methods like `openFileOutput()` and for
external storage, you can use the `getExternalFilesDir()` method to get the appropriate
directory.

**Internal Storage Example:**


```java
String filename = "myfile.txt";
String fileContents = "Hello World!";
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(fileContents.getBytes());
fos.close();
```

**External Storage Example:**


```java
File externalDir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File file = new File(externalDir, "myfile.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(fileContents.getBytes());
fos.close();
```

#### Reading Data from Files


To read data from files, you can use `openFileInput()` for internal storage and standard
`FileInputStream` for external storage.

**Internal Storage Example:**


```java
FileInputStream fis = openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String fileContents = sb.toString();
fis.close();
```

**External Storage Example:**


```java
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String fileContents = sb.toString();
fis.close();
```

#### Listing Contents of a Directory


You can list the contents of a directory using the `listFiles()` method.

**Internal Storage Example:**


```java
File dir = getFilesDir();
File[] files = dir.listFiles();
for (File file : files) {
Log.d("Files", "File name: " + file.getName());
}
```

**External Storage Example:**


```java
File externalDir = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File[] files = externalDir.listFiles();
for (File file : files) {
Log.d("Files", "File name: " + file.getName());
}
```

#### Considerations
- **Permissions**: Writing to external storage requires the `WRITE_EXTERNAL_STORAGE`
permission in the app's manifest, and starting from Android 6.0 (API level 23), you need to
request this permission at runtime.
- **Storage Space**: Be mindful of the storage space as excessive use of internal storage
can fill up the device's available space.
- **Security**: Internal storage provides more security than external storage since it is
private to the application.

Using application-specific folders and files allows for organized and secure storage of an
app's data, ensuring that the information is properly managed and accessed as needed.

You might also like