[go: up one dir, main page]

0% found this document useful (0 votes)
27 views5 pages

Chapter12-Files and Preferences - Publish

The document discusses different file storage options in Android including internal storage, external SD storage, and shared preferences. Internal storage stores private files and resources in the device's main memory. External SD storage stores public files on the external SD card. Shared preferences provide a simple way to store and retrieve primitive data in key-value pairs and are stored internally.

Uploaded by

Linh Linh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views5 pages

Chapter12-Files and Preferences - Publish

The document discusses different file storage options in Android including internal storage, external SD storage, and shared preferences. Internal storage stores private files and resources in the device's main memory. External SD storage stores public files on the external SD card. Shared preferences provide a simple way to store and retrieve primitive data in key-value pairs and are stored internally.

Uploaded by

Linh Linh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

CONTENTS

ANDROID FILES
INTERNAL STORAGE
EXTERNAL SD FILES

MOBILE DEVELOPMENT
FILES AND PREFERENCES

ANDROID FILES
(Exploring Android’s file system) ANDROID FILES
Persistence is a strategy that allows the reusing of volatile objects and other data items by Use the emulator’s File Explorer to see and manage your device’s storage structure
storing them Into a permanent storage system such as disk files and databases.
File IO management in Android includes –among others- the familiar IO Java classes: Streams,
Internal
Scanner, PrintWriter, and so on. Main Memory
Permanent files can be stored internally in the device’s main memory (usually small, but not
volatile) or externally in the much larger SD card.
Files stored in the device’s memory, share space with other application’s resources such as code, External
icons, pictures, music, etc. SD Card
Internal files are called: Resource Files or Embedded Files.

ANDROID FILES
(Choosing a persistent environment) ANDROID FILES (SHARED PREFERENCES)
Your permanent data storage destination is usually determined by parameters such as: SharedPreferences files are good for handling a handful of Items. Data in this type of container is
◦ size (small/large), saved as <Key, Value> pairs where the key is a string and its associated value must be a primitive
◦ location (internal/external), data type.
◦ accessibility (private/public). This class is functionally similar to Java Maps, however; unlike Maps they are permanent.
Depending of your situation the following options are available: Data is stored in the device’s internal main memory.
◦ 1. Shared Preferences Store private primitive data in key-value pairs.
PREFERENCES are typically used to keep state information and shared data among several
◦ 2. Internal Storage Store private data on the device’s main memory.
activities of an application.
◦ 3. External Storage Store public data on the shared external storage.
◦ 4. SQLite Databases Store structured data in a private/public database. KEY VALUE
◦ 5. Network Connection Store data on the web.
ANDROID FILES (SHARED PREFERENCES) ANDROID FILES (SHARED PREFERENCES)
Using Preferences API calls In this example the user selects a preferred ‘color’ and ‘number’. Both values are stored in a
SharedPreferences file.
Each of the Preference mutator methods carries a typed-value content that can be manipulated
by an editor that allows putXxx… and getXxx… commands to place data in and out of the KEY VALUE
Preference container. Xxx = { Long, Int, Double, Boolean, String } private void usingPreferences(){ chosenColor RED
.getXxx(key n) // Save data in a SharedPreferences container
// We need an Editor object to make preference changes. chosenNumber 7
Preference Container .getAll()
1 SharedPreferences myPrefs = getSharedPreferences(“my_preferred_choices”, Activity.MODE_PRIVATE);
.getStringSet()
SharedPreferences.Editor editor = myPrefs.edit();
KEY VALUE
E … editor.putString(“chosenColor”, “RED”);
2
D editor.putInt(“chosenNumber”, 7 );
.putXxx(key n, value n)
editor.commit();
I // retrieving data from SharedPreferences container (apply default if needed)
T .remove(key n) 3 String favoriteColor = myPrefs.getString(“chosenColor”, “BLACK”);
.clear() int favoriteNumber = myPrefs.getInt(“chosenNumber”, 11 );
O .commit() }
R

ANDROID FILES (SHARED PREFERENCES) ANDROID FILES (SHARED PREFERENCES)


1. The method getSharedPreferences(…) creates (or retrieves) a table called SharedPreference containers are saved as XML files in the application’s internal memory space.
my_preferred_choices file, using the default MODE_PRIVATE access. Under this access mode The path to a preference files is /data/data/packageName/shared_prefs/filename.
only the calling application can operate on the file.
For instance in this example we have:
2. A SharedPreferences editor is needed to make any changes on the file. For instance
editor.putString(“chosenColor”, “RED”) creates(or updates) the key “chosenColor” and assigns to
it the value “RED”. All editing actions must be explicitly committed for the file to be updated.
3. The method getXXX(…) is used to extract a value for a given key. If no key exists for the
supplied name, the method uses the designated default value. For instance
myPrefs.getString(“chosenColor”, “BLACK”) looks into the file myPrefs for the key “chosenColor” If you pull the file from the device, you will see the following
to returns its value, however if the key is not found it returns the default value “BLACK”.

INTERNAL STORAGE
INTERNAL STORAGE (Example 1: Reading an internal resource file )
An Android application may include resource elements such as those in: res/drawable, res/raw, This app stores a text file in its RESOURCE (res/raw) folder. The embedded raw data (containing a
res/menu, res/style, etc. pamgram) is read and displayed in a text box (see previous image)
Resources could be accessed through the .getResources(…) method. The method’s argument is //reading an embedded RAW data file
public class File1Resources extends Activity {
the ID assigned by Android to the element in the R resource file. For example: TextView txtMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
InputStream is = this.getResources().openRawResource(R.raw.my_text_file); super.onCreate(savedInstanceState); setContentView(R.layout.main);
txtMsg = (TextView) findViewById(R.id.textView1);
try { PlayWithRawFiles(); }
If needed create the res/raw folder. catch (IOException e) { txtMsg.setText(“Problems: ” + e.getMessage() ); }
Use drag/drop to place the file my_text_file.txt }// onCreate
in res folder. It will be stored in the device’s public void PlayWithRawFiles() throws IOException {
String str=“”, buf = new StringBuffer();
memory as part of the .apk
1 int fileResourceId = R.raw.my_text_file;
InputStream is = this.getResources().openRawResource(fileResourceId);
2 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) { while ((str = reader.readLine()) != null) { buf.append(str + “\n” ); } }
reader.close(); is.close();
txtMsg.setText( buf.toString() );
}// PlayWithRawFiles
3

} // File1Resources

Example of a pamgram in Spanish: La cigüeña tocaba cada vez mejor el saxofón y el búho pedía whiskey y queso.
INTERNAL STORAGE INTERNAL STORAGE
(Example 1: Reading an internal resource file ) (Example 2: Reading/writing
Comments
an internal resource file)
1. A raw file is an arbitrary dataset stored in its original raw format (such as .docx, pdf, gif, jpeg, In this example an application exposes a
etc). Raw files can be accessed through an GUI on which the user enters a few lines of
data. The app collects the input lines and
InputStream acting on a R.raw.filename resource entity. CAUTION: Android requires resource file writes them to a persistent internal data
names to be in lowercase form.
file.
2. The expression getResources().openRawResource(fileResourceId) creates an InputStream
object that sends the bytes from the selected resource file to an input buffer. If the resource file Next time the application is executed
is not found it raises a NotFoundException condition. Resource File will be read and its data will
be shown on UI.
3. A BufferedReader object is responsible for extracting lines from the input buffer and
assembling a string which finally will be shown to the user in a textbox. Protocol expects that
conventional IO housekeeping operations should be issued to close the reader and stream
objects.

INTERNAL STORAGE INTERNAL STORAGE


(Example 2: Reading/writing an internal resource file) (Example 2: Reading/writing an internal resource file)
The internal resource file In our example the files notes.txt is stored in the
(notes.txt) is private and phone’s internal memory under the name: <?xml version=“1.0” encoding=“utf-8”?>
cannot be seen by other apps /data/data/com.example.myapplication/files/notes.txt <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
residing in main memory. android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:background=“#ffdddddd”
android:padding=“10dp”
android:orientation=“vertical”>
<Button android:id=“@+id/btnFinish”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:padding=“10dp”
android:text=“Save File and Close”/>
<EditText android:id=“@+id/txtMsg”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:padding=“10dp”
android:background=“#ffffffff”
android:gravity=“top”
android:hint=“Enter some lines of data here...” />
</LinearLayout>

INTERNAL STORAGE INTERNAL STORAGE


(Example 2: Reading/writing an internal resource file) (Example 2: Reading/writing an internal resource file)
public class File2WriteRead extends Activity { public void onPause() {
private final static String FILE_NAME = “notes.txt”; private EditText txtMsg; super.onPause(); Comments
@Override try {
public void onCreate(Bundle icicle) {
super.onCreate(icicle); setContentView(R.layout.main);
OutputStreamWriter out = new OutputStreamWriter( 1. The expression openFileInput(FILE_NAME) opens a private file linked to this Context's
openFileOutput(FILE_NAME, 0));
txtMsg = (EditText) findViewById(R.id.txtMsg);
// deleteFile(); //keep for debugging
out.write(txtMsg.getText().toString()); out.close(); application package for reading. This is an alternative to the method
Button btnFinish = (Button) findViewById(R.id.btnFinish); } getResources().openRawResource(fileResourceId) discussed in the previous example.
btnFinish.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); catch (Throwable t) { txtMsg.setText( t.getMessage() ); }
}// onCreate }// onPause
public void onStart() { private void deleteFile() { 2. A BufferedReader object moves data line by line from the input file to a textbox. After the
super.onStart(); String path = “/data/data/com.example.myapplication/files/” + FILE_NAME; buffer is emptied the data sources are closed.
try { File f1 = new File(path);
InputStream inputStream = openFileInput(FILE_NAME); Toast.makeText(getApplicationContext(), “Exists?” + f1.exists() , 1).show();
if (inputStream != null) { boolean success = f1.delete(); 3. An OutputStreamWriter takes the data entered by the user and send this stream to an internal
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); if (!success) Toast.makeText(getApplicationContext(), “Delete op. failed.”, 1).show();
String str = “”;
file. The method openFileOutput() opens a private file for writing and creates the file if it doesn't
else Toast.makeText(getApplicationContext(), “File deleted.”, 1).show();
StringBuffer stringBuffer = new StringBuffer();
} already exist. The file’s path is: /data/data/packageName/FileName
while ((str = reader.readLine()) != null) { stringBuffer.append(str + “\n”); }
inputStream.close(); }
txtMsg.setText(stringBuffer.toString()); 4. You may delete an existing resource file using conventional .delete() method.
}
}
catch ( Exception ex ) { Toast.makeText(CONTEXT, ex.getMessage() , 1).show(); }
}// onStart
EXTERNAL SD EXTERNAL SD FILES
FILES Use the File Explorer tool to locate files in your device (or emulator).
SD cards offer the advantage of a Look into the folder: mnt/sdcard/ there you typically keep music, pictures, videos, etc.
much larger capacity as well as
portability.
Many devices allow SD cards to be
easily removed and reused in
another device.
SD cards are ideal for keeping your
collection of music, picture,
ebooks, and video files.

EXTERNAL SD FILES
EXTERNAL SD FILES (Example 3: Reading/writing external SD files)
Although you may use the specific path to an SD file, such as: mnt/sdcard/mysdfile.txt This app accepts a few lines of user input and writes it to the external SD card. User clicks on
buttons to either have the data read and brought back, or terminate the app.
it is a better practice to determine the SD location as suggested below

String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();


WARNING
When you deal with external files you need to request permission to read and write to the SD
card. Add the following clauses to your AndroidManifest.xml

<uses-permission android:name=“android.permission.READ_EXTERNAL_STORAGE”/> Using Device


File Explorer
<uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/> to inspect the
SD card.

EXTERNAL SD FILES EXTERNAL SD FILES


(Example 3: Reading/writing external SD files) (Example 3: Reading/writing external SD files)
public class File3SdCard extends Activity {
Layout: // GUI controls
<?xml version=“1.0” encoding=“utf-8”?> private EditText txtData;
private Button btnWriteSDFile, btnReadSDFile, btnClearScreen, btnClose;
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android” android:id=“@+id/widget28” private String mySdPath;
android:padding=“10dp” android:layout_width=“match_parent” @Override
android:layout_height=“match_parent” android:orientation=“vertical”> public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.main);
<EditText android:id=“@+id/txtData” android:layout_width=“match_parent” // find SD card absolute location
android:layout_height=“180dp” android:layout_margin=“10dp” 1 mySdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
android:background=“#55dddddd” android:padding=“10dp” // bind GUI elements to local controls
txtData = (EditText) findViewById(R.id.txtData); txtData.setHint(“Enter some lines of data here...”);
android:gravity=“top” android:hint= “Enter some lines of data here...” android:textSize=“18sp” /> btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
<Button android:id=“@+id/btnWriteSDFile” android:layout_width=“160dp” btnWriteSDFile.setOnClickListener(new OnClickListener() {
android:layout_height=“wrap_content” android:text=“1. Write SD File” /> @Override
public void onClick(View v) {// WRITE on SD card file data taken from the text box
<Button android:id=“@+id/btnClearScreen” android:layout_width=“160dp” try {
android:layout_height=“wrap_content” android:text=“2. Clear Screen” /> 2 File myFile = new File(mySdPath + “/mysdfile.txt”);
<Button android:id=“@+id/btnReadSDFile” android:layout_width=“160dp” OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(myFile));
android:layout_height=“wrap_content” android:text=“3. Read SD File” /> myOutWriter.append(txtData.getText()); myOutWriter.close();
Toast.makeText(getBaseContext(), “Done writing SD ‘mysdfile.txt’”, Toast.LENGTH_SHORT).show();
<Button android:id=“@+id/btnFinish” android:layout_width=“160dp” }
android:layout_height=“wrap_content” android:text=“4. Finish App”/> catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); }
}}); // btnWriteSDFile
</LinearLayout>
EXTERNAL SD FILES EXTERNAL SD FILES
(Example 3: Reading/writing external SD files) (Example 4: using scanner/printWriter on external SD Files)
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() { In this example we use the Scanner and PrintWriter classes. Scanners are useful for dissecting
@Override
public void onClick(View v) {// READ data from SD card show it in the text box formatted input into simple tokens. Whitespace markers separate the tokens, which could be
try {
BufferedReader myReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(mySdPath + “/mysdfile.txt”))));
translated according to their data type.
3
String aDataRow = “”, aBuffer = “”;
while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + “\n”; }
<?xml version=“1.0” encoding=“utf-8”?>
txtData.setText(aBuffer); <LinearLayout xmlns:android= “http://schemas.android.com/apk/res/android”
myReader.close();
Toast.makeText(getApplicationContext(), “Done reading SD ‘mysdfile.txt’”, Toast.LENGTH_SHORT).show();
android:orientation=“vertical”
} android:layout_width=“fill_parent”
catch (Exception e) { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } android:layout_height=“fill_parent”
}}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen); android:layout_margin=“10dp”>
btnClearScreen.setOnClickListener(new OnClickListener() { <TextView android:layout_width=“fill_parent”
@Override public void onClick(View v) {txtData.setText(“”);}
}); // btnClearScreen android:layout_height=“wrap_content”
btnClose = (Button) findViewById(R.id.btnFinish); android:padding=“10dp”
btnClose.setOnClickListener(new OnClickListener() {
@Override android:id=“@+id/txtMsg”
public void onClick(View v) {// terminate app android:textStyle=“bold”
Toast.makeText(getApplicationContext(), “Adios...”, Toast.LENGTH_SHORT).show();
finish();
android:background=“#77eeeeee”/>
}}); // btnClose </LinearLayout>
}// onCreate
}// File3SdCard

EXTERNAL SD FILES EXTERNAL SD FILES


(Example 4: using scanner/printWriter on external SD Files) (Example 4: using scanner/printWriter on external SD Files)
public class File4Scanner extends Activity {
TextView txtMsg; Comments
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView) findViewById(R.id.txtMsg);
1. You want to use the method Environment.getExternalStorageDirectory().getPath() to
testScannedFile(); detemine the path to the external SD card.
}//onCreate
private void testScannedFile(){
try {
2. A PrintWriter object is used to send data tokens to disk using any of the following methods:
String SDcardPath = Environment.getExternalStorageDirectory().getPath(), mySDFileName = SDcardPath + “/” + “mysdfiletest.txt”; print(), println(), printf().
txtMsg.setText(“Writing to: ” + mySDFileName);
// write to SD, needs “android.permission.WRITE_EXTERNAL_STORAGE” 3. A Scanner accepts whitespace separated tokens and converts then to their corresponding
PrintWriter outfile= new PrintWriter(new FileWriter(mySDFileName) );
outfile.println(“Hola Android”); outfile.println(“Adios Android”); outfile.println(new Date().toString()); types using methods: next(), nextInt(), nextDouble(), etc.
outfile.close();
// read SD-file, show records. Needs permission “android.permission.READ_EXTERNAL_STORAGE”
Scanner infile= new Scanner(new FileReader(mySDFileName));
String inString= “\n\nReading from: ” + mySDFileName + “\n”;
while(infile.hasNextLine()) { inString += infile.nextLine() + “\n”; }
txtMsg.append(inString); infile.close();
}
catch (FileNotFoundException e) { txtMsg.setText(“Error: ” + e.getMessage()); }
catch (IOException e) { txtMsg.setText(“Error: ” + e.getMessage()); }
}//testScannerFiles
}//class

You might also like