UNIT-4(MAD)
1) how to access files in android? explain using application specific
folders to store files
ANS) Accessing files in Android typically involves using the device's storage system. Android provides
several options for storing files, including internal storage, external storage (such as an SD card), and
specific directories for different types of files. Here, we'll focus on using application-specific folders to
store files.
Internal Storage
Internal storage is private to the application, meaning other applications cannot access it. It's a
good place to store sensitive data. Files stored here are deleted when the application is
uninstalled.
Storing Files in Internal Storage
To store a file in internal storage, you can use the following methods:
1. [Link](): Returns a File object representing the internal storage directory.
2. [Link](): Opens a file output stream to write to a file in the internal
storage.
Reading Files from Internal Storage
To read a file from internal storage, use the following methods:
1. [Link](): Opens a file input stream to read from a file in the internal
storage.
External Storage
External storage can be public or private to the application. Public files can be accessed by
other applications, while private files are only accessible by the application that created them.
Note that accessing external storage requires permissions.
Storing Files in External Storage
To store files in external storage, you need to check if the storage is available and writable. Use
the following methods:
1. [Link](): Returns a File object representing the external storage
directory specific to the application.
2. Reading Files from External Storage
3. To read files from external storage, ensure you have the necessary permissions and use the
following methods:
Application-Specific Folders
Application-specific folders are directories within the internal or external storage dedicated to
your application. These folders ensure that files are separated from other applications' files and
are deleted when the application is uninstalled.
Internal Application-Specific Folders
Files Directory: Use [Link]() to get the directory.
Cache Directory: Use [Link]() for cache files.
External Application-Specific Folders
Files Directory: Use [Link](String type) for external storage.
Cache Directory: Use [Link]() for external cache.
Using these application-specific folders is crucial for managing your app's data efficiently and
securely, ensuring that files are only accessible by your application and are appropriately
cleaned up when the app is uninstalled.
2) how to create file in andriod application
ans) Steps to Create a File in Android:
1. Add Permissions:
o If you're working with external storage, add the necessary permissions in the
[Link] file.
<uses-permission android:name="[Link].WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="[Link].READ_EXTERNAL_STORAGE" />
[Link] Storage Location:
Decide if you want to use internal or external storage. Internal storage is private to your
app, while external storage is shared.
3. Write Data to a File:
Internal Storage:
1. Open a file output stream.
2. Write data to the file.
3. Close the file output stream
String filename = "[Link]";
String fileContents = "Hello, World!";
try (FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE)) {
[Link]([Link]());
} catch (IOException e) {
[Link]();
}
External Storage:
1. Check if the external storage is writable.
2. Get the external storage directory.
3. Create a new file in the directory.
4. Write data to the file.
5. Close the file output stream
if (isExternalStorageWritable()) {
File file = new File(getExternalFilesDir(null), "[Link]");
try (FileOutputStream fos = new FileOutputStream(file)) {
[Link]([Link]());
} catch (IOException e) {
[Link]();
}
}
// Helper method to check if external storage is writable
public boolean isExternalStorageWritable() {
String state = [Link]();
return Environment.MEDIA_MOUNTED.equals(state);
}
Syntax to Remember:
Internal Storage:
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
[Link]([Link]());
[Link]();
External Storage:
File file = new File(getExternalFilesDir(null), "[Link]");
FileOutputStream fos = new FileOutputStream(file);
[Link]([Link]());
[Link]();
Summary:
1. Permissions (for external storage).
2. Choose Storage Location (internal or external).
3. Write Data:
o For internal: openFileOutput().
o For external: Check writable, getExternalFilesDir(), create File, write using
FileOutputStream.
3)read data from files in android
Procedure to Read Data from Files
1. Internal Storage
Steps:
1. Open the File: Use `openFileInput()` method to access the file.
2. Read the Data: Use `FileInputStream` and `BufferedReader` to read the file contents.
3. Close Streams: Ensure to close the input streams to free resources.
2. External Storage
Steps:
1. **Check Permissions**: Ensure you have permission to read external storage.
2. **Check Storage Readable**: Verify if external storage is readable.
3. **Open the File**: Use `FileInputStream` to access the file.
4. **Read the Data**: Use `InputStreamReader` and `BufferedReader` to read the file contents.
5. **Close Streams**: Close the input streams after reading.
Summary:
1. **Internal Storage**:
- Use `openFileInput("[Link]")`
- Read with `FileInputStream` + `BufferedReader`
- Close streams with `try-with-resources` or manually
2. **External Storage**:
- Check for permission and readability
- Use `new File(getExternalFilesDir(null), "[Link]")`
- Read with `FileInputStream` + `BufferedReader`
- Close streams with `try-with-resources` or manually
These steps provide a clear and concise procedure to read data from files in both internal and external
storage in Android.
4)shared preferences – creating, saving, and retrieving data using shared
preferences in android
Ans) Shared Preferences in Android is a lightweight mechanism for storing key-value pairs of primitive data
types. It is primarily used to save user preferences or application settings. The data stored in Shared
Preferences persists across user sessions, making it a suitable choice for saving small amounts of data.
1. Setting Up Shared Preferences
To use Shared Preferences in your Android application, you first need to obtain an instance of the
SharedPreferences class. This can be done using the getSharedPreferences() method or getPreferences()
method.
Using getSharedPreferences(): This method allows you to specify a name for your preferences file
and the mode (e.g., private or public).
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Using getPreferences(): This method is simpler and is typically used when you want to store
preferences specific to an activity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
2. Saving Data in Shared Preferences
Once you have the SharedPreferences instance, you can save data using the Editor interface. Here’s how to
do it step by step:
1. Obtain an Editor Instance: Call edit() on your SharedPreferences object.
2. Put Data: Use methods like putString(), putInt(), etc., to store data.
3. Commit Changes: Finally, call either apply() or commit() to save the changes.
Here’s an example of saving different types of data:
// Step 1: Obtain an Editor instance
[Link] editor = [Link]();
// Step 2: Put data
[Link]("username", "JohnDoe");
[Link]("userAge", 30);
[Link]("isPremiumUser", true);
// Step 3: Commit changes
[Link](); // or [Link]();
Common Methods:
putString(String key, String value)
putInt(String key, int value)
putBoolean(String key, boolean value)
putFloat(String key, float value)
putLong(String key, long value)
putStringSet(String key, Set<String> values)
Applying Changes:
apply(): Asynchronously saves changes.
commit(): Synchronously saves changes.
3. Retrieving Data from Shared Preferences
Retrieving data from Shared Preferences is straightforward as well. You can use various getter methods
provided by the SharedPreferences class:
1. Get Data: Use methods like getString(), getInt(), etc., specifying a default value that will be returned
if the key does not exist.
Here’s how you can retrieve the previously saved values:
// Retrieve data
String username = [Link]("username", "defaultUser");
int userAge = [Link]("userAge", 0);
boolean isPremiumUser = [Link]("isPremiumUser", false);
// Use retrieved values
Log.d("TAG", "Username: " + username);
Log.d("TAG", "User Age: " + userAge);
Log.d("TAG", "Is Premium User: " + isPremiumUser);
Common Methods:
getString(String key, String defaultValue)
getInt(String key, int defaultValue)
getBoolean(String key, boolean defaultValue)
getFloat(String key, float defaultValue)
getLong(String key, long defaultValue)
getStringSet(String key, Set<String> defaultValues)
4. Removing Data from Shared Preferences
If you need to remove a specific entry from Shared Preferences, you can do so using the remove() method
followed by applying or committing changes:
// Remove specific entry
[Link]("username");
[Link](); // or [Link]();
5. Clearing All Data from Shared Preferences
To clear all entries in your Shared Preferences file, use the clear() method:
// Clear all entries
[Link]();
[Link](); // or [Link]();
6. Best Practices
Always use apply() instead of commit() unless you need synchronous saving because apply() saves
changes in memory immediately but writes them to disk asynchronously.
Use meaningful keys for your preferences to avoid conflicts and make your code more readable.
Consider using encryption if you’re storing sensitive information.