Open In App

How to Access Data or Data Folder in an Android Device?

Improve
Improve
Like Article
Like
Save
Share
Report

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"?>
    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: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:



Last Updated : 26 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads