Professional Documents
Culture Documents
Android Application
Development
Series II
Review
ASMATT (suki1207@uum.edu.my)
ASMATT (suki1207@uum.edu.my)
ASMATT (suki1207@uum.edu.my)
4) Choose No skin
5) Click ok. Accept other
defaults. Click this button to
create the emulator.
2) Click
here
4) Choose
this
ASMATT (suki1207@uum.edu.my)
ANDROID CODING
ASMATT (suki1207@uum.edu.my)
ASMATT (suki1207@uum.edu.my)
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
21.
android:onClick="handleClick"
22.
android:text="Button" />
You can give
any name
Between the
last (two) }
A new method (beside
onCreate) to handle
onClick event
ASMATT (suki1207@uum.edu.my)
myFirstButtonHandlerActivity.java
1.
package com.Suki.ButtonHandler;
2.
3.
4.
5.
6.
import
import
import
import
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.widget.EditText;
android.widget.TextView;
Should be similar
with your onClick
button in the
activity_main.xml
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25. }
Manipulate Numbers
(Create a new project HandleNumber)
ASMATT (suki1207@uum.edu.my)
4.
5.
6.
7.
8.
9.
10.
Exercise:
Power 3 Calculator
ASMATT (suki1207@uum.edu.my)
Try This:
Multiplication Calculator
6.
7.
8.
9.
TextView tv = (TextView)
findViewById(R.id.textView2);
tv.setText("Result is: " + hasil);
5.
10.
11. }
ASMATT (suki1207@uum.edu.my)
10
Exercise:
Basic Calculator
ASMATT (suki1207@uum.edu.my)
11
ASMATT (suki1207@uum.edu.my)
12
The
if is a Java
reserved word
if ( condition ) {
statement(s);
}
26
ASMATT (suki1207@uum.edu.my)
13
Relational Operators
equal to
not equal to
less than
greater than
less than or equal to
greater than or equal to
27
ASMATT (suki1207@uum.edu.my)
14
4.
5.
6.
7.
8.
9.
ASMATT (suki1207@uum.edu.my)
15
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<Button
android:textColor="#FF0000"
android:id="@+id/button1"
android:background="#FFCC00"
android:layout_width="wrap_content"
android:text="Enter your Name:" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
android:layout_height="wrap_content"
android:background="#FFCC00"
android:onClick="handleClick"
android:text="
Button
" />
Http://html-color-codes.info
VIDEO
ASMATT (suki1207@uum.edu.my)
16
Remote Video
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
<uses-permission android:name="android.permission.INTERNET"/>
ASMATT (suki1207@uum.edu.my)
17
Remote Video
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
<uses-permission android:name="android.permission.INTERNET"/>
Live TV
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
<uses-permission android:name="android.permission.INTERNET"/>
ASMATT (suki1207@uum.edu.my)
18
Local Video
1. protected void onCreate(Bundle savedInstanceState) {
2.
super.onCreate(savedInstanceState);
3.
setContentView(R.layout.activity_main);
4.
5.
6.
7.
8.
9.
10. }
PLAY AN AUDIO
1. public class MainActivity extends Activity {
2.
private MediaPlayer mp;
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
}
Media Player source.
public void playSound(View v){
mp = MediaPlayer.create(MainActivity.this,
R.raw.lagu);
mp.start();
}
ASMATT (suki1207@uum.edu.my)
19
Android is Interesting!
TALKING ANDROID
ASMATT (suki1207@uum.edu.my)
20
TOUCH HANDLING
ASMATT (suki1207@uum.edu.my)
21
Three parameters:
The activity that is running this Toast alert
What the message should be
How long to show the Toast pop-up
import android.widget.Toast;
ASMATT (suki1207@uum.edu.my)
22
ASMATT (suki1207@uum.edu.my)
23
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gesture);
}
case MotionEvent.ACTION_UP:
x2 = event.getX();
y2 = event.getY();
ASMATT (suki1207@uum.edu.my)
24
35.
36.
37.
ASMATT (suki1207@uum.edu.my)
25
Exercise
When a user performs this swipe , play a
song.
When a user performs this swipe , stop the
song.
ASMATT (suki1207@uum.edu.my)
26
ASMATT (suki1207@uum.edu.my)
27
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
7.
public void Open_Layout2(View v) {
8.
setContentView(R.layout.second_layout);
9.
}
10.}
ASMATT (suki1207@uum.edu.my)
28
ASMATT (suki1207@uum.edu.my)
29
ASMATT (suki1207@uum.edu.my)
30
ASMATT (suki1207@uum.edu.my)
31
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.suki.mytaskbar.MainActivity" >
<item
android:id="@+id/main_acreen"
android:orderInCategory="100"
android:title="Paparan Utama"
app:showAsAction="never"/>
<item
android:id="@+id/layout2"
android:orderInCategory="100"
android:title="Buka Layout 2"
app:showAsAction="never"/>
ASMATT (suki1207@uum.edu.my)
32
<item
33.
</menu>
android:id="@+id/play_music"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
android:title="Play Music"
app:showAsAction="never"/>
<item
android:id="@+id/stop_music"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
android:title="Stop Music"
app:showAsAction="never"/>
<item
android:id="@+id/bantuan"
android:icon="@drawable/ic_launcher"
android:orderInCategory="100"
android:title="Bantuan"
app:showAsAction="never"/>
ASMATT (suki1207@uum.edu.my)
33
if (id == R.id.play_music) {
mp = MediaPlayer.create(getApplicationContext(),
R.raw.uum_song);
mp.start();
}
if (id == R.id.stop_music) {
mp.stop();
}
if (id == R.id.bantuan) {
setContentView(R.layout.screen_bantuan);
}
return super.onOptionsItemSelected(item);
ASMATT (suki1207@uum.edu.my)
34
ASMATT (suki1207@uum.edu.my)
35
Try This:
Download am Image
ASMATT (suki1207@uum.edu.my)
36
The layout
ASMATT (suki1207@uum.edu.my)
37
The coding
1.
2.
3.
4.
5.
The Result
ASMATT (suki1207@uum.edu.my)
38
Now run it on
Emulator API19
ASMATT (suki1207@uum.edu.my)
39
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
8.
9.
new myDownloadThread().execute();
10.
11.
@Override
protected Bitmap doInBackground(Void... arg0) {
Bitmap imgResult = null;
try {
imgResult =
BitmapFactory.decodeStream((InputStream) new
URL(url).getContent());
} catch (Exception e) {}
return imgResult;
}
ASMATT (suki1207@uum.edu.my)
40
23.
24.
Toast.makeText(getApplicationContext(),
"is displaying...",
Toast.LENGTH_SHORT).show();
ImageView imgView = (ImageView)
findViewById(R.id.imageView1);
imgView.setImageBitmap(result);
25. }
26. }
27.}
Thread/AsynTask
(2014)
ASMATT (suki1207@uum.edu.my)
41
ASMATT (suki1207@uum.edu.my)
42
LOGO
Android AsynTask
Enables proper and easy use of the UI thread. This
class allows to perform background operations and
publish results on the UI thread without having to
manipulate threads and/or handlers.
Introduction
AsyncTask is a generic class, it uses 3 types:
AsyncTask<Params, Progress, Result>.
Params the input. What you pass to the
AsyncTask
Progress if you have any updates, passed to
onProgressUpdate()
Result the output. What returns doInBackground()
Example:
private class MyTask extends AsyncTask<String, Integer, String> { }
OR
private class MyTask2 extends AsyncTask<Void, Integer, Void> { }
ASMATT (suki1207@uum.edu.my)
43
Introduction
The most common methods you will need to
implement (overrides) are these:
1. onPreExecute() called on the UI thread
before the thread starts running.
2. doInBackground(Params3) put all the code
you want the application to perform in
background.
3. onProgressUpdate() - called when you invoke
publishProgress() in the doInBackground().
4. onPostExecute(Result) called after the
background thread finishes.
Example
ASMATT (suki1207@uum.edu.my)
44
Example
1.
2.
3.
4.
5.
6.
7.
8.
@Override
public void onCreate(Bundle savedInstanceState) {
Super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
}
Example
13.
14.
@Override
15.
16.
17.
18.
19.
@Override
20.
21.
super.onPreExecute();
tv.setText("Downloading...");
}
22.
23.
24.
25.
26.
27.
28.
// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
Return
publishProgress(i);
29.
30.
31.
32.
Array
type
to 2nd param of
the AsynTask class
ASMATT (suki1207@uum.edu.my)
45
Example
33.
34.
35.
36.
37.
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
tv.setText("Progress Value: " + values[0]);
}
38.
39.
40.
41.
42.
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tv.setText(result);
Input from 3rd param
}
of the AsynTask cls
43.
44.}
Summary
1. public void handleAsynTask(View v) {
2.
new MyTask().execute("http://ahmadsuki.blogspot.com");
3. }
4. private class MyTask extends AsyncTask<String, Integer, String> {
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
ASMATT (suki1207@uum.edu.my)
46
Summary
1. public void handleAsynTask(View v) {
2.
new MyTask().execute();
3. }
4. private class MyTask extends AsyncTask<Void, Integer, Void> {
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
7.
8.
9.
10.
2
11.
12.
13.
14.
@Override
protected Bitmap doInBackground(Void... arg0) {
return imgResult;
}
15.
16.
17. }
ASMATT (suki1207@uum.edu.my)
47
Analysis Issues
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
@Override
Toast.makeText(getApplicationContext(), "is
protected Bitmap doInBackground(Void... arg0) {
Toast.LENGTH_SHORT).show();
return imgResult;
ImageView imgView = (ImageView)
}
findViewById(R.id.imageView1);
imgView.setImageBitmap(result);
protected void onPostExecute(Bitmap
result) {
}
15.
16.
17. }
Analysis Issues
1.
2.
3.
4.
5.
6.
downloading...",
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
@Override
protected Bitmap doInBackground(Void... arg0) {
return imgResult;
}
}
ASMATT (suki1207@uum.edu.my)
48
3.
new myDownloadThread().execute(url);
4. }
5. private class myDownloadThread extends AsyncTask<String, Void,
Bitmap> {
6.
@Override
7.
8.
9.
10.
arg0)
ASMATT (suki1207@uum.edu.my)
49
2.
3.
4.
5.
6.
7.
Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... arg0) {
try {
int sizeFile= new URL(arg0[0]).openConnection().getContentLength();
publishProgress(sizeFile);
8.
9.
@Override
super.onProgressUpdate(values);
Toast.makeText(getApplicationContext(), "The file size is =
"+values[0], Toast.LENGTH_LONG).show();
}
ASMATT (suki1207@uum.edu.my)
50
<uses-permission android:name=android.permission.INTERNET/>
Background Thread
Starting
perform
network operations on your main UI thread
This will cause a NetworkOnMainThreadException
In order to solve this, you need to use background
thread:
Handler
or
AsyncTask
ASMATT (suki1207@uum.edu.my)
51
ASMATT (suki1207@uum.edu.my)
52
ASMATT (suki1207@uum.edu.my)
*ImageDownloader
is the name of
our AsyncTask
53
Override all the four methods in your AsyncTask , starting with the
onPreExecute() method.
- This is for initialising purpose
onPreExecute() method:
@Override
protected void onPreExecute() {
progress = 0; //declare this int variable as global in your AsyncTask
pb.setVisibility(View.VISIBLE);
Toast.makeText(LoadImageAsyncTaskActivity.this,
"starting download", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
ASMATT (suki1207@uum.edu.my)
54
doInBackground() method:
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap bmp = loadImageFromNetwork(urls[0]); //do the loading task
while (progress < 100) {
progress += 1;
publishProgress(progress); //update progress to UI thread
SystemClock.sleep(100); //to slowdown the system
}
return bmp;
}
onProgressUpdate() method:
@Override
protected void onProgressUpdate(Integer... values) {
pb.setProgress(values[0]);
percent.setText(values[0] + "%");
}
ASMATT (suki1207@uum.edu.my)
55
onPostExecute() method:
@Override
protected void onPostExecute(Bitmap result) {
img.setImageBitmap(result);
Toast.makeText(LoadImageAsyncTaskActivity.this,
"download complete", Toast.LENGTH_SHORT).show();
}
loadImageFromNetwork() method:
private Bitmap loadImageFromNetwork(String url) {
try {
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(url).getContent());
// URL urlObj = new URL(url);
// InputStream in = (InputStream) urlObj.getContent();
//Bitmap bitmap = BitmapFactory.decodeStream(in);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
Log.d("getBmpFromUrl error: ", e.getMessage().toString());
return null;
}
}
ASMATT (suki1207@uum.edu.my)
56
AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nasran.loadimageasynctask"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
:
:
:
ASMATT (suki1207@uum.edu.my)
57
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
58
(2014)
ASMATT (suki1207@uum.edu.my)
59
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
60
(2014)
ASMATT (suki1207@uum.edu.my)
61
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="21dp"
android:visibility="invisible"
android:ems="10" >
(2014)
6.
et.setVisibility(et.VISIBLE);
7.
et.setText(result);
8. }
(2014)
ASMATT (suki1207@uum.edu.my)
62
Try This:
(2014)
Try This:
4.
new MyDownTF().execute();
5.
6.
7.
@Override
8.
9.
10.
11.
12.
(2014)
ASMATT (suki1207@uum.edu.my)
63
Try This:
@Override
protected void onPostExecute(String strResult) {
// TODO Auto-generated method stub
super.onPostExecute(strResult);
EditText et = (EditText) findViewById(R.id.editText1);
et.setVisibility(et.VISIBLE);
et.setText(strResult);
}
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
64
String,
String>{
(2014)
@Override
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
publishProgress(line);
18.
19.
inputStream.close();
20.
21.
22.
23.
24.
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return theString;
}
(2014)
ASMATT (suki1207@uum.edu.my)
65
(2014)
Try This:
Download a WebPage File
(2014)
ASMATT (suki1207@uum.edu.my)
66
Try This:
Download a WebPage File
Start by changing the
previous layout screen by
embedding a WebView
object (remove the
EditText).
(2014)
Try This:
Download a WebPage File
1. @Override
2. protected void onPostExecute(String
strResult) {
3. // TODO Auto-generated method stub
4.
super.onPostExecute(strResult);
5.
WebView wv = (WebView)
findViewById(R.id.webView1);
6.
wv.loadData(strResult, "text/html", null);
7. }
(2014)
ASMATT (suki1207@uum.edu.my)
67
(2014)
ASMATT (suki1207@uum.edu.my)
68
@Override
13.
14.
try {
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
theString += line;
//publishProgress(line);
}
inputStream.close();
25.
26.
27.
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
28.
29.
return
theString;
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
69
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
70
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
71
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
72
(2014)
ASMATT (suki1207@uum.edu.my)
73
(2014)
ASMATT (suki1207@uum.edu.my)
74
(2014)
ASMATT (suki1207@uum.edu.my)
75
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
76
JSONObject jsonObj;
String strDate="", strTime="";
try {
jsonObj = new JSONObject(strJSON);
strDate = jsonObj.getString("date");
strTime = jsonObj.getString("time");
} catch (JSONException e) {}
TextView tvDate = (TextView)
findViewById(R.id.textView3);
9. TextView tvTime =
(TextView)findViewById(R.id.textView4);
10. tvDate.setText("Today Date: "+strDate);
11. tvTime.setText("US Time now: "+strTime);
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
77
(2014)
(2014)
ASMATT (suki1207@uum.edu.my)
78
(2014)
Exercise
(2014)
ASMATT (suki1207@uum.edu.my)
79
(2014)
ASMATT (suki1207@uum.edu.my)
80
ASMATT (suki1207@uum.edu.my)
81
ASMATT (suki1207@uum.edu.my)
82
List (GET)
Search (GET)
Create (POST)
ASMATT (suki1207@uum.edu.my)
83
1. Create the main layout (xml) for your Activity. It should have:
A TextView for the title
A Button to List All Contacts
A TextView to display Enter Name
An EditText to enter person name
A TextView to display Enter Name
An EditText to enter person phone number
A Button to find/search a contact
A Button to add a new contact
An EditText to display operation result message
ASMATT (suki1207@uum.edu.my)
84
* LongRunningGetIO
is the name of
our AsyncTask
ASMATT (suki1207@uum.edu.my)
85
doInBackground() method:
@Override
* http://10.11.8.204:8080/
protected String doInBackground(Void... params) {
is the IP Address of the server
HttpClient httpClient = new DefaultHttpClient();
String addr = null;
if (operation == 1)
addr = "http:// 10.1.100.229:8080/GetSomeRest/webresources/service/";
if (operation == 2) {
EditText edt = (EditText) findViewById(R.id.editText1);
String name = edt.getText().toString();
addr = "http:// 10.1.100.229:8080/GetSomeRest/webresources/service/"
+ name;
}
if (operation == 3) {
addr = "http:// 10.1.100.229:8080/GetSomeRest/webresources/service/add";
}
ASMATT (suki1207@uum.edu.my)
86
onPostExecute() method:
@Override
protected void onPostExecute(String results) {
if (results != null) {
EditText et = (EditText) findViewById(R.id.editText3);
et.setText(results);
}
}
ASMATT (suki1207@uum.edu.my)
87
getResultFromEntity() method:
protected String getResultFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package= "com.example.testrestclientasynctask"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
:
:
:
ASMATT (suki1207@uum.edu.my)
88
Introduction
Web services provide a standard means of
interoperating between different software
applications, running on a variety of platforms and/or
frameworks.
Intro - II
One of the most common functionalities required
in mobile applications is to call a web service to
retrieve data.
This process involves requesting the web service
with parameters, receiving the response and
parsing it to obtain data.
Today the most common web services types are
SOAP and REST.
Android does not provide a built in SOAP client,
there are many third party libraries that can be
used
ASMATT (suki1207@uum.edu.my)
89
Intro (REST)
REST (or RESTful) Services are an increasingly
common paradigm for creating web services
because of their simplicity and inherent platform
agnostic approach.
Many of the major service providers use REST,
such as Twitter, Flickr, Facebook, etc.
REST allows for stateless, cacheable, and simple
to consume client-server architecture over HTTP.
Among the most popular formats are JSON
(JavaScript Object Notation) and XML.
ASMATT (suki1207@uum.edu.my)
90
String id;
String name;
String category;
String jsonString = "{\"data\" : {\"id\": "1234","category" :
Android","name" : Ahmad Suki"}}";
try{
JSONObject jsonObj= new JSONObject(jsonString);
JSONObject dataObj = jsonObj.getJSONObject("data");
id = dataObj.getString("id");
category = dataObj.getString("category");
name = dataObj.getString("name");
}
catch(JSONException e) {
}
We have to parse the JSON formatted massage to extract the data inside it
e.g. how to obtain only the names and phone numbers from the message
ASMATT (suki1207@uum.edu.my)
91
2. The JSON processing methods can throw exceptions, so add try and
catch blocks next:
try {
}
catch (Exception e) {
et.setText(Something went wrong!");
e.printStackTrace();
}
ASMATT (suki1207@uum.edu.my)
92
4. We need to retrieve this contact array, using its name: Contacts. Get
the Contacts array from the JSON Object:
ASMATT (suki1207@uum.edu.my)
93
8. Next, retrieve the phone number from the object, also appending it to
the String Builder and ended with a new line character:
contactResult.append(contactObject.getString("telNo")+ "\n");
if(contactResult.length()>0)
et.setText(contactResult.toString());
else
et.setText("Sorry - no results!");
ASMATT (suki1207@uum.edu.my)
94