Wednesday 2 August 2017

Save File in External Storage in Android


There are two categories of files we might save in External Storage.

1.) Public files→Files that are freely available to other app and user.When the user uninstalls app these files should remain available to the user.
2.) Private files→Files that rightfully belong to the app and should be deleted when user uninstall your app.

To save the public file in external storage we need a method getExternalStoragePublicDirectory() method.e file
To save the private file in external storage we need method getExternalFilesDir().
Here we are dealing with external storage.To work with external storage we need permission.

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

This permission is required to read or write date from external storage.This permission is placed in AndroidManifest.xml.I give you the example as mention below.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hp.publicfileexternalstorage">
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>




Step 1: -Write code in activity_main.xml to design your layout.                                                      

activity_main.xml                                                                                                                            
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.example.hp.publicfileexternalstorage.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/entername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/save"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SAVE"
            android:onClick="savedata"/>
        <Button

            android:id="@+id/retreive"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="RETRIEVE"
            android:onClick="retreivdata"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/display"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="15sp"/>
    </LinearLayout>


</LinearLayout>


Step 2: -Type code in MainActivity.xml to save the file in External storage.

MainActivity.xml
package com.example.hp.publicfileexternalstorage;

import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

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;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG=MainActivity.class.getSimpleName();
    TextView display;
    File file;
    File file1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(LOG_TAG,"create");
        display=(TextView)findViewById(R.id.display);
        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "file"); //To save public file in external storage;
        file = new File(getExternalFilesDir("MyDocument"), "appfile.txt"); //To save private file in external storage;      
 if (!file.mkdir()) {
            Log.e(LOG_TAG,"Directory not created");
        }else{
            Log.e(LOG_TAG,"Directory created");
        }

    }
    public void savedata(View view){
         file1=new File(file,"Mytext.txt");
        EditText name=(EditText)findViewById(R.id.entername);
        String username=name.getText().toString();
        try {
            FileOutputStream outputStream=new FileOutputStream(file1);
            outputStream.write(username.getBytes());
            outputStream.close();
            name.setText("");

        }
        catch (FileNotFoundException e){
            e.printStackTrace();

        }

        catch (IOException e){
            e.printStackTrace();
        }

    }
    public void retreivdata(View view) {
        try {
            FileInputStream inputStream = new FileInputStream(file1);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String temp, temp1 = "";
                try {
                    while ((temp = bufferedReader.readLine()) != null)
                        temp1 += temp;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                display.setText(temp1);
                inputStream.close();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }


    }



}





No comments:

Post a Comment

Change Fragment on button click in Android

In example mention below on click of a button, we attach the desired fragment in our frame layout which was present in activity_main.xml. ...