Android Persistence and Networking

  • Published on
    11-May-2015

  • View
    371

  • Download
    0

DESCRIPTION

Unterlage zur Android Vorlesung "Programmierung von Apps" an der Hochschule Karlsruhe. Die Studierenden kennen die Mglichkeiten frAndroid Persistence und Networking und verstehen, wie damit auf Daten und Netzwerke zugegriffen werden kann.

Transcript

1.Programmierung von AppsAndroid Persistenceand NetworkingDanny Frni, 25.11.2012, 12. Die Studierenden kennen die Mglichkeiten frAndroid Persistence und Networkingund verstehen, wie damit auf Datenund Netzwerke zugegriffen werden kann.Danny Frni, 25.11.2012, 2 3. Danny Frni, 25.11.2012, 3Files 4. Internal Storage/data/data/ /files /shared_prefs /cache /databases /libDanny Frni, 25.11.2012, 4 Demo 5. openFileInput()openFileOutput()MODE_PRIVATE Kein Zugriff durch andere AppsMODE_WORLD_READABLE Lesender Zugriff durch andere AppsMODE_WORLD_WRITABLE Schreibender Zugriff durch andere AppsMODE_WORLD_READABLE | MODE_WORLD_WRITABLE Lese- und Schreib-ZugriffDanny Frni, 25.11.2012, 5 6. External StorageEnvironment.getExternalStorageState();Context.getExternalFilesDir(type);android.permission null.WRITE_EXTERNAL_STORAGE Environment.DIRECTORY_MUSIC, Environment.DIRECTORY_PODCASTS, Environment.DIRECTORY_RINGTONES, Environment.DIRECTORY_ALARMS, Environment.DIRECTORY_NOTIFICATIONS,Danny Frni, 25.11.2012, 6 Environment.DIRECTORY_PICTURES, Environment.DIRECTORY_MOVIES./Android/data/ Demo Quelle: http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String) 7. In-APP-Storage/res/raw getResources().openRawResource()/res/xml getResources().getXml()/assets getAssets().open()Danny Frni, 25.11.2012, 7 8. Danny Frni, 25.11.2012, 8Shared Preferences 9. PreferenceActivity@Overridepublic void onBuildHeaders(Listtarget){super.onBuildHeaders(target);loadHeadersFromResource(R.xml.prefs_headers,target);}Danny Frni, 25.11.2012, 9Demo 10. extends PreferenceFragmentaddPreferencesFromResource(R.xml.prefs_server); prefs_server.xml 11. SharedPreferenceslesen und schreiben prefs =PreferenceManager.getDefaultSharedPreferences(this); StringprefsServerUrl = prefs.getString("",""); SharedPreferences.Editor editor =prefs.edit(); editor.putString("","");Danny Frni, 25.11.2012, 11 editor.commit(); 12. Danny Frni, 25.11.2012, 12 Database 13. SQLite Keine Konfiguration notwendig Kein Datenbank-Server Single-File Datenbank (Filesystem-Security) Open Source In Android integriert Keine strikte statische Typisierung sqlite.orgDanny Frni, 25.11.2012, 13 14. SQLite DataTypes TEXT INTEGER REAL No checks! Date and Time (functions) TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").Danny Frni, 25.11.2012, 14 INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC. Quelle: http://www.sqlite.org/datatype3.html 15. extend SQLiteOpenHelper Erzeugt Datenbank onCreate() Aktualisiert Datenbank onUpgrade() Ermglicht Zugriff auf die Datenbank getReadableDatabase() getWritableDatabase()Danny Frni, 25.11.2012, 15Demo 16. onCreate() public void onCreate(SQLiteDatabase db){ db.execSQL(NewsItemContract.Table.CREATE_TABLE_NEWS); db.execSQL("CREATETABLExyz (_id PRIMARYKEYAUTOIN"); }Danny Frni, 25.11.2012, 16 17. onUpgrade() public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion){ db.execSQL("droptableifexists" + NewsItemContract.Table.NEWS); onCreate(db); }Danny Frni, 25.11.2012, 17 18. Danny Frni, 25.11.2012, 18EETARE A D E T A P DEEELT 19. insert() ContentValues values = new ContentValues(); values.put(NewsItemColumns.title, item.getTitle()); values.put(NewsItemColumns.teaser, item.getTeaser()); values.put(NewsItemColumns.published, item.getPublished().getTime()); values.put(NewsItemColumns.pictureUrl, item.getPictureUri().toString()); values.put(NewsItemColumns.imageFileName, item.getImageFileName()); db.insertOrThrow(NewsItemContract.Table.NEWS, null, values);Danny Frni, 25.11.2012, 19 20. query()SQLInterface SELECTedvNr,name projection/columns FROMlehrveranstaltung table WHEREname selection="Prof.Dr.Ing.Vogelsang"selectionArgs groupBy =nullDanny Frni, 25.11.2012, 20having =null ORDERBYedvNr orderBy 21. update() db.update(table,values,whereClause,whereArgs );Danny Frni, 25.11.2012, 21 22. delete() db.delete( table, whereClause, whereArgs );Danny Frni, 25.11.2012, 22 23. Danny Frni, 25.11.2012, 23 Cursor 24. Cursor nutzen _id edvNr name 0123 int edvNrIndexDanny Frni, 25.11.2012, 24 =cursor.getColumnIndex(edvNr) StringedvNr = cursor.getString(edvNrIndex) 25. Transactions int inserts =0; try { db.beginTransaction(); if (null !=table){ for (ContentValues contentValues :values){ db.insert(table,"",contentValues); inserts++; } db.setTransactionSuccessful(); } }catch (SQLException e){ Log.e(LOG_TAG,"Insertfehlgeschlagen",e);Danny Frni, 25.11.2012, 25 }finally { db.endTransaction(); } Bildquelle: http://developer.android.com/design/patterns/actionbar.html 26. Danny Frni, 25.11.2012, 26 Networking 27. Permissions android.permission.INTERNET android.permission.ACCESS_NETWORK_STATEDanny Frni, 25.11.2012, 27 28. 10.0.2.2 IPAdressefrdasHostSystemimAndroid EmulatorDanny Frni, 25.11.2012, 28 29. Apache Http Client HttpClient client =new DefaultHttpClient(); HttpGet request =new HttpGet(host + "/api/persons?type=ProfessorInnen"); //Responselesen HttpResponse response =client.execute(request); BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent())); Stringcontent =""; StringBuilder responseTxt =new StringBuilder(); while ((content =reader.readLine())!=null){ responseTxt.append(content);Danny Frni, 25.11.2012, 29 }Demo 30. java.net.HttpUrlConnection URLnewsUrl =new URL(host +"/api/news.json"); HttpURLConnection conn =(HttpURLConnection) newsUrl.openConnection(); //Responselesen InputStream in=conn.getInputStream(); BufferedReader reader =new BufferedReader( new InputStreamReader(in)); Stringcontent =""; StringBuilder response =new StringBuilder(); while ((content =reader.readLine())!=null){ response.append(content);Danny Frni, 25.11.2012, 30 }Demo Quelle: http://android-developers.blogspot.de/2011/09/androids-http-clients.html 31. Danny Frni, 25.11.2012, 31 32. Representational StateTransfer (REST)Architekturstil HTTP-Verben basierend auf WWWPOSTGET URI, Ressourcen, Reprsentationen http://localhost:8180/api/newsPUT http://localhost:8180/api/news/3 http://localhost:8180/api/persons DELETEDanny Frni, 25.11.2012, 32 etc. json,xml,html,etc.http://www.slideshare.net/dnene/rest representationalstatetransferexplained 33. JSONJSONObject JSONArray JSONObject {"newsItem":[{"id":3, "imageFileName":"news3.jpg", "pictureUri":"http://localhost:8180/images/news3.jpg", "published":"20111220T13:07:54.480+01:00", "teaser":"frInnovationeninderHochschullehre", "title":"Prof.Dr.AndreasHeberle erhltfrguteLehreFrderpreisvon50000Euro" }]}Danny Frni, 25.11.2012, 33Demo 34. XML APIs SAX (Simple API for XML) DOM (Document Object Model) StAX (Streaming API for XML)Danny Frni, 25.11.2012, 34Quelle: http://www.torsten-horn.de/techdocs/java-xml.htm 35. XmlPullParserXmlPullParserFactory.newPullParser().Danny Frni, 25.11.2012, 35 Quelle: http://www.xmlpull.org; http://android-developers.blogspot.com/2011/12/watch-out-for-xmlpullparsernexttext.html 36. XMLSTART_TAG,name =person START_TAG,name =akademischerTitel Text Prof.Dr.Albrecht,Ditzingerhttp://localhost:8180/images/I_2e8f4d534f.jpghttp://localhost:8180/api/persons/3Danny Frni, 25.11.2012, 36END_TAG,name =personDemo 37. Danny Frni, 25.11.2012, 37 ContentProvider 38. Danny Frni, 25.11.2012, 38 ContentProvider 39. URIsMulti Item content://com.dfuerniss.pva.ss2012.database.contentprovider/lehrveranstaltungenSingle Item content://com.dfuerniss.pva.ss2012.database.contentprovider/lehrveranstaltungen/# PlatzhalterfrdieId der LehrveranstaltungDanny Frni, 25.11.2012, 39 Demo 40. ContentResolver Cursor cursor =getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);Danny Frni, 25.11.2012, 40 41. android:authorities Danny Frni, 25.11.2012, 41 42. Danny Frni, 25.11.2012, 42 extend ContentProvider Demo 43. Danny Frni, 25.11.2012, 43 Loader 44. Danny Frni, 25.11.2012, 44 Loaders 45. initLoader private static final int NEWS_LOADER =0; //setup news loader Log.i(TAG,"initLoader:" +NEWS_LOADER); newsLoader =getLoaderManager().initLoader(NEWS_LOADER,null,this);Danny Frni, 25.11.2012, 45 46. implementsLoaderCallbacks 1 @Override public LoaderonCreateLoader(int loaderId,Bundlebundle){ Log.i(TAG,"creating loader for id:" +loaderId); AsyncTaskLoaderloader =null; if (loaderId ==NEWS_LOADER){ Log.i(TAG,"creating news loader"); loader =new AsyncTaskLoader(this){ }; } return loader;Danny Frni, 25.11.2012, 46 } 47. implementsLoaderCallbacks 2 @Override public void onLoadFinished(Loaderloader,Cursorcursor){ Log.i(TAG,"loader finished:" +loader.getId()); if (loader.getId()==NEWS_LOADER){ newsAdapter.swapCursor(cursor); } } @Override public void onLoaderReset(Loaderloader){ Log.i(TAG,"loader reset:" +loader.getId());Danny Frni, 25.11.2012, 47 if (loader.getId()==NEWS_LOADER){ newsAdapter.swapCursor(null); } } Demo 48. AsyncTaskLoader @Override public CursorloadInBackground(){ Log.i(TAG,"load inbackground"); SQLiteDatabase db =((Application)getApplication()) .getDbHelper().getReadableDatabase(); return db.query( NewsItemContract.Table.NEWS, //Projectionmuss_identhalten! NewsItemContract.Query.PROJECTION_ALL,selection,selectionArgs,groupBy,having,Danny Frni, 25.11.2012, 48orderBy); } @Override public void onStartLoading(){forceLoad()} 49. CursorLoader CursorLoader cl= new CursorLoader(context, URI, projection, selection, selectionArgs, sortOrder );Danny Frni, 25.11.2012, 49 50. android:installLocationinternalOnly (default)auto preferExternalDanny Frni, 25.11.2012, 50 51. Portions of this presentation are modifications based on work created and shared by Google and used according to terms described inthe Creative Commons 3.0Attribution License.Danny Frni, 25.11.2012, 51