Share your knowledge

Saturday 11 March 2017

Android External Storage

There are several ways(Shared preferences, Internal storage, External storage, SQLite) to save data in android. Here we will discuss about Internal Storage.

Here is our final output:





Here you can download the source code: download

External storage is used to write and read data. User has a permission to access these files at anytime.

Primary External Storage: Inbuilt shared storage

Second External Storage: Removable storage (Ex: SD Card)

1. Open AndroidManifest.xml and below two permissions


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


2. Open activity_main.xml and paste below code:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.externalstorage.MainActivity">


    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fontFamily="monospace"
        android:hint="Write some data here..."
        android:paddingLeft="10dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/file_path"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:padding="10dp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/file_path"
        android:gravity="center">

        <Button
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="save" />

        <Button
            android:id="@+id/read"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/save"
            android:text="read" />

    </RelativeLayout>


</RelativeLayout>



3. Open MainActivity.java and paste below code



package com.externalstorage;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

    private EditText data;
    private Button save, read;
    private TextView filePathTextView;

    private String fileName = "noteFile.txt";
    private String filePath = "myStore";
    private File noteFile;
    private StringBuilder dataBuilder = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        data = (EditText) findViewById(R.id.editText);

        save = (Button) findViewById(R.id.save);
        read = (Button) findViewById(R.id.read);

        filePathTextView = (TextView) findViewById(R.id.file_path);


        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (data.getText().toString().length()>0){
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(noteFile);

                        fileOutputStream.write(data.getText().toString().getBytes());

                        fileOutputStream.close();
                    }
                    catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }

                    filePathTextView.setText("");
                    filePathTextView.setText("noteFile.txt file saved to external storage");

                }
                else{
                    Toast.makeText(MainActivity.this,"Enter some data",Toast.LENGTH_SHORT).show();
                }


            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    FileInputStream fileInputStream = new FileInputStream(noteFile);

                    //creating instance of DataInputStream
                    DataInputStream dataInputStream = new DataInputStream(fileInputStream);

                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));
                    String line;

                    while ((line=bufferedReader.readLine())!=null){
                        dataBuilder.append(line);
                    }

                    fileInputStream.close();
                }
                catch (FileNotFoundException e){
                    e.printStackTrace();
                }
                catch (IOException e){
                    e.printStackTrace();
                }

                filePathTextView.setText("");
                filePathTextView.setText("noteFile.txt data recieved from external storage");

                data.setText(dataBuilder.toString());
            }
        });


        //checking whether external storage is avialble or not
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            //external storage is not available and is not writable, so we are making save button as not clickable

            save.setEnabled(false);
        } else {

            //if external storage is avilable and is writable
            noteFile = new File(getExternalFilesDir(filePath),fileName);
        }
    }

    private static boolean isExternalStorageAvailable() {

        /**
         * Returns the current state of the primary shared/external storage media.
         *
         * @see #getExternalStorageDirectory()
         * @return one of {@link #MEDIA_UNKNOWN}, {@link #MEDIA_REMOVED},
         *         {@link #MEDIA_UNMOUNTED}, {@link #MEDIA_CHECKING},
         *         {@link #MEDIA_NOFS}, {@link #MEDIA_MOUNTED},
         *         {@link #MEDIA_MOUNTED_READ_ONLY}, {@link #MEDIA_SHARED},
         *         {@link #MEDIA_BAD_REMOVAL}, or {@link #MEDIA_UNMOUNTABLE}.
         */
        String exeStoragestate = Environment.getExternalStorageState();

        if (exeStoragestate.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageReadOnly() {
        //if storage is only for read, then we can't do any write operations

        String exeStorageState = Environment.getExternalStorageState();

        if (exeStorageState.equalsIgnoreCase(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return true;
        }
        return false;
    }
}


No comments:

Post a Comment