Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS499 – Mobile Application Development

Similar presentations


Presentation on theme: "CS499 – Mobile Application Development"— Presentation transcript:

1 CS499 – Mobile Application Development
Fall 2013 Programming the Android Platform Data Management

2 Data Management Files (internal/external) SQLite database
SharedPreferences (not discussed but a couple of examples included online)

3 File Represents a file system entity identified by a pathname
Classified as internal or external Internal memory (on the device) usually used for application private files External memory (removable media) used for public files Cache files – temporary files Examples: DataManagementFileInternalMemory DataManagementFileExternalMemory

4 File API boolean isDIrectory() String getAbsolutePath()
return true if this file represents a directory String getAbsolutePath() returns the absolute path to this file boolean setReadable(boolean readable) sets read permission on this file MANY others – see documentation

5 Writing an Internal Memory File
// Open file with ContextWrapper.openFileOutput() FileOutputStream fos = openFileOutput(filename,MODE_PRIVATE); PrintWriter pw = new PrintWriter( new BufferedWriter( new OutputStreamWriter(fos))); // Write to file pw.println(…); //Close file pw.close();

6 Reading an Internal Memory File
// Open file with ContextWrapper.openFileOutput() FileInputStream fis = openFileOutput(filename); PrintWriter fr = new PrintWriter( new BufferedReader( new InputStreamReader(fis))); // Read from file while (null != (line=fr.readLine())) { // process data } //Close file fr.close();

7 External Memory Files Removable media may appear/disappear without warning String Environment.getExternalStorageState() MEDIA_MOUNTED – present & mounted with read/write access MEDIA_MOUNTED_READ_ONLY MEDIA_REMOVED – not present Need permission to write external files in AndroidManifest.xml: <uses-permission android:name= “android.permission.WRITE_EXTERNAL_STORAGE” />

8 Writing an External Memory File
public class FileWriteAndReadActivity extends Activity { public void onCreate(Bundle savedState) { … if (Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState())) { File outFile = new File(getExternalFilesDir( Environment.DIRECTORY_PICTURES),fileName); try { BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); BufferedInputStream is = new BufferedInputStream(getResources() .openRawResource(R.drawable.icon)); copy(is,os); } catch (FileNotFoundException e) {} }

9 Writing an External Memory File
private void copy(InputStream is, OutputStream os) { final byte[] buf = new byte[1024]; int numBytes; try { while (-1 != (numBytes = is.read(buf))) { os.write(buf,0,numBytes); } } catch (IOException e) { … } } finally { is.close(); os.close(); } catch (IOException e) {} …

10 SQLite SQLite provides in-memory database available to the app that created it Designed to operate within a very small footprint Implements most of SQL92 Supports ACID transactions ACID: atomic, consistent, isolated & durable Will need to use a content provider to make data available to rest of the system.

11 Databases This is not a class in databases (CS450) and you aren’t required to know about databases to use SQLite Data organized in tables where each row will hold a single element that we are interested in. Each element has a unique identifier called the key each column is a field of the given elements in the table

12 Example: GradesDB GNumber LastName FirstName Exam1grade Exam2grade
Smith Bob 80 G Jones Davey 70 90 G White Betty 85 G Doe Jane 20 100 G John 50 G

13 SQL – Structured Query Language
Standard way to make database requests (creation, queries, insertion, deletion) Based on relational algebra and tuple relational calculus Fairly standardized SELECT LastName, FirstName FROM GradesDB WHERE Gnumber = G In Android, requests formulated as method calls with multiple parameters, but has the notation at the core.

14 Opening a Database Recommended method relies on a helper class called SQLiteOpenHelper Create a subclass SQLiteOpenHelper Override onCreate() Execute CREATE TABLE command Use Constructor to instantiate subclass Use SQLiteOpenHelper methods to open & return underlying database

15 Opening a Database public class DatabaseOpenHelper extends SQLiteOpenHelper { final private static String CREATE_CMD = “CREATE TABLE artists(“ + “_id “+”INTEGER PRIMARY KEY AUTOINCREMENT, “ + “name “+”TEXT NOT NULL)”; public DatabaseOpenHelper(Context context) { super(context,”artist_db”,null,1); } public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_CMD); …

16

17

18 Using a Database public class DatabaseExampleActivity extends ListActivity { final static String[] columns={“_id”, “name”}; static SQLiteDatabase db = null; public void onCreate(Bundle savedState) { … DatabaseOpenHelper dbHelper = new DatabaseOpenHelper(); db = dbHelper.getWritableDatabase(); insertArtists(); Cursor c = readArtists(); deleteLadyGaga(); setListAdapter(new SimpleCursorAdapter( this, R.layout.list_layout,c,columns, new int[]{R.id._id,R.id.name})); }

19

20 Insertion private void insertArtists() { ContentValues values = new ContentValues(); values.put(“name”,”Lady Gaga”); db.insert(“artists”,null,values); values.clear(); values.put(“name”,”Johnny Cash”); values.put(“name”,”Ludwig von Beethoven”); }

21

22 Deletion & Querying private int deleteLadyGaga() { return db.delete(“artists”,”name =?”, new String[]{“Lady Gaga”}); } private Cursor readArtists() { // SELECT * from artists // i.e. return all rows that match return db.query(“artists”, new String[]{“_id”,”name”}, null, new String[]{},null,null,null);

23 Querying public Cursor query(String table, String columns[], String selection, String selectionArgs, String groupBy, String having, String orderBy, String limit) The parameters are designed to allow queries with the full power of SQL

24 Query Examples Return all rows where there value matches a given parameter String[] COLUMNS = new STRING{“FirstName”,”LastName”}; String selection = “Gnumber = ?”; String[] args = {“G ”}; Cursor result = db.query(“GradesDB”,COLUMNS, selection, args,null,null,null,null); Return rows where some field has a particular range String selection = “Exam1Grade < ? AND Exam2Grade < ?”; String[] args = {“70”,”70”};

25 Cursor class  Provides random read-write access to the result set returned by a database query moveToFirst(), moveToNext(), moveToPosition(int) – iterate through getString(int index), getInt(int index) – column value associated with a particular row CursorAdapter lets you put info into a ListView

26 Upgrading

27 Content Providers

28

29

30

31 Examining Databases Databases stored in
/data/data/<package name>/databases Can examine database with sqlite3


Download ppt "CS499 – Mobile Application Development"

Similar presentations


Ads by Google