0% found this document useful (0 votes)
82 views15 pages

3-4 Android

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views15 pages

3-4 Android

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Notes: Mobile Application Development, Class: BCA TY, Unit I: Introduction to android

UNIT III: MULTIMEDIA, ANIMATION AND GRAPHICS

3.1 Playing Audio, Video.

We can play and control the audio files in android by the help of MediaPlayer
class.
MediaPlayer class we can easily fetch, decode and play both audio and video
files with minimal setup.

The android media framework provides built-in support for playing a variety of
common media types, such as audio or video. We have multiple ways to play
audio or video but the most important component of media framework is
MediaPlayer class.
MediaPlayer class we can access audio or video files from application (raw)
resources, standalone files in file system or from a data stream arriving over a
network connection and play audio or video files with the multiple playback
options such as play, pause, forward, backward, etc.
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
mPlayer.start();

The second parameter in create() method is the name of the song that we want
to play from our application resource directory (res/raw). create a new raw
folder under res directory and add a properly encoded and formatted media
files in it.

There are list of methods of MediaPlayer class.

1. public void setDataSource(String path)- sets the data source (file path
or http url) to use.
2. public void prepare()-prepares the player for playback synchronously.
3. public void start()-it starts or resumes the playback.
4. public void stop()-it stops the playback.
5. public void pause()-it pauses the playback.
6. public void seekTo(int millis)- seeks to specified time in miliseconds.
7. public int getDuration()-returns duration of the file.

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 1


Notes: Mobile Application Development, Class: BCA TY, Unit I: Introduction to android

8. public void setVolume(float leftVolume,float rightVolume)- sets the


volume on this player.

3.2 Rotate Animation


Rotate animation is used to change the appearance and behavior of the objects
over a particular interval of time. The Rotate animation will provide a better
look and feel for our applications.
the animations are useful when we want to notify users about the changes
happening in our app, such as new content loaded or new actions available, etc.
Create XML File to Define Animation
We need to create an XML file that defines the type of animation to perform in a
new folder anim under res directory (res a anim a rotate.xml) with required
properties. In case, if anim folder does not exist in res directory, create a new
one.
To use Rotate animation in our android applications, we need to define a new
xml file with <rotate> tag
To Rotate animation in Clockwise, we need to set android:fromDegrees and
android:toDegrees property values and these will defines a rotation angles

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


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/cycle_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%" android:pivotY="50%"
android:duration="5000" /> </set>

To Rotate animation in Anti Clockwise, we need to set android:fromDegrees


and android:toDegrees property values and these will defines a rotation angles
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/cycle_interpolator">
<rotate android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" /> </set>

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 2


Notes: Mobile Application Development, Class: BCA TY, Unit I: Introduction to android

3.3 FadeIn / FadeOut Animation.


Fade In and Fade Out animations are used to change the appearance and
behavior of the objects over a particular interval of time. The Fade In and Fade
Out animations will provide a better look and feel for our applications.

To use Fade In or Fade Out animations in our android applications, we need to


define a new XML file with <alpha> tag

Fade In animation

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


xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha android:duration="2000"
android:fromAlpha="0.1"
android:toAlpha="1.0">
</alpha>
</set>

Fade Out animation

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


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha android:duration="2000"
android:fromAlpha="1.0" android:toAlpha="0.1"
>
</alpha>
</set>

ImageView img = (ImageView)findViewById(R.id.imgvw);


Animation aniFade =
AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
img.startAnimation(aniFade);

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 3


Notes: Mobile Application Development, Class: BCA TY, Unit I: Introduction to android

3.3 Zoom Animation. Zoom


Animation
Zoom In and Zoom Out animations are used to enlarge and reduce the size of a
view in Android applications respectively. These types of animations are often
used by developers to provide a dynamic nature to the applications.
To use Zoom In or Zoom Out animations in our android applications, we need
to define new XML files with <scale> tag
For Zoom In animation, we need to set android:pivotX="50%" and
android:pivotY="50%" to perform the zoom from the centre of the element. Also,
we need to use fromXScale, fromYScale attributes to define the scaling of an
object and we need keep these values lesser than toXScale, toYScale
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000" android:fromXScale="2"
android:fromYScale="2" android:pivotX="50%"
android:pivotY="50%" android:toXScale="4" android:toYScale="4" >
</scale>
</set>
Zoom Out animation is same as Zoom In animation but fromXScale, fromYScale
attribute values must be greater than toXScale, toYScale
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:duration="2500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale=".2" android:toYScale=".2"
/>
</set>

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 4


Notes: Mobile Application Development, Class: BCA TY, Unit I: Introduction to android

3.4 Scale Animation

Scale Animation is basically to increase or decrease the size of the View.

There is a class ScaleAnimation. We need to create instance of ScaleAnimation (Can be done in


XML also) to do the work. One of the main constructor of this class is:

public ScaleAnimation(
float fromX, float toX,
float fromY, float toY,
int pivotXType, float pivotXValue,
int pivotYType, float pivotYValue)

Let us understand these parameters. Description of these parameters as given in Android SDK
documentation:

fromX Horizontal scaling factor to apply at the start of the animation


toX Horizontal scaling factor to apply at the end of the animation
fromY Vertical scaling factor to apply at the start of the animation
toY Vertical scaling factor to apply at the end of the animation
pivotXType Specifies how pivotXValue should be interpreted. One of Animation.ABSOLUTE,
Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT.
pivotXValue The X coordinate of the point about which the object is being scaled, specified as an
absolute number where 0 is the left edge. (This point remains fixed while the object changes size.)
This value can either be an absolute number if pivotXTypeis ABSOLUTE, or a percentage (where 1.0
is 100%) otherwise.
pivotYType Specifies how pivotYValue should be interpreted. One of Animation.ABSOLUTE,
Animation.RELATIVE_TO_SELF, or Animation.RELATIVE_TO_PARENT.
pivotYValue The Y coordinate of the point about which the object is being scaled, specified as an
absolute number where 0 is the top edge. (This point remains fixed while the object changes size.)
This value can either be an absolute number if pivotYType is ABSOLUTE, or a percentage (where
1.0 is 100%) otherwise.

The End

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 5


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

UNIT IV: MANAGING DATA STORAGE, ADVANCED COMPONENTS OF ANDROID


AND LOCATION MAP

4.1 Shared Preferences

Android provides many ways of storing data of an application. One of this way is
called Shared Preferences. Shared Preferences allow you to save and retrieve
data in the form of key,value pair.
In order to use shared preferences, you have to call a method
getSharedPreferences() that returns a SharedPreference instance pointing to
the file that contains the values of preferences. SharedPreferences
sharedpreferences =
getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
MODE_APPEND
This will append the new preferences with the already existing preferences
MODE_PRIVATE
It is a default mode. MODE_PRIVATE means that when any preference file is
created with private mode then it will not be accessible outside of your
application. This is the most common mode which is used.
MODE_WORLD_READABLE
If developer creates a shared preference file using mode world readable then it
can be read by anyone who knows it’s name, so any other outside application
can easily read data of your app. This mode is very rarely used in App.
MODE_WORLD_WRITEABLE
It’s similar to mode world readable but with both kind of accesses i.e read and
write. This mode is never used in App by Developer. You can save something
in the sharedpreferences by using
SharedPreferences.Editor class. You will call the edit method of
SharedPreference instance and will receive it in an editor object.
Editor editor = sharedpreferences.edit(); editor.putString("key",
"value");
editor.commit();
Apart from the putString method , there are methods available in the editor
class that allows manipulation of data inside shared preferences. clear()
It will remove all values from the editor
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n); editor.putString(Phone, ph);
editor.putString(Email, e); editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 1


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

4.2 Internal Storage, External Storage


Internal storage is the storage of the private data on the device memory. By
default these files are private and are accessed by only your application and
get deleted , when user delete your application.

Writing file

In order to use internal storage to write some data in the file, call the
openFileOutput() method with the name of the file and the mode. The mode
could be private , public e.t.c.

FileOutputStream fOut = openFileOutput("file name


here",MODE_WORLD_READABLE);

The method openFileOutput() returns an instance of FileOutputStream. So you


receive it in the object of FileInputStream. After that you can call write method
to write data on the file.

String str = "data";


fOut.write(str.getBytes()); fOut.close();

Reading file

In order to read from the file you just created , call the openFileInput() method
with the name of the file. It returns an instance of FileInputStream.

FileInputStream fin = openFileInput(file);

After that, you can call read method to read one character at a time from the file
and then you can print it.

int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
//string temp contains all the data of the file.
fin.close();

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 2


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

Apart from the the methods of write and close, there are other methods
provided by the FileOutputStream class for better writing files.

External Storage

External Storage is useful to store the data files publically on the shared
external storage using the FileOutputStream object. After storing the data files
on external storage, we can read the data file from external storage media using
a FileInputStream object.

The data files saved in external storage are word-readable and can be modified
by the user when they enable USB mass storage to transfer files on a computer.

Grant Access to External Storage

To read or write files on the external storage, our app must acquire the
WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system
permissions. For that, we need to add the following permissions in the android
manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Write a File to External Storage


By using android FileOutputStream object and
getExternalStoragePublicDirectory method, we can easily create and write
data to the file in external storage public folders.
Following is the code snippet to create and write a public file in the device
Downloads folder.

String FILENAME = "user_details"; String name = "suresh"; File folder =


Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DO
WNLOADS); File myFile = new File(folder, FILENAME); FileOutputStream
fstream = new FileOutputStream(myFile);
fstream.write(name.getBytes()); fstream.close();

we are creating and writing a file in device public Downloads folder by using
getExternalStoragePublicDirectory method. We used write() method to

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 3


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

write the data in file and used close() method to close the stream. Read a
File from External Storage
By using the android FileInputStream object and
getExternalStoragePublicDirectory method, we can easily read the file from
external storage.

4.3 SQLite Databases

SQLite is an open-source relational database i.e. used to perform database


operations on android devices such as storing, manipulating or retrieving
persistent data from the database.
SQLite is a Structure query base database, open source, light weight, no network
access and standalone database. It support embedded relational database
features.
It is embedded in android bydefault. So, there is no need to perform any
database setup or administration task.
Here, we are going to see the example of sqlite to store and fetch the data. Data
is displayed in the logcat. For displaying data on the spinner or listview, move to
the next page.
SQLiteOpenHelper class provides the functionality to use the SQLite database.

SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database
creation and version management. For performing any database operation, you
have to provide the implementation of onCreate() and onUpgrade() methods
of SQLiteOpenHelper class.

public class DatabaseHelper extends SQLiteOpenHelper { public


static final String DATABASE_NAME = "Student.db"; public static
final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID"; public
static final String COL_2 = "NAME"; public
static final String COL_3 = "SURNAME";
public static final String COL_4 = "MARKS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 4


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

@Override
public void onCreate(SQLiteDatabase db) { db.execSQL("create table " +
TABLE_NAME +" (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db);
}
public boolean insertData(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks); long result =
db.insert(TABLE_NAME,null ,contentValues); if(result == -
1) return false; else return true;
}

public Cursor getAllData() {


SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null); return
res;
}

public boolean updateData(String id,String name,String surname,String marks)


{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id); contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id }); return
true;
}
public Integer deleteData (String id) {

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 5


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

SQLiteDatabase db = this.getWritableDatabase(); return


db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}

public void DeleteData() {


btnDelete.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
if(deletedRows > 0)
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Deleted",Toast.LENGTH_LONG).show();
}
}
);
}

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 6


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

4.4 Content provides And Remote Databases

A content provider manages access to a central repository of data. A


provider is part of an Android application, which often provides its own
UI for working with the data.

However, content providers are primarily 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 interprocess communication and secure data
access.

Typically you work with content providers in one of two scenarios: implementing
code to access an existing content provider in another application or creating a new
content provider in your application to share data with other applications.

This page covers the basics of working with existing content providers. To learn
about implementing content providers in your own applications, see Create a
content provider.

This topic describes the following:

• How content providers work.

• The API you use to retrieve data from a content provider.

• The API you use to insert, update, or delete data in a content provider.

• Other API features that facilitate working with providers.

Content URI

Content URI(Uniform Resource Identifier) is the key concept of Content


providers. To access the data from a content provider, URI is used as a query
string.

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 7


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

Following are the steps which are essential to follow in order to create a
Content Provider:
1. Create a class in the same directory where the that MainActivity file
resides and this class must extend the ContentProvider base class.

2. To access the content, define a content provider URI address.


3. Create a database to store the application data.

4. Implement the six abstract methods of ContentProvider class.


5. Register the content provider in AndroidManifest.xml file
using <provider> tag.

Remote databases

A remote database means that you can access the data from this database in
a remote location. A lot of applications are used to send the data to the
remote database module. I will show you how to send the data to the remote
database in an Android Application, using Android Studio.

4.5 Web App

A web application is a program stored on a remote server and delivered to


the user via a browser. Similar to a website, but not entirely.
A website is content displayed to the user and is not meant for interactions.
The purpose of websites is to display static content to the user—for example,
portfolios, official websites of brands, etc.

Web application, however, is intended for interaction between the user and
the application. To explain it more clearly, let’s take a social media platform
like Instagram. What will you usually do on Instagram? You scroll through
various posts and reels, send messages to your friends, and share your day.
These activities are the interactions from your side with the web application.
This usually is not possible on websites.

There are a Examples of web applications we are not aware of and still are
using every day. Some of them are:

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 8


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

1. Online shopping carts


2. Email
3. Word processors
4. Photo and video editing
5. File scanning
6. Spreadsheets
7. Presentations

Pros:

• Web applications are flexible. They can be accessed via any browser on
mobile and desktop.
• Web applications need not need to be updated manually as the web
application updates on its own.
• They don’t require to be installed on mobile; thus, the memory and
data are also saved.
• The applications are cross-platform and can be run on any OS.

Cons:

• Web applications are accessed via browsers; hence they rely on the
internet and cannot be accessed offline.
• If any website of the web application experiences even a slight error,
the whole application will likely experience performance lag.
• Web applications run at a relatively slower speed.
• Web applications are highly likely to experience security breaches.

4.5 JSON Parsing

JSON stands for JavaScript Object Notation. It is structured, light weight,


human readable and easy to parse. It’s a best alternative to XML when our
android app needs to interchange data from server. XML parsing is very
complex as compare to JSON parsing.
JSON is shorter, quicker and easier way to interchange data from server. JSON
is great success and most of the API available support JSON format.

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 9


Notes: Mobile Application Development, Class: BCA TY, Unit IV: Managing Data Storage,

Android Provide us four different classes to manipulate JSON data. These


classes are JSONObject, JSONArray, JSONStringer and JSONTokenizer.

JSON Elements In Android:

In Android, JSON consist of many components. Below we define some


common components.
1. Array([): In a JSON, square bracket ([) represents a JSONArray.
JSONArray values may be any mix of JSONObjects, other JSONArrays,
Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may not
be NaNs, infinities, or of any type not listed here.

2. Objects({): In a JSON, curly bracket ({) represents a JSONObject. A


JSONObject represents the data in the form of key and value pair.
JSONObject values may be any mix of other JSONObjects, JSONArrays,
Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values may not
be NaNs, infinities, or of any type not listed here.

3. key: A JSONObject contains a key that is in string format. A pair of key and
value creates a JSONObject.

4. Value: Each key has a value that could be primitive datatype(integer, float,
String etc).

Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 10

You might also like