2016年8月31日水曜日

Android Internal Storage Tutorial

1- Android Internal Storage

Android Internal Storage: A place to store private data of each application, this data is stored and used for own application. Other applications can not access it. Normally when the application is removed from Android devices, the associated data file is also removed.

Another feature when you work with files in Internal Storage, you can only work with a simple file name, can not work with a file name has the path.

Open file to write:

?

1

2

3

4

5

6

7

// Is a simple file name.

// Note!! Do not allow the path.

String simpleFileName ="note.txt";

 

 

// Open Stream to write file.

FileOutputStream out = openFileOutput(simpleFileName, MODE_PRIVATE);

You have four option for creating mode:

Mode

Description

MODE_PRIVATE

File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).

MODE_APPEND

Mode data appended to the file if it already exists.

MODE_ENABLE_WRITE_AHEAD_LOGGING

 

MODE_WORLD_READABLE

These modes are very dangerous, it's like a security hole in Android, best not to use, you can use alternative techniques such as:

  • ContentProvider
  • BroadcastReceiver
  • Service

MODE_WORLD_WRITEABLE

MODE_MULTI_PROCESS

This mode allows multiple processes can be writen to the file. However, it is recommended that you should not use this mode because it does not work on some versions of Android. You can use other techniques:

  • ContentProvider

Open file to read data:

?

1

2

3

4

5

6

// Is a simple file name.

// Note!! Do not allow the path.

String simpleFileName = "note.txt";

 

// Open stream to read file.

FileInputStream in = this.openFileInput(simpleFileName);

2- Reading and writing data to Internal Storage example

Now you can make an example of writing data to files stored in Internal Storage, and read data from this file.

Create a project named InternalStorageDemo.

The application interface:

activity_main.xml

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

<?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="org.o7planning.internalstoragedemo.MainActivity">

 

    <EditText

        android:layout_width="wrap_content"

        android:layout_height="100dp"

        android:id="@+id/editText"

        android:layout_alignParentTop="true"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true" />

 

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="120dp"

        android:id="@+id/textView"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_below="@+id/editText"

        android:layout_alignRight="@+id/editText"

        android:layout_alignEnd="@+id/editText" />

 

    <Button

        style="?android:attr/buttonStyleSmall"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Save To File"

        android:id="@+id/button_save"

        android:layout_below="@+id/textView"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_marginLeft="43dp"

        android:layout_marginStart="43dp"

        android:layout_marginTop="63dp" />

 

    <Button

        style="?android:attr/buttonStyleSmall"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Read File"

        android:id="@+id/button_read"

        android:layout_alignTop="@+id/button_save"

        android:layout_toRightOf="@+id/button_save"

        android:layout_toEndOf="@+id/button_save" />

    

</RelativeLayout>

MainActivity.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

package org.o7planning.internalstoragedemo;

 

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

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.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStreamReader;

 

public class MainActivity extends AppCompatActivity {

 

    private Button saveButton;

    private Button readButton;

 

    private TextView textView;

    private EditText editText;

 

    // Is a simple file name.

    // Note!! Do not allow the path.

    private String simpleFileName = "note.txt";

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        this.saveButton = (Button) this.findViewById(R.id.button_save);

        this.readButton = (Button) this.findViewById(R.id.button_read);

        this.textView = (TextView) this.findViewById(R.id.textView);

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

 

        this.saveButton.setOnClickListener(new Button.OnClickListener() {

 

            @Override

            public void onClick(View v) {

                saveData();

            }

        });

 

        this.readButton.setOnClickListener(new Button.OnClickListener() {

 

            @Override

            public void onClick(View v) {

                readData();

            }

        });

    }

 

 

    private void saveData() {

        String data = this.editText.getText().toString();

        try {

            // Open Stream to write file.

            FileOutputStream out = this.openFileOutput(simpleFileName, MODE_PRIVATE);

            // Ghi d liu.

            out.write(data.getBytes());

            out.close();

            Toast.makeText(this,"File saved!",Toast.LENGTH_SHORT).show();

        } catch (Exception e) {

            Toast.makeText(this,"Error:"+ e.getMessage(),Toast.LENGTH_SHORT).show();

        }

    }

 

    private void readData() {

        try {

            // Open stream to read file.

            FileInputStream in = this.openFileInput(simpleFileName);

 

            BufferedReader br= new BufferedReader(new InputStreamReader(in));

 

            StringBuilder sb= new StringBuilder();

            String s= null;

            while((s= br.readLine())!= null)  {

                sb.append(s).append("\n");

            }

            this.textView.setText(sb.toString());

 

        } catch (Exception e) {

            Toast.makeText(this,"Error:"+ e.getMessage(),Toast.LENGTH_SHORT).show();

        }

    }

 

}

Running app:

Use the "Android Device Manager" you can see the file is created.

See more about "Android Device Manager":

·         http://o7planning.org/en/10537/android-device-manager-tutorial

 

0 件のコメント:

コメントを投稿