Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

DFP40093 JTMK | PUO

DFP40093 JTMK | PUO

Construct Persistence Data in


Android

Apply Graphics And Animations

Apply Multimedia Component


JTMK|PUO
JTMK|PUO

App data is private to the application


Several mechanism
– State Storage: Ram memory!
• Mechanism for saving activity’s state temporarily
– Preferences
• Lightweight mechanism to store and retrieve key-‐value pairs
– Files
• Open and save files on the device or removable storage
– SQLite databases
• Databases
Content provider is used to give the data to other apps
JTMK|PUO

• Shared Preferences
⚬ Store private primitive data in key-value pairs.
• Files
⚬ Store private data on the device memory.
⚬ Store public data on the shared external storage.
• SQLite Databases
⚬ Store structured data in a private database.
• Network Connection
⚬ Store data on the web with your own network server.
JTMK|PUO

• Useful for storing and retrieving primitive data in key value pairs.
• Lightweight usage, such as saving application settings.
• Typical usage of SharedPreferences is for saving application such as
username and password, auto login flag, remember-user flag etc.
JTMK|PUO

• It provides general framework for saving and retrieving


• To get Shared Preferences, use
⚬ getSharedPreferences(String name)
■ Use if you need multiple preference files (identified by name)
⚬ getPreferences()
■ Use if only one preferences file is needed
• To write values, call edit() to get SharedPreferences.Editor to be used
when adding values to file
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
JTMK|PUO
@Override

protected void onCreate(Bundle state){


super.onCreate(state); . . .

// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
}
@Override

protected void onStop(){

super.onStop();

// We need an Editor object to make preference changes.


// All objects are from android.context.Context

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);


SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);

// Commit the edits! editor.commit();


}
}
JTMK|PUO

• Its possible to store files on the mobile device or on a removable


storage
• Current application folder only. Exception throws otherwise
⚬ Modes : MODE_PRIVATE, MODE_WORLD_READABLE,
MODE_WORLD_WRITABLE .
⚬ Reading
■ openFileInput()
⚬ Writing
■ openFileOutput()
• Standard Java streams after that
JTMK|PUO

• You can save static files into res/raw directory


• Accessing using openRawResource (R.raw.<filename>)
• Returns InputStream
• Cannot write to data
JTMK|PUO

// Write
String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);


fos.write(string.getBytes());
fos.close();

// Read
FileInputStream fis = openFileInput(FILENAME);
int byteChar;
while((byteChar = fis.read()) != -1)
{
System.out.println((char) byteChar);
}
fis.close()
JTMK|PUO

• Android Provides full support for SQLite


• To create a new SQLitedatabase
⚬ create a subclass of SQLiteOpenHelper
⚬ override the onCreate() method,
■ execute a SQLite command to create tables in the database.
JTMK|PUO

• Wraps best practice pattern for creating, opening and upgrading


databases
• You hide the logic used to decide if a database needs to be created
or upgraded before it's opened
JTMK|PUO

• Database communication
⚬ call getWritableDatabase()
getReadableDatabase()
• It returns a SQLiteDatabase object for SQLite operations.
JTMK|PUO

• Use to execute SQLitequeries,

• Every SQLite query returns a Cursor

• Cursor used to hold query result and read rows and columns.

• Cursor points to all the rows found by the query.


JTMK|PUO

• Create a database • insert rows

• define SQL tables • delete rows

• indices • change rows

• queries • run queries and

• views • administer a SQLLite Database

• triggers • file
JTMK|PUO

public void openDatabase()


{ try
{
db = this.openOrCreateDatabase("MyTestDatabase.db", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE MYDATA(firstname TEXT, lastname TEXT)");
} catch (SQLiteException e) {
e.printStackTrace();
}
}
JTMK|PUO

public void insertRows() {


try {
db.execSQL("INSERT INTO MYDATA VALUES ('Jack',
'Smith')");
}
catch (Exception e) {
e.printStackTrace();
}
}
JTMK|PUO

public void readRows() {


try {
Cursor c = db.rawQuery("SELECT * FROM MYDATA", null);
String text = ""; c.moveToFirst();

for(int i=0; i<c.getCount(); i++)


{
text += c.getString(0) + " " + c.getString(1);
c.moveToNext();
} tv.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
JTMK|PUO

public class DictionaryOpenHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;


private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";

DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
JTMK|PUO

• The recommended way of sharing data in Android is to use content providers

• Generic interface for data

• Permission control and accessing using URI model

• NaAve databases available as Content Providers

• Publishing your own data source, other apps can incorporate your database
JTMK|PUO

• ApplicaAon context has Content Resolver which you can use to access data

⚬ ContentResolver cr = getContentResolver();

• For accessing other databases, you need a URI

• URI is arbitraty String, which is defined in manifest file


JTMK|PUO

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="fi.tamk"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CallMe"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<provider android:name=".Data"
android:authorities="fi.pohjolainen_jussi.provider.mycontentprovider">
</provider>

</application>

<uses-sdk android:minSdkVersion="8" />

</manifest>
JTMK|PUO

public class MyContentProvider extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ContentResolver cr = getContentResolver();

Uri uri =
Uri.parse("content://fi.pohjolainen_jussi.provider.mycontentprovider");

Cursor cursor = cr.query(uri, null, null, null, null);


}
}
JTMK|PUO

public class MyContentProvider extends ContentProvider {

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {...}

@Override
public String getType(Uri uri) {...}

@Override
public Uri insert(Uri uri, ContentValues values) {...}

@Override public boolean onCreate() {...}

@Override public Cursor query(Uri uri, String[] projection, String


selection,
String[] selectionArgs, String
sortOrder) {...}

@Override public int update(Uri uri, ContentValues values, String


selection,
String[] selectionArgs) {...}
}
DFP40093 JTMK | PUO

Construct Persistence Data in


Android

Apply Graphics And Animations

Apply Multimedia Component


JTMK|PUO
JTMK|PUO

Animations can add visual cues that notify users about what's going on in your app. They
are especially useful when the UI changes state, such as when new content loads or new
actions become available. Animations also add a polished look to your app, which gives it
a higher quality look and feel.

Android includes different animation APIs depending on what type of animation you want,
so this page provides an overview of the different ways you can add motion to your UI.
JTMK|PUO

When you want to animate a bitmap graphic such as an icon or illustration, you should use
the drawable animation APIs. Usually, these animations are defined statically with a
drawable resource, but you can also define the animation behavior at runtime.

An Animated Drawable
JTMK|PUO

When you need to change the visibility or position of views in your layout,
you should include subtle animations to help the user understand how the UI
is changing.
To move, reveal, or hide views within the current layout, you can use
the property animation system provided by the android.animation
package, available in Android 3.0 (API level 11) and higher.

A subtle animation when a dialog appears and disappears makes the UI change less jarring
JTMK|PUO

Animations should apply real-world physics so they are natural-looking


Example – they should maintain momentum when their target changes, and make smooth
transitions during any changes

To provide this, the Android Support library includes physics-based animation APIs that
rely on the laws of physics to control how your animations occur.
2 common physics-based animations
a) Spring Animation
b) Fling Animation

Animation built with Animation built with


ObjectAnimator physics-based APIs
JTMK|PUO

Spring Animation
❑ SpringForce class - customize spring's stiffness, its damping ratio, and its final position.
Fling Animation
❑ It use a friction force that is proportional to an object's velocity.

❑ Use it to animate a property of an object and to end the animation gradually

Spring release effect Fling animation


JTMK|PUO

On Android 4.4 (API level 19) and higher – you can use the transition framework to
create animations when you swap the layout within the current activity or fragment

It will executes an animation between 2 layout – when you specify starting and
ending layout, and type of animation

An animation to show more


details can be achieved by
either changing the layout or
starting a new activity
JTMK|PUO

The Android framework provides a rich set of powerful APIs for applying
animation to UI elements and graphics as well as drawing custom 2D and 3D
graphics.
JTMK|PUO

Android provides three animation systems for meeting the animation


needs of Android apps. From the most sophisticated "Property Animation"
to the simpler "View Animation" and "Drawable Animation".

1. Property Animation

❑The property animation system is the robust


framework that lets you animate any properties of
any objects, View or non-View objects, as well as
any custom types. It is the preferred method of
animation in Android. The "android.animation"
provides classes that handle property animation.
JTMK|PUO

2. View Animation

❑As the older animation system, "View Animation" is also


called "Tween Animation". It can only be used to animate
the content of a View, and is limited to simple
transformation such as moving, re-sizing, and rotation, but
not its background color. The "android.view.animation"
provides classes that handle "View Animation".
JTMK|PUO

3. Drawable Animation

❑Drawable animation works by displaying a running


sequence of "Drawable" resources, i.e. images, frame by
frame, inside a View object. It is implemented using the
"AnimationDrawable" class.
JTMK|PUO

Depending on the graphic types and the processing demand of your app,
you may choose from these options for drawing graphics on Android

1. Canvas

❑Android framework provides a set of 2D-drawing


APIs for rendering custom graphics either onto a
canvas using the various drawing methods provided
by the "Canvas" class.
JTMK|PUO

2. OpenGL ES

❑If you are venturing into 3D graphics or interacting gaming


apps, you should consider the "OpenGL ES" APIs
supported by the Android framework. It offers a set of
extremely powerful tools for manipulating and displaying
high-end animated 3D graphics that can be benefited
from the hardware acceleration of graphics processing
units (GPUs) provided on many Android devices.
DFP40093 JTMK | PUO

Construct Persistence Data in


Android

Apply Graphics And Animations

Apply Multimedia Component


JTMK|PUO

One of the class that can control playback of audio/video files and streams in
Android, it call MediaPlayer
MediaPlayer class – to access built-in mediaplayer services (audio, video e.t.c)

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

Method that returns an instance of MediaPlayer class.


JTMK|PUO

Song – make new folder (under your project) -> name it raw -> place
music file in it

start() method – music start playing from the beginning

pause() method – music will start playing from where it left (not in
the beginning)

mediaPlayer.start();
mediaPlayer.reset();
mediaPlayer.pause();

Method to start or stop the music To start music from the beginning
JTMK|PUO

Other methods provided by this class for better dealing with audio/video
files.
METHOD DESCRIPTION
isPlaying() This method just returns true/false indicating the song is playing or not
This method takes an integer, and move song to that particular position
seekTo(position)
millisecond

This method returns the current position of song in milliseconds


getCurrentPosition()
getDuration() This method returns the total time duration of song in milliseconds
reset() This method resets the media player
release() This method releases any resource attached with MediaPlayer object
setVolume(float leftVolume, float
This method sets the up down volume for this player
rightVolume)
setDataSource(FileDescriptor fd) This method sets the data source of audio/video file
This method takes an integer, and select the track from the list on that
selectTrack(int index)
particular index
getTrackInfo() This method returns an array of track information
JTMK|PUO

You might also like