getsharedpreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.



Similar documents
ANDROID APPS DEVELOPMENT FOR MOBILE GAME

App Development for Smart Devices. Lec #4: Files, Saving State, and Preferences

Programming Mobile Applications with Android

Persistent Data Storage. Akhilesh Tyagi

CS 193A. Data files and storage

File System. /boot /system /recovery /data /cache /misc. /sdcard /sd-ext. Also Below are the for SD Card Fie System Partitions.

Creating and Using Databases for Android Applications

MAP524/DPS924 MOBILE APP DEVELOPMENT (ANDROID) MIDTERM TEST OCTOBER 2013 STUDENT NAME STUDENT NUMBER

Android Persistency: Files

Facebook Twitter YouTube Google Plus Website

MapGuide Open Source Repository Management Back up, restore, and recover your resource repository.

How to develop your own app

Programming with Android: Data management. Dipartimento di Scienze dell Informazione Università di Bologna

Raima Database Manager Version 14.0 In-memory Database Engine

Web development... the server side (of the force)

Installing buzztouch Self Hosted

INSTALLING, CONFIGURING, AND DEVELOPING WITH XAMPP

A Brief Introduction to MySQL

MarkLogic Server. Java Application Developer s Guide. MarkLogic 8 February, Copyright 2015 MarkLogic Corporation. All rights reserved.

IMPORT / EXPORT PRODUCTS

Building a Multi-Threaded Web Server

PaaS Operation Manual

SQLITE C/C++ TUTORIAL

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

Assignment 3 Version 2.0 Reactive NoSQL Due April 13

The full setup includes the server itself, the server control panel, Firebird Database Server, and three sample applications with source code.

Certified PHP/MySQL Web Developer Course

Installation & User Guide

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Spring Design ScreenShare Service SDK Instructions

Creating a Java application using Perfect Developer and the Java Develo...

WEB2CS INSTALLATION GUIDE

Android Development. Marc Mc Loughlin

sqlite driver manual

High-performance Android apps. Tim Bray

IceWarp Server Upgrade

I. Delivery Flash CMS template package II. Flash CMS template installation III. Control Panel setup... 5

Introduction to Android. CSG250 Wireless Networks Fall, 2008

ID TECH UniMag Android SDK User Manual

MySQL for Beginners Ed 3

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Web Development using PHP (WD_PHP) Duration 1.5 months

Migrating helpdesk to a new server

CS506 Web Design and Development Solved Online Quiz No. 01

A Case Study of an Android* Client App Using Cloud-Based Alert Service

Iotivity Programmer s Guide Soft Sensor Manager for Android

Autodownloader Toolset User Guide

Drupal CMS for marketing sites

HP AppPulse Mobile. Adding HP AppPulse Mobile to Your Android App

Workflow Templates Library

CS 103 Lab Linux and Virtual Machines

Installation of PHP, MariaDB, and Apache

System Requirement Specification for A Distributed Desktop Search and Document Sharing Tool for Local Area Networks

Version of this tutorial: 1.06a (this tutorial will going to evolve with versions of NWNX4)

DataFlex Connectivity Kit For ODBC User's Guide. Version 2.2

Android Development Exercises Version Hands On Exercises for. Android Development. v

Web Service Caching Using Command Cache

LabVIEW Internet Toolkit User Guide

Getting Started with Android Programming (5 days) with Android 4.3 Jelly Bean

CrushFTP User Manager

Developer Guide. Android Printing Framework. ISB Vietnam Co., Ltd. (IVC) Page i

Android Development. 吳 俊 興 國 立 高 雄 大 學 資 訊 工 程 學 系

UQC103S1 UFCE Systems Development. uqc103s/ufce PHP-mySQL 1

Cleaning your Windows 7, Windows XP and Macintosh OSX Computers

We begin with a number of definitions, and follow through to the conclusion of the installation.

An Introduction to Developing ez Publish Extensions

Monitoring and Alerting

Architecting the Future of Big Data

WatchDox Administrator's Guide. Application Version 3.7.5

To install Multifront you need to have familiarity with Internet Information Services (IIS), Microsoft.NET Framework and SQL Server 2008.

Using SQL Server Management Studio

RTI Database Integration Service. Getting Started Guide

Android Application Development Course Program

Published. Technical Bulletin: Use and Configuration of Quanterix Database Backup Scripts 1. PURPOSE 2. REFERENCES 3.

Python and MongoDB. Why?

FOR PARALLELS / PLESK PANEL

With a single download, the ADT Bundle includes everything you need to begin developing apps:

How to Install Applications (APK Files) on Your Android Phone

Lab 4 In class Hands-on Android Debugging Tutorial

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

PHP Language Binding Guide For The Connection Cloud Web Services

Implementation of a HomeMatic simulator using Android

EZcast technical documentation

Overview of Databases On MacOS. Karl Kuehn Automation Engineer RethinkDB

ADOBE FLASH PLAYER Administration Guide for Microsoft Windows 8

Global Search v.2.8 for Microsoft Dynamics CRM 4.0

Hands-On UNIX Exercise:

Table of Contents. Java CGI HOWTO

Password Depot for Android

PHP Integration Kit. Version User Guide

Transcription:

Android Storage Stolen from: developer.android.com data-storage.html i Data Storage Options a) Shared Preferences b) Internal Storage c) External Storage d) SQLite Database e) Network Connection ii Shared Preferences > The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. > You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. > This data will persist across user sessions (even if your application is killed). > To get a SharedPreferences object for your application, use one of two methods: getsharedpreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. getpreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name. > To write values:

1) Call edit() to get a SharedPreferences.Editor. 2) Add values with methods such as putboolean() and putstring(). 3) Commit the new values with commit() > To read values, use SharedPreferences methods such as getboolean() and getstring(). > Here is an example that saves a preference for silent keypress mode in a calculator: public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void oncreate(bundle state){ super.oncreate(state);... // Restore preferences SharedPreferences settings = getsharedpreferences(prefs_name, 0); // Context.MODE_PRIVATE boolean silent = settings.getboolean("silentmode", false); setsilent(silent); } @Override protected void onstop(){ super.onstop();

} } // Editor object to make preference changes. // All objects are from android.context.context SharedPreferences settings = getsharedpreferences(prefs_name, 0); SharedPreferences.Editor editor = settings.edit(); editor.putboolean("silentmode", msilentmode); // Commit the edits! editor.commit(); iii Internal Storage > Files saved to the internal storage are private to your application and other applications cannot access them. > When the user uninstalls your application, these files are removed. > To create and write a private file to the internal storage: 1) Call openfileoutput() with the name of the file and the operating mode. This returns a FileOutputStream. 2) Write to the file with write(). 3) Close the stream with close(). For Example: String FILENAME = "hello_file";

String string = "hello world!"; FileOutputStream fos = openfileoutput(filename, Context.MODE_PRIVATE); fos.write(string.getbytes()); fos.close(); ------------------------------- notes: 1) MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. 2) Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. > To read from an internal-storage file: 1) Call openfileinput() and pass it the name of the file to read. This returns a FileInputStream. 2) Read bytes from the file with read() 3) Then close the stream with close(). -------------------------------------------------- > Opening a file saved as WORLD_READABLE from another Application: The file mystuff.txt in package com.myco.greatapp is stored in: /data/data/com.myco.greatapp/files/mystuff.txt ------------------------------------------------- > To save a file at compile time, put the file in your project's res/raw directory. - You can open it with openrawresource(), passing the R.raw.<filename> resource ID.

- This method returns an InputStream that you can use to read the file. ------------------------------------------------- Saving cache files > If you'd like to cache some data, rather than store it persistently, you should use getcachedir() to open a File that represents the internal directory where your application should save temporary cache files. > When the device is low on internal storage space, Android may delete these cache files to recover space. > You should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. ------------------------------------------------------------ Other Methods getfilesdir() Gets the absolute path to the filesystem directory where your internal files are saved. getdir() Creates (or opens an existing) directory within your internal storage space. deletefile() Deletes a file saved on the internal storage. filelist() Returns an array of files currently saved by your application. iv External Storage > Every Android-compatible device supports a shared "external storage" that you can use to save files. > This can be a removable storage media (such as an SD card) or an internal (non-removable)

storage. > Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer. > All applications can read and write files placed on the external storage and the user can remove them. -------------------------------------------------------------------------- Checking for Media Availability > Call getexternalstoragestate() to check whether the media is available. > For Example: this example checks whether the external storage is available. boolean mexternalstorageavailable = false; boolean mexternalstoragewriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mexternalstorageavailable = mexternalstoragewriteable = true; } else if(environment.media_mounted_read_only.equals(state)) { // We can only read the media mexternalstorageavailable = true; mexternalstoragewriteable = false; } else { // Something else is wrong. // It may be one of many other states, // but all we need // to know is we can neither read nor write mexternalstorageavailable =

mexternalstoragewriteable = false; -------------------------------------- Accessing External Storage > use getexternalfilesdir() to open a File that represents the external storage directory where you should save your files. > This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory). > This method will create the appropriate directory if necessary. > Specifying the type of directory to ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). > If the user uninstalls your application, this directory and all its contents will be deleted. > ------------------------------------------------- Saving Sharable Files > For sharing: save files to one of external storage's public directories. > These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others. > Use getexternalstoragepublicdirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. - This method will create the appropriate directory if necessary. ----------------------------------------------------------- Saving Cache Files

> use getexternalcachedir() to open a File that represents the external storage directory where you should save cache files. v SQLite Database > Any databases you create will be accessible by name to any class in the application, but not outside the application. > To create a new SQLite database, create a subclass of SQLiteOpenHelper and override the oncreate() method, in which you can execute a SQLite command to create tables in the database. For example: public class DictionaryOpenHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 2; private static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);"; 3 DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void oncreate(sqlitedatabase db) {

} } db.execsql(dictionary_table_create); > You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. > To write to and read from the database, call getwritabledatabase() and getreadabledatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations. > You can execute SQLite queries using - the SQLiteDatabase query() methods, which accept various query parameters, such as - the table to query, - the projection, - selection, - columns, - grouping, - and others. - use SQLiteQueryBuilder for complex queries, such as those that require column aliases > Every SQLite query will return a Cursor that points to all the rows found by the query. (see the Note Pad and Searchable Dictionary for sample apps that demonstrate how to use SQLite databases in Android) vi Network Connection > Use java.net.* and android.net.* packages to do network operations.

=============================================================== vii Choosing Which Storage Type to Use Shared preferences are good for storing... an application's preferences, and other small bits of data. It's a just really simple persistent string key store for a few data types: boolean, float, int, long and string. So for instance if my app had a login, I might consider storing the session key as string within SharedPreferences. Internal storage is good for storing application data that the user doesn't need access to, because the user cannot easily access internal storage. Possibly good for caching, logs, other things. Anything that only the app intends to Create Read Update or Delete. External storage. Great for the opposite of what I just said. The dropbox app probably uses external storage to store the user's dropbox folder, so that the user has easy access to these files outside the dropbox application, for instance, using the file manager. SQLite databases are great whenever you are going to use a lot of structured data and a relatively rigid schema for managing it. Put in layman's terms, SQLite is like MySQL or PostgreSQL except instead of the database acting as a server daemon which then takes queries from the CGI scripts like php, it is simply stored in a.db file, and accessed and queried through a simple library within the application. While SQLite cannot scale nearly as big as the dedicated databases, it is very quick and convenient for smaller applications, like Android apps. I would use an SQLite db if I were making an app for aggregating and downloading recipes, since that kind of data is relatively structured and a database would

allow for it to scale well. Databases are nice because writing all of your data to a file, then parsing it back in your own proprietary format it no fun. Then again, storing data in XML or JSON wouldn't be so bad. Network connection refers to storing data on the cloud. HTTP or FTP file and content transfers through the java.net.* packages makes this happen. From: stackoverflow.com which-android-data-storage-technique-to-use