Reading Writing Image Files in Android Studio

Android external storage can be used to write and save data, read configuration files etc. This article is continuation of the Android Internal Storage tutorial in the series of tutorials on structured information storage in android.

Android External Storage

External storage such as SD card can also shop awarding information, there's no security enforced upon files y'all salvage to the external storage.
In general there are two types of External Storage:

  • Primary External Storage: In built shared storage which is "accessible past the user by plugging in a USB cable and mounting it as a drive on a host computer". Case: When nosotros say Nexus 5 32 GB.
  • Secondary External Storage: Removable storage. Example: SD Carte

All applications tin can read and write files placed on the external storage and the user can remove them. We demand to check if the SD carte du jour is available and if we can write to it. Once we've checked that the external storage is available merely and then we tin can write to it else the salvage push button would be disabled.

Android External Storage Example Project Structure

android external storage

Firstly, we need to make sure that the application has permission to read and write data to the users SD card, so lets open up up the AndroidManifest.xml and add together the post-obit permissions:

                                  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:proper noun="android.permission.READ_EXTERNAL_STORAGE"/>                              

Also, external storage may be tied up by the user having mounted it every bit a USB storage device. So we need to cheque if the external storage is available and is not read only.

                                  if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {      saveButton.setEnabled(false);   }    individual static boolean isExternalStorageReadOnly() {     String extStorageState = Environment.getExternalStorageState();     if (Surroundings.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {      return true;     }     return simulated;    }      private static boolean isExternalStorageAvailable() {     String extStorageState = Environment.getExternalStorageState();     if (Environs.MEDIA_MOUNTED.equals(extStorageState)) {      render true;     }     return imitation;    }                              

getExternalStorageState() is a static method of Environment to determine if external storage is presently bachelor or non. As you can see if the condition is false nosotros've disabled the salvage push button.

Android External Storage Example Lawmaking

The activity_main.xml layout is divers as follows:

                                  <?xml version="i.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"     android:layout_width="fill_parent" android:layout_height="fill_parent"     android:orientation="vertical">      <TextView android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="Reading and Writing to External Storage"         android:textSize="24sp"/>      <EditText android:id="@+id/myInputText"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:ems="x" android:lines="five"         android:minLines="3" android:gravity="top|left"         android:inputType="textMultiLine">          <requestFocus />     </EditText>      <LinearLayout     android:layout_width="match_parent" android:layout_height="wrap_content"     android:orientation="horizontal"         android:weightSum="1.0"         android:layout_marginTop="20dp">      <Button android:id="@+id/saveExternalStorage"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Save"         android:layout_weight="0.v"/>      <Push button android:id="@+id/getExternalStorage"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_weight="0.v"         android:text="READ" />      </LinearLayout>      <TextView android:id="@+id/response"         android:layout_width="wrap_content"         android:layout_height="wrap_content" android:padding="5dp"         android:text=""         android:textAppearance="?android:attr/textAppearanceMedium" />  </LinearLayout>                              

Hither apart from the save and read from external storage buttons nosotros display the response of saving/reading to/from an external storage in a textview dissimilar in the previous tutorial where android toast was displayed.

The MainActivity.java course is given beneath:

                                  package com.journaldev.externalstorage;  import coffee.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import coffee.io.FileInputStream; import coffee.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import android.os.Bundle; import android.app.Activity; import android.bone.Surroundings; import android.view.View; import android.view.View.OnClickListener; import android.widget.Push; import android.widget.EditText; import android.widget.TextView;   public class MainActivity extends Activity {     EditText inputText;     TextView response;     Button saveButton,readButton;      private String filename = "SampleFile.txt";     private String filepath = "MyFileStorage";     File myExternalFile;     Cord myData = "";      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          inputText = (EditText) findViewById(R.id.myInputText);         response = (TextView) findViewById(R.id.response);            saveButton =                 (Button) findViewById(R.id.saveExternalStorage);         saveButton.setOnClickListener(new OnClickListener() {             @Override             public void onClick(View 5) {                 try {                     FileOutputStream fos = new FileOutputStream(myExternalFile);                     fos.write(inputText.getText().toString().getBytes());                     fos.close();                 } take hold of (IOException eastward) {                     e.printStackTrace();                 }                 inputText.setText("");                 response.setText("SampleFile.txt saved to External Storage...");             }         });          readButton = (Push button) findViewById(R.id.getExternalStorage);         readButton.setOnClickListener(new OnClickListener() {             @Override             public void onClick(View five) {                 try {                     FileInputStream fis = new FileInputStream(myExternalFile);                     DataInputStream in = new DataInputStream(fis);                     BufferedReader br =                             new BufferedReader(new InputStreamReader(in));                     String strLine;                     while ((strLine = br.readLine()) != cypher) {                         myData = myData + strLine;                     }                     in.close();                 } catch (IOException e) {                     due east.printStackTrace();                 }                 inputText.setText(myData);                 response.setText("SampleFile.txt data retrieved from Internal Storage...");             }         });          if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {             saveButton.setEnabled(false);         }         else {             myExternalFile = new File(getExternalFilesDir(filepath), filename);         }       }     private static boolean isExternalStorageReadOnly() {         Cord extStorageState = Environment.getExternalStorageState();         if (Environs.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {             render true;         }         return fake;     }      private static boolean isExternalStorageAvailable() {         String extStorageState = Environment.getExternalStorageState();         if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {             return truthful;         }         return simulated;     }   }                              
  1. Environment.getExternalStorageState(): returns path to internal SD mount point like "/mnt/sdcard"
  2. getExternalFilesDir(): It returns the path to files binder inside Android/information/data/application_package/ on the SD card. It is used to store whatever required files for your app (similar images downloaded from web or enshroud files). One time the app is uninstalled, any information stored in this folder is gone too.

As well if the external storage is not available we disable the salve button using the if condition that was discussed earlier in this tutorial.

Below is our application running in android emulator, where we are writing information to file and and so reading it.

android external storage example read write save file

Annotation: Make certain your Android Emulator is configured such that it has a SD card as shown in the image dialog from AVD below. Become to Tools->Android->Android Virtual Device, edit configurations->Testify Advance Settings.

android external storage config, android save file to external storage

This brings an end to this tutorial. We'll hash out storage using Shared Preferences in the next tutorial. You can download the concluding Android External Storage Project from the below link.

ramirezthred1974.blogspot.com

Source: https://www.journaldev.com/9400/android-external-storage-read-write-save-file

0 Response to "Reading Writing Image Files in Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel