Chapter12-Files and Preferences - Publish
Chapter12-Files and Preferences - Publish
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
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.
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