Android – Read/Write to External Storage

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 5 Overview Overview of Networking Programming Tutorial 2: Downloading from the Internet.
Advertisements

Getting Started with Android APIs Ivan Wong. Motivation - “Datasheet” - Recently exposed to what’s available in Android - So let’s see what API’s are.
Package org.androidtown.database.query; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
Social Media Apps Programming Min-Yuh Day, Ph.D. Assistant Professor Department of Information Management Tamkang University
1/29/ Android Programming: FrameLayout By Dr. Ramji M. Makwana Professor and Head, Computer Engineering Department A.D. Patel.
Android - Broadcast Receivers
Networking: Part 1 (Web Content). Networking with Android Android provides A full-featured web browser based on Chromium, the open source browser engine.
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
Mobile Device Development Camera and Sensors Dr.YingLiang Ma.
Android ImageView and Splash Screen 1. After copying an image file (Ctrl-c or right click copy), right click and paste it into one of the res/drawable.
Android 基本 I/O. 基本 I/O 介面元件 在此節中主要介紹常見的 I/O 使用者介 面元件 – Button, TextView, 以及 EditText , 學習者可以學會: – Android 的視窗表單設計 res/layout/main.xml – Android SDK –
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Mobile Software Development for Android - I397
Lab7 – Appendix.
Lab7 – Advanced.
several communicating screens
GUI Programming Fundamentals
Android -By Yogita Nirmal.
Android Dr. Vaishali D. Khairnar IT Department
Android 5: Assignment 1, First Half, Arithmetic Operations and Exceptions.
Android Widgets 1 7 August 2018
Android 7: Assignment 2, Part 1, One Button Recursion and Debugging
Picasso Revisted.
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CS323 Android Model-View-Controller Architecture
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
Android Sensor Programming
CMPE419 Mobile Application Development
Android Persistency: Files
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
BMI Android Application will take weight and height from the users to calculate Body Mass Index (BMI) with the information, whether user is underweight,
CIS 470 Mobile App Development
滑動 建國科技大學 資管系 饒瑞佶.
Programski jezici za mobilne aplikacije
CIS 470 Mobile App Development
CIS 493/EEC 492 Android Sensor Programming
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 493/EEC 492 Android Sensor Programming
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CMPE419 Mobile Application Development
Adding Components to Activity
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
BLP 4216 MOBİL UYGULAMA GELİŞTİRME-2
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
CIS 470 Mobile App Development
Android Sensor Programming
Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
Android Sensor Programming
CIS 470 Mobile App Development
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Android – Read/Write to External Storage 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage 1

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage Android External Storage: a place to store addition data  of Android, the files that you store here is not applied the security system. Usually there are two types of external storage:  Fixed external storage: Commonly understood as the hard drive of the device. Removable  storage: Such as SD Card.  Use the static method of Environment class  you can get the information on the directory of the external storage. 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage Android External Storage The table below results running on the emulator device. To read/write the data on the external storage requires you to configureAndroidManifest.xml, added: 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

Read and write files on the external storage example AndroidManifest.xml configuration allows read and write data on the external storage memory. Full content of  AndroidManifest.xml: 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

Read and write files on the external storage example activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context=".MainActivity">  <EditText         android:id="@+id/editText"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:ems="10"         android:layout_alignParentTop="true"         android:layout_alignParentLeft="true"         android:layout_alignParentStart="true"         android:layout_alignParentRight="true"         android:layout_alignParentEnd="true">           <requestFocus />     </EditText>     <TextView         android:layout_width="fill_parent"         android:layout_height="120dp"         android:id="@+id/textView"         android:layout_below="@+id/editText"         android:layout_above="@+id/button_save"         android:layout_marginTop="10dp" />    <Button         android:id="@+id/button_save"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="save"         android:layout_alignParentBottom="true"         android:layout_alignLeft="@+id/textView"         android:layout_alignStart="@+id/textView" />       <Button         android:id="@+id/button_read"         android:layout_alignBaseline="@+id/button_save"         android:layout_alignBottom="@+id/button_save"         android:layout_toRightOf="@+id/button_save"         android:text="read" />         style="?android:attr/buttonStyleSmall"         android:text="List Dirs"         android:id="@+id/button_list"         android:layout_alignBottom="@+id/button_read"         android:layout_toRightOf="@+id/button_read"         android:layout_toEndOf="@+id/button_read" /> </RelativeLayout> 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

Read and write files on the external storage example public class MainActivity extends Activity {    private EditText editText;    private TextView textView;    private Button saveButton;    private Button readButton;    private Button listButton;       private static final int REQUEST_ID_READ_PERMISSION = 100;    private static final int REQUEST_ID_WRITE_PERMISSION = 200;      private final String fileName = "note.txt";     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        editText = (EditText) findViewById(R.id.editText);        textView = (TextView) findViewById(R.id.textView);        saveButton = (Button) findViewById(R.id.button_save);        readButton = (Button) findViewById(R.id.button_read);        listButton = (Button) findViewById(R.id.button_list);        saveButton.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View arg0) {                askPermissionAndWriteFile();            }        }); MainActivity.java import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;   import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage MainActivity.java  Contd readButton.setOnClickListener(new OnClickListener() {              @Override            public void onClick(View arg0) {                askPermissionAndReadFile();            }        });        listButton.setOnClickListener(new OnClickListener() {                listExternalStorages();    }    private void askPermissionAndWriteFile() {        boolean canWrite = this.askPermission(REQUEST_ID_WRITE_PERMISSION,                Manifest.permission.WRITE_EXTERNAL_STORAGE);        //        if (canWrite) {            this.writeFile();        }    }      private void askPermissionAndReadFile() {        boolean canRead = this.askPermission(REQUEST_ID_READ_PERMISSION,                Manifest.permission.READ_EXTERNAL_STORAGE);        if (canRead) {            this.readFile(); 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage    // When you have the request results MainActivity.java  Contd   @Override    public void onRequestPermissionsResult(int requestCode,                                           String permissions[], int[] grantResults) {          super.onRequestPermissionsResult(requestCode, permissions, grantResults);        //        // Note: If request is cancelled, the result arrays are empty.        if (grantResults.length > 0) {            switch (requestCode) {                case REQUEST_ID_READ_PERMISSION: {                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {                        readFile();                    }                }                case REQUEST_ID_WRITE_PERMISSION: {                        writeFile();            }        } else {            Toast.makeText(getApplicationContext(), "Permission Cancelled!", Toast.LENGTH_SHORT).show();        }    }  // With Android Level >= 23, you have to ask the user    // for permission with device (For example read/write data on the device). private boolean askPermission(int requestId, String permissionName) {        if (android.os.Build.VERSION.SDK_INT >= 23) {              // Check if we have permission            int permission = ActivityCompat.checkSelfPermission(this, permissionName);            if (permission != PackageManager.PERMISSION_GRANTED) {                // If don't have permission so prompt the user.                this.requestPermissions(                        new String[]{permissionName},                        requestId                );                return false;            }        }        return true;    } 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage MainActivity.java  Contd private void writeFile() {            File extStore = Environment.getExternalStorageDirectory();        // ==> /storage/emulated/0/note.txt        String path = extStore.getAbsolutePath() + "/" + fileName;        Log.i("ExternalStorageDemo", "Save to: " + path);          String data = editText.getText().toString();        try {            File myFile = new File(path);            myFile.createNewFile();            FileOutputStream fOut = new FileOutputStream(myFile);            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);            myOutWriter.append(data);            myOutWriter.close();            fOut.close();            Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();        } catch (Exception e) {            e.printStackTrace();        }    }  private void readFile() {            File extStore = Environment.getExternalStorageDirectory();        // ==> /storage/emulated/0/note.txt        String path = extStore.getAbsolutePath() + "/" + fileName;        Log.i("ExternalStorageDemo", "Read file: " + path);          String s = "";        String fileContent = "";        try {            File myFile = new File(path);            FileInputStream fIn = new FileInputStream(myFile);            BufferedReader myReader = new BufferedReader(                    new InputStreamReader(fIn));            while ((s = myReader.readLine()) != null) {                fileContent += s + "\n";            }            myReader.close();            this.textView.setText(fileContent);        } catch (IOException e) {            e.printStackTrace();        }        Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();    } 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage    private void listExternalStorages() {        StringBuilder sb = new StringBuilder();         sb.append("Data Directory: ").append("\n - ")                .append(Environment.getDataDirectory().toString()).append("\n");         sb.append("Download Cache Directory: ").append("\n - ")                .append(Environment.getDownloadCacheDirectory().toString()).append("\n");         sb.append("External Storage State: ").append("\n - ")                .append(Environment.getExternalStorageState().toString()).append("\n");         sb.append("External Storage Directory: ").append("\n - ")                .append(Environment.getExternalStorageDirectory().toString()).append("\n");         sb.append("Is External Storage Emulated?: ").append("\n - ")                .append(Environment.isExternalStorageEmulated()).append("\n");         sb.append("Is External Storage Removable?: ").append("\n - ")                .append(Environment.isExternalStorageRemovable()).append("\n");         sb.append("External Storage Public Directory (Music): ").append("\n - ")                .append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).toString()).append("\n");          sb.append("Download Cache Directory: ").append("\n - ")        sb.append("Root Directory: ").append("\n - ")                .append(Environment.getRootDirectory().toString()).append("\n");        Log.i("ExternalStorageDemo", sb.toString());        this.textView.setText(sb.toString());    } } MainActivity.java  Contd 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

Read and write files on the external storage example Output 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage

S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage Thank You 12 September 2018 S.RENUKADEVI/AP/SCD/ANDROID - Read/Write to External Storage