How to Access Data or Data Folder in an Android Device?
Last Updated :
26 Feb, 2023
Android Operating System offers several storage methods to save your app data and images, audio files, docs, etc.
- App-specific storage: It only stores the data that is used by your App.
- Shared Storage: It stores files including images and documents.
- Databases: It provides a local Database for your app (for example, SQLite)
In this project, we access the data from our device's physical storage. As in real life to do something we require some permission from the legal authorities. So android also requires some permission from the user to access stored data. To read data from the EXTERNAL ST0RAGE we have to add the following code to our AndroidManifest.xml file.
In this project, we are going to access images from the gallery.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
If you want to write/save some data to your device storage then you have to add the below permission to your AndroidManifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The Code is given in Kotlin language so make sure that you select Kotlin language for your project.
Step 2: Add Permission to the AndroidManifest.xml file
Next, go to your AndroidManifest.xml file (Navigate to app > manifests > AndroidManifest.xml) and Add the Below Permission under the manifest section.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
By adding the above permission in the AndroidManifest.xml file your app will able to read/access the data from the EXTERNAL_STORAGE of your android device.
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.accessdata">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AccessData"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 3: Add buildFeatures to build.gradle (Module:app)
Since in this project we used ViewBinding so we have to set ViewBinding=True.
Navigate to Gradle Scripts > build.gradle (Module:app) and add the Below buildFeatures section under the android section in the build.gradle (Module:app).
buildFeatures {
viewBinding = true
}
Android Section
android {
compileSdk 32
defaultConfig {
applicationId "com.example.accessdata"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding = true
}
}
After adding this buildFeatures section, Sync the Project.
Step 4: Working with activity_main.xml
Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. Below is the code for the activity_main.xml file. The activity_main.xml represents the UI part of our application. It includes one ImageView and one Button. Comments are added inside the code for a better understanding of the Code.
XML
<?xml version="1.0" encoding="utf-8"?>
<!-- Here we use ConstraintLayout -->
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
tools:context=".MainActivity">
<!-- ImageView for displaying the image that you select from the gallery -->
<ImageView
android:id="@+id/background"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="100dp"
android:background="@color/white"
app:layout_constraintBottom_toTopOf="@id/btn_access"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<!-- Button on which we apply OnClickListener to opening the gallery -->
<Button
android:id="@+id/btn_access"
android:layout_width="200dp"
android:layout_height="50dp"
android:text="Access Images"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/background" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 5: Change the StatusBar Color
Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.
<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>
Step 6: Working with the MainActivity File
In the MainActivity file, we implement all our functionality like requesting permission from the user, opening the gallery, applying OnClickListener to the Button, and displaying the selected image from the gallery. Go to the MainActivity File (Navigate to app > java > YourPackageName > MainActivity) and follow the below code. Comments are added inside the code for a better understanding of the Code.
Kotlin
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.example.accessdata.databinding.ActivityMainBinding
// In this project we used VIEW BINDING
class MainActivity : AppCompatActivity() {
private var binding: ActivityMainBinding? = null
// creating an variable for view binding it create an activity
// result launcher to open an intent i.e. To Open Gallery
val openGallery: ActivityResultLauncher<Intent> = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) { result ->
// Here we get the result return from the lambda function get the returned result from the
// lambda and check the result code and the data returned and check the result code as
// (result.resultCode==RESULT_OK) and check the data to be not null (result.data!=null)
if (result.resultCode === RESULT_OK && result.data != null) {
binding?.background?.setImageURI(result.data?.data)
}
}
// Here we create an ActivityResultLauncher with MultiplePermissions so we can request for
// multiple permission like location storage etc For this project we use only storage permission
private val requestPermission: ActivityResultLauncher<Array<String>> = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
// Here it returns a Map of permission name as key with boolean as value
// we have to loop through the MAP and get the value i,e MAP<String,Boolean>
permissions.entries.forEach() {
// ig the intent launcher here we created above launch the pick intent
// i.e. Opening gallery openGallery.key gives us the name of the permission
val permissionName = it.key
// Here it store whether our permission granted or not in boolean value i,e: True or False
val isGranted = it.value
// if permission is granted show a toast and perform operation i,e; ACCESSING THE GALLERY
if (isGranted) {
Toast.makeText(this, "Permission is granted for accessing gallery", Toast.LENGTH_LONG).show()
// Here we create an intent to pick image from external storage
var intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
// it will gives the image path by using .launch(intent)
} else {
// Here we use array of permission so we have to check whether the specific permission is granted or not
if (permissionName == android.Manifest.permission.READ_EXTERNAL_STORAGE) {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_LONG).show()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
// set the content view by view binding applying OnClickListener to the Access Images Button
binding?.btnAccess?.setOnClickListener {
requestStoragePermission()
}
}
// It Shows rationale dialog for displaying why the app needs permission
// Only shown if the user has denied the permission request previously
private fun showRationaleDialog(title: String, message: String) {
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle(title).setMessage(message).setPositiveButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
builder.create().show()
}
// Here we create a method to request Storage permission
private fun requestStoragePermission() {
// Here we Check if the permission was denied and show rationale
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Here We call the rationale dialog to tell the user why they need to allow permission request
showRationaleDialog("Drawing App", "Drawing app needs to access your external storage")
} else {
// Here we can add multiple permission but for this project only add storage permission
// to access the data i,e:android.Manifest.permission.READ_EXTERNAL_STORAGE since it is
// an array of permission you can add multiple permission as per your requirements
requestPermission.launch(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE))
}
}
}
Java
import android.content.Intent;
import android.provider.MediaStore;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
public class MainActivity extends AppCompatActivity {
//ActivityResultLauncher to open the gallery
private ActivityResultLauncher<Intent> openGallery = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
//Check if result is OK and data is not null
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
binding.getBackground().setImageURI(result.getData().getData());
}
});
//ActivityResultLauncher to request permission
private ActivityResultLauncher<String[]> requestPermission = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> {
//Iterate through the permissions to check if they are granted
for (Map.Entry<String, Boolean> entry : permissions.entrySet()) {
String permissionName = entry.getKey();
boolean isGranted = entry.getValue();
if (isGranted) {
Toast.makeText(this, "Permission is granted for accessing gallery", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
openGallery.launch(intent);
} else {
if (permissionName.equals(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_LONG).show();
}
}
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Inflate the activity's layout
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//Set onClickListener for button to request storage permission
binding.getBtnAccess().setOnClickListener(v -> requestStoragePermission());
}
//Show rationale dialog if permission is denied
private void showRationaleDialog(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title).setMessage(message).setPositiveButton("Cancel", (dialog, which) -> dialog.dismiss());
builder.create().show();
}
//Request storage permission
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
showRationaleDialog("Drawing App", "Drawing app needs to access your external storage");
} else {
requestPermission.launch(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE});
}
}
}
Output:
Similar Reads
How to Access Content of Google Drive in Android?
In certain cases, while uploading files we may require to upload files from our google drive or it may happen that we want to give certain folder access of our google drive to users of our case. Like in the case of providing courses or study material that we have stored in our google drive. Here we
3 min read
How to Access SQLite Database in Android For Debugging?
A software library that provides a relational database management system is called SQLite. It allows the users to interact with RDBMS. The lite in SQLite denotes the lightweight when it comes to setup, database administration, and resources required. In SQLite, a database is stored in a single file
10 min read
How to Read Data from Realm Database in Android?
In the previous article, we have seen adding data to the realm database in Android. In this article, we will take a look at reading this data from our Realm Database in the Android app. What we are going to build in this article? In this article, we will be simply adding a Button to open a new act
8 min read
How to Read Data from SQLite Database in Android?
In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in RecyclerView. What we are going to
12 min read
How to Extract Data from PDF file in Android?
PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the
4 min read
How to Create and Add Data to SQLite Database in Android?
SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app. This is a series of 4 ar
8 min read
How to Delete Data from Firebase Realtime Database in Android?
In this article, we will see How to Delete added data inside our Firebase Realtime Database. So we will move towards the implementation of this deleting data in Android Firebase. Â What we are going to build in this article? Â We will be showing a simple AlertBox when the user long clicks on the ite
4 min read
How to Add Data to Back4App Database in Android?
Prerequisite: How to Connect Android App with Back4App? Back4App is an online database providing platform that provides us services with which we can manage the data of our app inside the database. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update,
4 min read
How to Access and Manage iCloud on Any Device
How to Access and Manage iCloud on Any DeviceYou can access important files, papers, and pictures on your Mac, iPhone, or iPad from anywhere. The easiest way to prove that you are who you say you are is by using the Apple ID as a way to set up iCloud. This perfect link lets you send and get any pict
6 min read
How to Debug Database in Android?
The Android Debug Database library is a useful tool for troubleshooting databases and shared preferences in Android apps. In this article we would be looking forward to using this library and get our hand on it, so continue reading, and indulge. First thing's first, What's Exactly an Android Debug D
3 min read