* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Data Management
Survey
Document related concepts
Transcript
CS499 – Mobile Application Development Fall 2013 Programming the Android Platform Data Management Data Management • Files (internal/external) • SQLite database • SharedPreferences (not discussed but a couple of examples included online) 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 File API • boolean isDIrectory() – 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 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(); 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(); 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” /> 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) {} } } 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 { try { is.close(); os.close(); } catch (IOException e) {} … 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. 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 Example: GradesDB GNumber LastName FirstName Exam1grade Exam2grade G12345678 Smith Bob 80 80 G00000001 Jones Davey 70 90 G01010101 White Betty 90 85 G87654321 Doe Jane 20 100 G99999999 Doe John 20 50 G88888888 Smith Bob 80 85 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 = G99999999 • In Android, requests formulated as method calls with multiple parameters, but has the notation at the core. 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 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); } … 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})); } 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”); db.insert(“artists”,null,values); values.clear(); values.put(“name”,”Ludwig von Beethoven”); db.insert(“artists”,null,values); } 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); } 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 Query Examples • Return all rows where there value matches a given parameter String[] COLUMNS = new STRING{“FirstName”,”LastName”}; String selection = “Gnumber = ?”; String[] args = {“G99999999”}; Cursor result = db.query(“GradesDB”,COLUMNS, selection, args,null,null,null,null); • Return rows where some field has a particular range String[] COLUMNS = new STRING{“FirstName”,”LastName”}; String selection = “Exam1Grade < ? AND Exam2Grade < ?”; String[] args = {“70”,”70”}; Cursor result = db.query(“GradesDB”,COLUMNS, selection, args,null,null,null,null); Cursor class • Provides random read-write access to the result set returned by a database query • http://developer.android.com/reference/andr oid/database/Cursor.html • 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 Upgrading Content Providers Examining Databases • Databases stored in /data/data/<package name>/databases • Can examine database with sqlite3