SlideShare ist ein Scribd-Unternehmen logo
1 von 51
Downloaden Sie, um offline zu lesen
Programmierung
                                 von Apps
                              Android Persistence
                                and Networking
Danny Fürniß, 25.11.2012, 1
Die Studierenden
                                 kennen die Möglichkeiten für
                              Android Persistence und Networking
                              und verstehen, wie damit auf Daten
                                  und Netzwerke zugegriffen
                                         werden kann.
Danny Fürniß, 25.11.2012, 2
Danny Fürniß, 25.11.2012, 3




                              Files
Internal Storage
                              /data/data/<app-package-name>
                                   /files
                                   /shared_prefs
                                   /cache
                                   /databases
                                   /lib
Danny Fürniß, 25.11.2012, 4




                                   …
                                                              Demo
openFileInput()
                                              openFileOutput()

                              MODE_PRIVATE – Kein Zugriff durch andere Apps

                              MODE_WORLD_READABLE – Lesender Zugriff durch andere Apps

                              MODE_WORLD_WRITABLE – Schreibender Zugriff durch andere Apps

                              MODE_WORLD_READABLE | MODE_WORLD_WRITABLE – Lese- und Schreib-Zugriff
Danny Fürniß, 25.11.2012, 5
External Storage
                              Environment.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 Fürniß, 25.11.2012, 6




                                             Environment.DIRECTORY_PICTURES,
                                             Environment.DIRECTORY_MOVIES.
                              /Android/data/<package-name>
                                                                                                                                                           Demo
                                       Quelle: http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
„In-APP“-Storage

                              /res/raw       getResources().openRawResource()

                              /res/xml       getResources().getXml()

                              /assets        getAssets().open()
Danny Fürniß, 25.11.2012, 7
Danny Fürniß, 25.11.2012, 8




                              Shared Preferences
PreferenceActivity

                              @Override
                              public void onBuildHeaders(List<Header> target) {
                                  super.onBuildHeaders(target);
                                  loadHeadersFromResource(R.xml.prefs_headers, 
                                      target);
                              }
Danny Fürniß, 25.11.2012, 9




                                                                                  Demo
extends PreferenceFragment
                                addPreferencesFromResource(R.xml.prefs_server);

                               prefs_server.xml
                                <?xml version="1.0" encoding="utf‐8"?>
                                <PreferenceScreen
                                    xmlns:android="http://schemas.android.com/apk/res/android">
                                    <PreferenceCategory
                                        android:title="@string/prefsServerSettings">
                                        <EditTextPreference
                                            android:title="@string/prefsServerUrl" 
                                            android:key="prefsServerUrl"/>
                                        <CheckBoxPreference
                                            android:title="@string/prefsServerWifiOnly" 
Danny Fürniß, 25.11.2012, 10




                                            android:key="prefsServerWifiOnly"/>
                                    </PreferenceCategory>
                                </PreferenceScreen>
SharedPreferences
                                            lesen und schreiben

                               prefs = PreferenceManager.getDefaultSharedPreferences(this);
                               String prefsServerUrl = 
                                   prefs.getString("<key>", "<default‐value>");




                               SharedPreferences.Editor editor = prefs.edit();
                               editor.putString("<key>", "<value>");
Danny Fürniß, 25.11.2012, 11




                               editor.commit();
Danny Fürniß, 25.11.2012, 12




                               Database
SQLite
                               • Keine Konfiguration notwendig
                               • Kein Datenbank-Server
                               • Single-File Datenbank (Filesystem-Security)
                               • Open Source
                               • In Android integriert
                               • Keine strikte statische Typisierung
                               • sqlite.org
Danny Fürniß, 25.11.2012, 13
SQLite DataTypes
                               • TEXT
                               • INTEGER
                               • REAL
                               No checks!


                               • Date and Time (functions)
                                  • TEXT as ISO8601 strings
                                     ("YYYY-MM-DD HH:MM:SS.SSS").
Danny Fürniß, 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
extend SQLiteOpenHelper
                               • Erzeugt Datenbank
                                  • onCreate()
                               • Aktualisiert Datenbank
                                  • onUpgrade()
                               • Ermöglicht Zugriff auf die Datenbank
                                  • getReadableDatabase()
                                  • getWritableDatabase()
Danny Fürniß, 25.11.2012, 15




                                                                        Demo
onCreate()

                               public void onCreate(SQLiteDatabase db) {

                                   db.execSQL(NewsItemContract.Table.CREATE_TABLE_NEWS);

                                   db.execSQL("CREATE TABLE xyz (_id PRIMARY KEY AUTOIN…");
                               }
Danny Fürniß, 25.11.2012, 16
onUpgrade()

                               public void onUpgrade(SQLiteDatabase db, 
                                   int oldVersion, int newVersion) {

                                   db.execSQL("drop table if exists " + 
                                       NewsItemContract.Table.NEWS);

                                   onCreate(db);
                               }
Danny Fürniß, 25.11.2012, 17
Danny Fürniß, 25.11.2012, 18




    E
    E

    T
    A
    R                          E
                               A
                               D

     E
     T
     A
     P
     D



    E
    E
    E
    L

    T
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 Fürniß, 25.11.2012, 19
query()
                                      SQL                              Interface

                               SELECT edvNr, name                 projection/columns
                               FROM lehrveranstaltung                         table
                               WHERE name                                 selection
                                  = "Prof. Dr.‐Ing. Vogelsang"        selectionArgs
                                                                     groupBy = null
Danny Fürniß, 25.11.2012, 20




                                                                      having = null
                               ORDER BY edvNr                               orderBy
update()

                               db.update(
                                    table,
                                    values,
                                    whereClause,
                                    whereArgs
                               );
Danny Fürniß, 25.11.2012, 21
delete()

                               db.delete(
                                     table,
                                     whereClause,
                                     whereArgs
                               );
Danny Fürniß, 25.11.2012, 22
Danny Fürniß, 25.11.2012, 23




                               Cursor
Cursor nutzen
                                 _id             edvNr             name                   …        
                                  0                  1                 2                  3




                                                   int edvNrIndex
Danny Fürniß, 25.11.2012, 24




                                                       = cursor.getColumnIndex(„edvNr“)   
                                                   String edvNr =  
                                                       cursor.getString(edvNrIndex)
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, "Insert fehlgeschlagen", e);
Danny Fürniß, 25.11.2012, 25




                               } finally {
                                 db.endTransaction();
                               }

                                             Bildquelle: http://developer.android.com/design/patterns/actionbar.html
Danny Fürniß, 25.11.2012, 26




                               Networking
Permissions

                               android.permission.INTERNET

                               android.permission.ACCESS_NETWORK_STATE
Danny Fürniß, 25.11.2012, 27
10.0.2.2
                               IP‐Adresse für das Host‐System im Android Emulator
Danny Fürniß, 25.11.2012, 28
Apache Http Client
                               HttpClient client = new DefaultHttpClient();
                               HttpGet request = new HttpGet(host +  
                                   "/api/persons?type=ProfessorInnen");

                               // Response lesen
                               HttpResponse response = client.execute(request);
                               BufferedReader reader = new BufferedReader(new
                                   InputStreamReader(response.getEntity().getContent()));
                               String content = "";
                               StringBuilder responseTxt = new StringBuilder(); 
                               while ((content = reader.readLine()) != null) {
                                   responseTxt.append(content);
Danny Fürniß, 25.11.2012, 29




                               }



                                                                                            Demo
java.net.HttpUrlConnection
                               URL newsUrl = new URL(host + "/api/news.json"); 
                               HttpURLConnection conn = (HttpURLConnection) 
                                   newsUrl.openConnection();

                               // Response lesen
                               InputStream in = conn.getInputStream();
                               BufferedReader reader = new BufferedReader(
                                   new InputStreamReader(in));
                               String content = "";
                               StringBuilder response = new StringBuilder();
                               while ((content = reader.readLine()) != null) {
                                   response.append(content);
Danny Fürniß, 25.11.2012, 30




                               }


                                                                                                                                Demo
                                             Quelle: http://android-developers.blogspot.de/2011/09/androids-http-clients.html
Danny Fürniß, 25.11.2012, 31
Representational State
                                              Transfer (REST)
                                          Architekturstil                         HTTP-Verben
                                     basierend auf WWW                                  POST
                                                                                          GET
                               URI, Ressourcen, Repräsentationen
                                     http://localhost:8180/api/news                      PUT
                                     http://localhost:8180/api/news/3
                                     http://localhost:8180/api/persons                 DELETE
Danny Fürniß, 25.11.2012, 32




                                     etc.

                                     json, xml, html, etc.            http://www.slideshare.net/dnene/rest‐
                                                                     representational‐state‐transfer‐explained
JSON
                                      JSONObject
                                                     JSONArray
                                                     JSONObject

                               { "newsItem" : [ { "id" : 3,
                                     "imageFileName" : "news3.jpg",
                                     "pictureUri" : "http://localhost:8180/images/news3.jpg",
                                     "published" : "2011‐12‐20T13:07:54.480+01:00",
                                     "teaser" : "für Innovationen in der Hochschullehre",
                                     "title" : "Prof. Dr. Andreas Heberle erhält für gute Lehre Förderpreis von 50 000 Euro"
                                   } ] }
Danny Fürniß, 25.11.2012, 33




                                                                                                                      Demo
XML APIs

                                 SAX (Simple API for XML)

                               DOM (Document Object Model)

                               StAX (Streaming API for XML)
Danny Fürniß, 25.11.2012, 34




                                  Quelle: http://www.torsten-horn.de/techdocs/java-xml.htm
XmlPullParser
                                                    XmlPullParserFactory.newPullParser().
Danny Fürniß, 25.11.2012, 35




                               Quelle: http://www.xmlpull.org; http://android-developers.blogspot.com/2011/12/watch-out-for-xmlpullparsernexttext.html
XML
                                        START_TAG, name = person


                                                 START_TAG, name = akademischerTitel
                                                             Text
                               <person>
                                 <akademischerTitel>Prof. Dr.</akademischerTitel>
                                 <displayName>Albrecht, Ditzinger</displayName>
                                 <imageURI>http://localhost:8180/images/I_2e8f4d534f.jpg</imageURI>
                                 <personURI>http://localhost:8180/api/persons/3</personURI>
                               </person>
Danny Fürniß, 25.11.2012, 36




                                        END_TAG, name = person


                                                                                                      Demo
Danny Fürniß, 25.11.2012, 37




                               ContentProvider
Danny Fürniß, 25.11.2012, 38




                               ContentProvider
URIs
                                      Multi Item
                               content://com.dfuerniss.pva.ss2012.database.contentprovider/lehrveranstaltungen



                                      Single Item
                               content://com.dfuerniss.pva.ss2012.database.contentprovider/lehrveranstaltungen/#


                                                                                   Platzhalter für die Id der 
                                                                                         Lehrveranstaltung
Danny Fürniß, 25.11.2012, 39




                                                                                                                   Demo
ContentResolver

                               Cursor cursor = 
                                      getContentResolver().query(
                                              uri, 
                                              projection, 
                                              selection, 
                                              selectionArgs, 
                                              sortOrder
                                      );
Danny Fürniß, 25.11.2012, 40
android:authorities

                               <provider
                                 android:name=".provider.LehrveranstaltungContentProvider" 
                                 android:authorities=
                                     "com.dfuerniss.pva.ss2012.database.contentprovider">
                               </provider>
Danny Fürniß, 25.11.2012, 41
Danny Fürniß, 25.11.2012, 42




                                   extend
                               ContentProvider



   Demo
Danny Fürniß, 25.11.2012, 43




                               Loader
Danny Fürniß, 25.11.2012, 44




                               Loaders
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 Fürniß, 25.11.2012, 45
implements
                                        LoaderCallbacks<Cursor>
                                                   1
                               @Override
                               public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) {
                                   Log.i(TAG, "creating loader for id: " + loaderId);
                                   AsyncTaskLoader<Cursor> loader = null;
                                   if (loaderId == NEWS_LOADER) {
                                       Log.i(TAG, "creating news loader");
                                       loader = new AsyncTaskLoader<Cursor>(this) {
                                           …
                                       };
                                   }
                                   return loader;
Danny Fürniß, 25.11.2012, 46




                               }
implements
                                        LoaderCallbacks<Cursor>
                                                   2
                               @Override
                               public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
                                   Log.i(TAG, "loader finished: " + loader.getId());
                                   if (loader.getId() == NEWS_LOADER) {
                                       newsAdapter.swapCursor(cursor);
                                   }
                               }

                               @Override
                               public void onLoaderReset(Loader<Cursor> loader) {
                                   Log.i(TAG, "loader reset: " + loader.getId());
Danny Fürniß, 25.11.2012, 47




                                   if (loader.getId() == NEWS_LOADER) {
                                       newsAdapter.swapCursor(null);
                                   }
                               }
                                                                                             Demo
AsyncTaskLoader
                               @Override
                               public Cursor loadInBackground() {
                                   Log.i(TAG, "load in background");
                                   SQLiteDatabase db = ((Application) getApplication())
                                       .getDbHelper().getReadableDatabase();
                                   return db.query(
                                       NewsItemContract.Table.NEWS, 
                                       // Projection muss _id enthalten!
                                       NewsItemContract.Query.PROJECTION_ALL, 
                                      selection, 
                                      selectionArgs, 
                                      groupBy, 
                                      having, 
Danny Fürniß, 25.11.2012, 48




                                      orderBy);
                               }

                               @Override
                               public void onStartLoading() { …forceLoad()… }
CursorLoader
                               CursorLoader cl = 
                                   new CursorLoader(context, 
                                   URI, 
                                   projection, 
                                   selection, 
                                   selectionArgs, 
                                   sortOrder
                               );
Danny Fürniß, 25.11.2012, 49
android:installLocation

                                    internalOnly (default)

                                            auto

                                       preferExternal
Danny Fürniß, 25.11.2012, 50
Portions of this presentation
                               are modifications based on
                               work created and shared by
                               Google and used according
                                   to terms described in
                                the Creative Commons 3.0
                                    Attribution License.
Danny Fürniß, 25.11.2012, 51

Weitere ähnliche Inhalte

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Android Persistence and Networking

  • 1. Programmierung von Apps Android Persistence and Networking Danny Fürniß, 25.11.2012, 1
  • 2. Die Studierenden kennen die Möglichkeiten für Android Persistence und Networking und verstehen, wie damit auf Daten und Netzwerke zugegriffen werden kann. Danny Fürniß, 25.11.2012, 2
  • 4. Internal Storage /data/data/<app-package-name> /files /shared_prefs /cache /databases /lib Danny Fürniß, 25.11.2012, 4 … Demo
  • 5. openFileInput() openFileOutput() MODE_PRIVATE – Kein Zugriff durch andere Apps MODE_WORLD_READABLE – Lesender Zugriff durch andere Apps MODE_WORLD_WRITABLE – Schreibender Zugriff durch andere Apps MODE_WORLD_READABLE | MODE_WORLD_WRITABLE – Lese- und Schreib-Zugriff Danny Fürniß, 25.11.2012, 5
  • 6. External Storage Environment.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 Fürniß, 25.11.2012, 6 Environment.DIRECTORY_PICTURES, Environment.DIRECTORY_MOVIES. /Android/data/<package-name> 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 Fürniß, 25.11.2012, 7
  • 8. Danny Fürniß, 25.11.2012, 8 Shared Preferences
  • 9. PreferenceActivity @Override public void onBuildHeaders(List<Header> target) { super.onBuildHeaders(target); loadHeadersFromResource(R.xml.prefs_headers,  target); } Danny Fürniß, 25.11.2012, 9 Demo
  • 10. extends PreferenceFragment addPreferencesFromResource(R.xml.prefs_server); prefs_server.xml <?xml version="1.0" encoding="utf‐8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="@string/prefsServerSettings"> <EditTextPreference android:title="@string/prefsServerUrl"  android:key="prefsServerUrl"/> <CheckBoxPreference android:title="@string/prefsServerWifiOnly"  Danny Fürniß, 25.11.2012, 10 android:key="prefsServerWifiOnly"/> </PreferenceCategory> </PreferenceScreen>
  • 11. SharedPreferences lesen und schreiben prefs = PreferenceManager.getDefaultSharedPreferences(this); String prefsServerUrl =  prefs.getString("<key>", "<default‐value>"); SharedPreferences.Editor editor = prefs.edit(); editor.putString("<key>", "<value>"); Danny Fürniß, 25.11.2012, 11 editor.commit();
  • 13. SQLite • Keine Konfiguration notwendig • Kein Datenbank-Server • Single-File Datenbank (Filesystem-Security) • Open Source • In Android integriert • Keine strikte statische Typisierung • sqlite.org Danny Fürniß, 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 Fürniß, 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() • Ermöglicht Zugriff auf die Datenbank • getReadableDatabase() • getWritableDatabase() Danny Fürniß, 25.11.2012, 15 Demo
  • 16. onCreate() public void onCreate(SQLiteDatabase db) { db.execSQL(NewsItemContract.Table.CREATE_TABLE_NEWS); db.execSQL("CREATE TABLE xyz (_id PRIMARY KEY AUTOIN…"); } Danny Fürniß, 25.11.2012, 16
  • 17. onUpgrade() public void onUpgrade(SQLiteDatabase db,  int oldVersion, int newVersion) { db.execSQL("drop table if exists " +  NewsItemContract.Table.NEWS); onCreate(db); } Danny Fürniß, 25.11.2012, 17
  • 18. Danny Fürniß, 25.11.2012, 18 E E T A R E A D E T A P D E E E L T
  • 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 Fürniß, 25.11.2012, 19
  • 20. query() SQL Interface SELECT edvNr, name projection/columns FROM lehrveranstaltung table WHERE name selection = "Prof. Dr.‐Ing. Vogelsang" selectionArgs groupBy = null Danny Fürniß, 25.11.2012, 20 having = null ORDER BY edvNr orderBy
  • 21. update() db.update( table, values, whereClause, whereArgs ); Danny Fürniß, 25.11.2012, 21
  • 22. delete() db.delete( table, whereClause, whereArgs ); Danny Fürniß, 25.11.2012, 22
  • 24. Cursor nutzen _id edvNr name …         0                  1                 2                  3 int edvNrIndex Danny Fürniß, 25.11.2012, 24 = cursor.getColumnIndex(„edvNr“)    String edvNr =   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, "Insert fehlgeschlagen", e); Danny Fürniß, 25.11.2012, 25 } finally { db.endTransaction(); } Bildquelle: http://developer.android.com/design/patterns/actionbar.html
  • 27. Permissions android.permission.INTERNET android.permission.ACCESS_NETWORK_STATE Danny Fürniß, 25.11.2012, 27
  • 28. 10.0.2.2 IP‐Adresse für das Host‐System im Android Emulator Danny Fürniß, 25.11.2012, 28
  • 29. Apache Http Client HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(host +   "/api/persons?type=ProfessorInnen"); // Response lesen HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String content = ""; StringBuilder responseTxt = new StringBuilder();  while ((content = reader.readLine()) != null) { responseTxt.append(content); Danny Fürniß, 25.11.2012, 29 } Demo
  • 30. java.net.HttpUrlConnection URL newsUrl = new URL(host + "/api/news.json");  HttpURLConnection conn = (HttpURLConnection)  newsUrl.openConnection(); // Response lesen InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String content = ""; StringBuilder response = new StringBuilder(); while ((content = reader.readLine()) != null) { response.append(content); Danny Fürniß, 25.11.2012, 30 } Demo Quelle: http://android-developers.blogspot.de/2011/09/androids-http-clients.html
  • 32. Representational State Transfer (REST) Architekturstil HTTP-Verben basierend auf WWW POST GET URI, Ressourcen, Repräsentationen http://localhost:8180/api/news PUT http://localhost:8180/api/news/3 http://localhost:8180/api/persons DELETE Danny Fürniß, 25.11.2012, 32 etc. json, xml, html, etc. http://www.slideshare.net/dnene/rest‐ representational‐state‐transfer‐explained
  • 33. JSON JSONObject JSONArray JSONObject { "newsItem" : [ { "id" : 3, "imageFileName" : "news3.jpg", "pictureUri" : "http://localhost:8180/images/news3.jpg", "published" : "2011‐12‐20T13:07:54.480+01:00", "teaser" : "für Innovationen in der Hochschullehre", "title" : "Prof. Dr. Andreas Heberle erhält für gute Lehre Förderpreis von 50 000 Euro" } ] } Danny Fürniß, 25.11.2012, 33 Demo
  • 34. XML APIs SAX (Simple API for XML) DOM (Document Object Model) StAX (Streaming API for XML) Danny Fürniß, 25.11.2012, 34 Quelle: http://www.torsten-horn.de/techdocs/java-xml.htm
  • 35. XmlPullParser XmlPullParserFactory.newPullParser(). Danny Fürniß, 25.11.2012, 35 Quelle: http://www.xmlpull.org; http://android-developers.blogspot.com/2011/12/watch-out-for-xmlpullparsernexttext.html
  • 36. XML START_TAG, name = person START_TAG, name = akademischerTitel Text <person> <akademischerTitel>Prof. Dr.</akademischerTitel> <displayName>Albrecht, Ditzinger</displayName> <imageURI>http://localhost:8180/images/I_2e8f4d534f.jpg</imageURI> <personURI>http://localhost:8180/api/persons/3</personURI> </person> Danny Fürniß, 25.11.2012, 36 END_TAG, name = person Demo
  • 37. Danny Fürniß, 25.11.2012, 37 ContentProvider
  • 38. Danny Fürniß, 25.11.2012, 38 ContentProvider
  • 39. URIs Multi Item content://com.dfuerniss.pva.ss2012.database.contentprovider/lehrveranstaltungen Single Item content://com.dfuerniss.pva.ss2012.database.contentprovider/lehrveranstaltungen/# Platzhalter für die Id der  Lehrveranstaltung Danny Fürniß, 25.11.2012, 39 Demo
  • 40. ContentResolver Cursor cursor =  getContentResolver().query( uri,  projection,  selection,  selectionArgs,  sortOrder ); Danny Fürniß, 25.11.2012, 40
  • 41. android:authorities <provider android:name=".provider.LehrveranstaltungContentProvider"  android:authorities= "com.dfuerniss.pva.ss2012.database.contentprovider"> </provider> Danny Fürniß, 25.11.2012, 41
  • 42. Danny Fürniß, 25.11.2012, 42 extend ContentProvider Demo
  • 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 Fürniß, 25.11.2012, 45
  • 46. implements LoaderCallbacks<Cursor> 1 @Override public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) { Log.i(TAG, "creating loader for id: " + loaderId); AsyncTaskLoader<Cursor> loader = null; if (loaderId == NEWS_LOADER) { Log.i(TAG, "creating news loader"); loader = new AsyncTaskLoader<Cursor>(this) { … }; } return loader; Danny Fürniß, 25.11.2012, 46 }
  • 47. implements LoaderCallbacks<Cursor> 2 @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { Log.i(TAG, "loader finished: " + loader.getId()); if (loader.getId() == NEWS_LOADER) { newsAdapter.swapCursor(cursor); } } @Override public void onLoaderReset(Loader<Cursor> loader) { Log.i(TAG, "loader reset: " + loader.getId()); Danny Fürniß, 25.11.2012, 47 if (loader.getId() == NEWS_LOADER) { newsAdapter.swapCursor(null); } } Demo
  • 48. AsyncTaskLoader @Override public Cursor loadInBackground() { Log.i(TAG, "load in background"); SQLiteDatabase db = ((Application) getApplication()) .getDbHelper().getReadableDatabase(); return db.query( NewsItemContract.Table.NEWS,  // Projection muss _id enthalten! NewsItemContract.Query.PROJECTION_ALL,  selection,  selectionArgs,  groupBy,  having,  Danny Fürniß, 25.11.2012, 48 orderBy); } @Override public void onStartLoading() { …forceLoad()… }
  • 49. CursorLoader CursorLoader cl =  new CursorLoader(context,  URI,  projection,  selection,  selectionArgs,  sortOrder ); Danny Fürniß, 25.11.2012, 49
  • 50. android:installLocation internalOnly (default) auto preferExternal Danny Fürniß, 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 in the Creative Commons 3.0 Attribution License. Danny Fürniß, 25.11.2012, 51