Download Android - part IV

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

File locking wikipedia , lookup

Semantic Web wikipedia , lookup

Data analysis wikipedia , lookup

Expense and cost recovery system (ECRS) wikipedia , lookup

Computer file wikipedia , lookup

PL/SQL wikipedia , lookup

SQL wikipedia , lookup

Object storage wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Information privacy law wikipedia , lookup

Database wikipedia , lookup

SAP IQ wikipedia , lookup

Data vault modeling wikipedia , lookup

Open data in the United Kingdom wikipedia , lookup

Business intelligence wikipedia , lookup

3D optical data storage wikipedia , lookup

Versant Object Database wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Relational model wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Transcript
Data Management
Different options
• Most Android apps need to save data
– Shared Preferences for private primitive data in key-value
pairs
– Internal Storage for private data on the device memory
– External Storage for public data on the shared external
storage
– SQLite Databases for structured data in a private database
– Network Connection for data on the web with your own
network server
Shared preferences
• Class SharedPreferences class provides a general
framework to save and retrieve persistent key-value pairs
of primitive data types (booleans, floats, ints, longs, and
strings)
– These data will persist across user sessions
• To get a SharedPreferences object we can use
getSharedPreferences() if we need multiple preferences
files, or getPreferences() one preferences file is enough
• Call edit() to get a SharedPreferences.Editor, putBoolean()
or putString(), and then commit()
• Call getBoolean() or getString() to read values
Example
File system
• Internal storage - Always available
– Files saved here accessible by only your app
– System removes all app's files when app unistalled
– Best when neither the user nor other apps can access files
• External storage - Not always available
– Files saved here may be read outside of our control
– System removes app's files only in particular cases
– Best place for files that don't require access restrictions
• Files we want to share with other apps
• Files the user can access with a computer
– Permissions in the manifest needed
– Before you do any work with the external storage you should always check
whether the media is available
Internal storage
• To create and write a private file
– Call openFileOutput() with the name of the file and the operating
mode
• This returns a FileOutputStream
– Write to the file with write() and close the stream with close()
• To read from a file
– Call openFileInput() and pass it the name of the file to read
• This returns a FileInputStream
• Read bytes from the file with read() and close the stream
with close()
Other options
• getCacheDir() to open a file that represents the internal
directory where your application should save temporary
cache files
• getFilesDir() returns the absolute path to the directory
where internal files are saved
• getDir() creates (or opens) a directory
• deleteFile() deletes a file
• fileList() returns an array of files currently saved by
your application
SQLite
• Android provides full support for SQLite databases
– Lightweight database based on SQL
– Standard SQL syntax
• Any database is accessible by name to any class in the
application, but not outside the application
• To create a new database, we must subclass
SQLiteOpenHelper and override method onCreate() to
execute SQLite commands to create tables
Companion class (contract class)
publicstaticabstractclassFeedEntry implementsBaseColumns {
publicstaticfinalStringTABLE_NAME="entry";
publicstaticfinalStringCOLUMN_NAME_ENTRY_ID="entryid";
publicstaticfinalStringCOLUMN_NAME_TITLE="title";
publicstaticfinalStringCOLUMN_NAME_SUBTITLE="subtitle";
privatestaticfinalStringTEXT_TYPE="TEXT";
privatestaticfinalStringCOMMA_SEP=",";
privatestaticfinalStringSQL_CREATE_ENTRIES=
"CREATETABLE"+FeedEntry.TABLE_NAME +"("+
FeedEntry._ID+"INTEGERPRIMARYKEY,"+
FeedEntry.COLUMN_NAME_ENTRY_ID +TEXT_TYPE+COMMA_SEP+
FeedEntry.COLUMN_NAME_TITLE +TEXT_TYPE+COMMA_SEP+")";
}
privatestaticfinalStringSQL_DELETE_ENTRIES=
"DROPTABLEIFEXISTS"+FeedEntry.TABLE_NAME;
publicclassFeedReaderDbHelper extendsSQLiteOpenHelper {
//Ifyouchangethedatabaseschema,youmustincrementthedatabaseversion.
publicstaticfinalint DATABASE_VERSION=1;
publicstaticfinalStringDATABASE_NAME="FeedReader.db";
publicFeedReaderDbHelper(Contextcontext){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
publicvoidonCreate(SQLiteDatabase db){
db.execSQL(SQL_CREATE_ENTRIES);
}
publicvoidonUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
publicvoidonDowngrade(SQLiteDatabase db,int oldVersion,int newVersion){
onUpgrade(db,oldVersion,newVersion);
}
Then …
• getWritableDatabase() and getReadableDatabase()
allow us to write to and read from the database
– They return a SQLiteDatabase object that represents the
database and provides methods for SQLite operations
• query() allows one to issue queries to the database
– Every query returns a Cursor that points to all the rows and
columns found by the query
Insert data
FeedReaderDbHelper mDbHelper =newFeedReaderDbHelper(getContext());
//Getsthedatarepositoryinwritemode
SQLiteDatabase db =mDbHelper.getWritableDatabase();
//Createanewmapofvalues,wherecolumnnamesarethekeys
ContentValues values=newContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID,id);
values.put(FeedEntry.COLUMN_NAME_TITLE,title);
values.put(FeedEntry.COLUMN_NAME_CONTENT,content);
//Insertthenewrow,returningtheprimarykeyvalueofthenewrow
longnewRowId;
newRowId =db.insert(
FeedEntry.TABLE_NAME,
FeedEntry.COLUMN_NAME_NULLABLE,
values);
FeedReaderDbHelper mDbHelper =newFeedReaderDbHelper(getContext());
SQLiteDatabase db =mDbHelper.getReadableDatabase();
//HowyouwanttheresultssortedintheresultingCursor
StringsortOrder =FeedEntry.COLUMN_NAME_UPDATED +"DESC";
Cursorc=db.query(
FeedEntry.TABLE_NAME,
//Thetabletoquery
projection, //Thecolumnstoreturn
selection, //ThecolumnsfortheWHEREclause
selectionArgs, //ThevaluesfortheWHEREclause
null,
//don'tgrouptherows
null,
//don'tfilterbyrowgroups
sortOrder
//Thesortorder
);
Read data
//Defineaprojectionthatspecifieswhichcolumnsfromthedatabase
//youwillactuallyuseafterthisquery.
String[]projection={
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_UPDATED,
...
};
In conclusion
• insert() to add data
• query() to retrieve data, and then use a Cursor to
navigate them
• delete() to remove data (rows)
• update() to modify data
Google Cloud Endpoints
• Provides a simple way to develop a shared web backend and also
provides critical infrastructures, such as OAuth 2.0 authentication
Content providers
• Manage access to a structured set of data
– Encapsulate data and provide mechanisms for defining data security
• Are the standard interface that connects data in one process with
code running in another process
• Applications usually must request specific permissions in their
manifest files to access providers
• There is no need for a provider if you don't intend to share your
data with other applications
• Android itself includes content providers that manage data such
as audio, video, images, and personal contact information
How to use it
• Content providers are primarily intended to be used by other applications, which
access the provider using a provider client object
• Together, providers and provider clients offer a consistent, standard interface to
data that also handles inter-process communication and secure data access
• A content provider presents data to external applications as one or more tables
that are similar to the tables found in a relational database
• An application accesses the data from a content provider with a ContentResolver
client object
– This object provides the basic "CRUD" (create, retrieve, update, and delete) functions
of persistent storage
• The ContentResolver object (client process) and the ContentProvider object in the
application (server) automatically handle inter-process communication
– ContentResolver has methods that call identically-named methods of ContentProvider
– ContentProvider also acts as an abstraction layer on top of its repository of data
User Dictionary
mCursor = getContentResolver().query
Threads and services
Activity (1)
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Push the menu button!");
setContentView(tv);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
int base = Menu.FIRST;
menu.add(base,1,1,"View web page");
menu.add(base,2,2,"Search on Google");
menu.add(base,3,3,”Show Directions");
menu.add(base,4,4,"dial");
return true;
}
Activity (2)
}
public boolean onOptionsItemSelected(MenuItem item) {
System.err.println("item="+item.getItemId());
if (item.getItemId()==1) IntentUtils.invokeWebBrowser(this);
else if (item.getItemId()==2) IntentUtils.invokeWebSearch(this);
else if (item.getItemId()==3) IntentUtils.showDirections(this);
else if (item.getItemId()==4) IntentUtils.dial(this);
else return super.onOptionsItemSelected(item);
return true;
}
IntentUtils
public class IntentUtils {
public static void invokeWebBrowser(Activity activity) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.polimi.it"));
activity.startActivity(intent);
}
public static void invokeWebSearch(Activity activity) {
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH,
Uri.parse("http://www.google.it"));
activity.startActivity(intent);
}
public static void dial(Activity activity) {
Intent intent = new Intent(Intent.ACTION_DIAL);
activity.startActivity(intent);
}
}
public static void showDirections(Activity activity) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://maps.google.it/maps?saddr=Milano&daddr=Como"));
activity.startActivity(intent);
}
How to call apps
Targetapplication IntentURI
Browser
http://web_address
https://web_address
""(emptystring)
http://web_address
https://web_address
Intentaction
VIEW
OpenabrowserwindowtotheURL
specified
WEB_SEARCH
Opensthefileatthelocationonthedevice
inthebrowser
Dialer
GoogleMaps
GoogleStreetview
Result
tel:phone_number
CALL
tel:phone_number
voicemail:
DIAL
geo:latitude,longitude
geo:latitude,longitude?z=zoom
geo:0,0?q=my+street+address
geo:0,0?q=business+near+city
VIEW
google.streetview:cbll=lat,lng&cbp=
VIEW
1,yaw,,pitch,zoom&mz=mapZoom
Callstheenteredphonenumber.This
requiresyourapplicationtorequestthe
followingpermissioninyourmanifest:
<uses-permission
id="android.permission.CALL_PHONE"/>
Dials(butdoesnotactuallyinitiatethe
call)thenumbergiven(orthestored
voicemailonthephone)
OpenstheMapsapplicationtothegiven
locationorquery
OpenstheStreetViewapplicationtothe
givenlocation.TheURIschemeisbasedon
thesyntaxusedforStreetViewpanorama
informationinGoogleMapsURLs
http://developer.android.com/guide/appendix/app-intents.html