Your SlideShare is downloading. ×
0
Android Apps Development – Training
Day 5
Previously
public void onClick(View arg0) {
String name = ETname.getText().toString();
String email = ETemail.getText().to...
AsyncTask
● Perform operations on a different thread
and also do this
Adding to that
public void onClick(View arg0) {
String name = ETname.getText().toString();
String email = ETemail.getText(...
How do we do this ?
● We create a class inside our Activity that
extends the AsyncTask
● We use different methods it offer...
Class that extends the AsyncTask
public class DBAsync extends AsyncTask <String, String,
String>{
// code here
}
What are ...
● AsyncTask<Params, Progress, Result>
– Params: the input, what you pass into the
AsyncTask
– Progress: on updates, passed...
onPreExecute
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Declare ...
doInBackground
@Override
protected String doInBackground(String... string) {
// TODO Auto-generated method stub
dbhelper d...
onPostExecute
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecu...
Deeper with AsyncTask
● The first think you should understand:
– They rely on Java concepts of GENERICS and
VARARGS
GENERI...
Accessing HTTP
● There are two ways of accessing HTTP in
android:
– Using the HttpURLConnection
● Using the HttpURLConnect...
DistanceMatrix API
● URL –
http://maps.googleapis.com/maps/api/distancematrix/json?
params
● Parameters:
– origins
● origi...
API Response
Application UI
Call on the
AsyncTask
on click
Do NOT FORGET to use
the INTERNET permission
● How do we implement this ?
– Get the JSONObject
– Extract Results from the API's response
– Putting it all together
Get the JSONObject
● Create a HTTPClient
– DefaultHttpClient httpClient = new DefaultHttpClient();
● Use the HTTPGet
– Htt...
Extracting results from the API's
response
● To get the JSON output we use:
– JSONObject
● '{' represents the JSONObject
–...
JSONObject
JSONArray
Accessing JSON
JSONObject googleObject1, googleObject2, googleObject3, googleObject4;
JSONArray googleArray1, googleArray2...
Putting it all together
● A separate class is created to convert the URL
response to a JSONObject
● Button click triggers ...
ListViews
● Displays a group of scrollable items
● The items are automatically inserted to list
using an Adapter that pull...
Implementation
● Create a layout with listview
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
an...
In MainActivity
● Define the listview
listView = (ListView) findViewById(R.id.list);
● Define arrays to show in the ListVi...
Using Adapter
● What are the parameters to be passed in this
adapter ?
– First parameter - Context
– Second parameter - La...
● Define a new Adapter
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,android.R.layout.simple_list_
item_1, ...
● Set onItemClickListener
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<...
ListView Usage
Upcoming SlideShare
Loading in...5
×

Android training day 5

768

Published on

Android Training Day 5 slide organized in Mobile Nepal from 22nd sept, 2013 to 28th sept, 2013 for beginner level

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
768
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
29
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Android training day 5"

  1. 1. Android Apps Development – Training Day 5
  2. 2. Previously public void onClick(View arg0) { String name = ETname.getText().toString(); String email = ETemail.getText().toString(); String phoneno = ETphoneno.getText().toString(); if(name.length()<1 || email.length()<1 || phoneno.length()<1){ //do something }else{ dbhelper db= new dbhelper(getApplicationContext()); db.open(); Long response = db.insertdata(name, email, phoneno); db.close(); } }
  3. 3. AsyncTask ● Perform operations on a different thread and also do this
  4. 4. Adding to that public void onClick(View arg0) { String name = ETname.getText().toString(); String email = ETemail.getText().toString(); String phoneno = ETphoneno.getText().toString(); if(name.length()<1 || email.length()<1 || phoneno.length()<1){ //do something }else{ new DBAsync().execute(name, email, phoneno); } } This is the AsyncTask
  5. 5. How do we do this ? ● We create a class inside our Activity that extends the AsyncTask ● We use different methods it offers do perform operations in the background: – OnPreExecute() ● Generally used to load the progress bar – doInBackground(Params... ) ● All the logic is dumped here – OnProgressUpdate() ● Called when publishProgress() is called in the doInBackground() – onPostExecute(Result) ● Gives out the desired results
  6. 6. Class that extends the AsyncTask public class DBAsync extends AsyncTask <String, String, String>{ // code here } What are these?
  7. 7. ● AsyncTask<Params, Progress, Result> – Params: the input, what you pass into the AsyncTask – Progress: on updates, passed to onProgressUpdate() – Result: the output from doInBackground() returned to the onPostExecute()
  8. 8. onPreExecute @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); //Declare progress as a global variable progress = new ProgressDialog(Registration.this); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER ); progress.setMessage("Filling up Database ..."); progress.show(); }
  9. 9. doInBackground @Override protected String doInBackground(String... string) { // TODO Auto-generated method stub dbhelper db = new dbhelper(getApplicationContext()); db.open(); Long insert = db.insertdata(string[0], string[1], string[2]); db.close(); return null; }
  10. 10. onPostExecute @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); progress.dismiss(); Intent i = new Intent(Registration.this, afterlogin.class); i.putExtra("register", true); startActivity(i); }
  11. 11. Deeper with AsyncTask ● The first think you should understand: – They rely on Java concepts of GENERICS and VARARGS GENERICS: ● Can declare of any type VARARGS: ● Arrays… you can pass in number of values
  12. 12. Accessing HTTP ● There are two ways of accessing HTTP in android: – Using the HttpURLConnection ● Using the HttpURLConnection object and its method – Using the HttpClient ● Use DefaultHttpClient, Http GET & POST, HttpResponse, HttpEntity ● Both of these follow similar steps: – Process the Http input – Use InputStream and BufferedReader to iterate through the http output.
  13. 13. DistanceMatrix API ● URL – http://maps.googleapis.com/maps/api/distancematrix/json? params ● Parameters: – origins ● origins=Jamal,Kathmandu – destinations ● destinations=Kalanki,Kathmandu – sensor ● sensor=false
  14. 14. API Response
  15. 15. Application UI Call on the AsyncTask on click Do NOT FORGET to use the INTERNET permission
  16. 16. ● How do we implement this ? – Get the JSONObject – Extract Results from the API's response – Putting it all together
  17. 17. Get the JSONObject ● Create a HTTPClient – DefaultHttpClient httpClient = new DefaultHttpClient(); ● Use the HTTPGet – HttpGet httpGet = new HttpGet(url); ● Get the HTTPResponse – HttpResponse httpResponse = httpClient.execute(httpGet); ● Get the HTTPEntity to an InputStream HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); // InputStream is ● Pass the InputStream to a BufferedReader ● Convert the output to a JSONObject
  18. 18. Extracting results from the API's response ● To get the JSON output we use: – JSONObject ● '{' represents the JSONObject – JSONArray ● '[' represents the JSONArray
  19. 19. JSONObject JSONArray
  20. 20. Accessing JSON JSONObject googleObject1, googleObject2, googleObject3, googleObject4; JSONArray googleArray1, googleArray2; ... String distanceBetween = ""; try{ //Getting array of the API UserFunctions users = new UserFunctions(); googleObject1 = users.distanceGET(places[0], places[1]); //places[0] and places[1] are values passed on button click googleArray1 = googleObject1.getJSONArray(TAG_ROW); googleObject2 = googleArray1.getJSONObject(0); googleArray2 = googleObject2.getJSONArray(TAG_ELEMENTS); googleObject3 = googleArray2.getJSONObject(0); googleObject4 = googleObject3.getJSONObject(TAG_DISTANCE); distanceBetween = googleObject4.getString(TAG_TEXT); }catch(JSONException e){ e.printStackTrace(); } ●
  21. 21. Putting it all together ● A separate class is created to convert the URL response to a JSONObject ● Button click triggers the AsyncTask where inputs for the doInBackground() are stated ● All the accessing/references to the API is done in the AsyncTask, where the main logic lies in the doInBackground() ● doInBackground() returns results to the onPostExecute() where it refreshes the UI thread
  22. 22. ListViews ● Displays a group of scrollable items ● The items are automatically inserted to list using an Adapter that pull content from a source
  23. 23. Implementation ● Create a layout with listview <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/list" android:layout_height="wrap_content" android:layout_width="match_parent"> </ListView> </LinearLayout>
  24. 24. In MainActivity ● Define the listview listView = (ListView) findViewById(R.id.list); ● Define arrays to show in the ListView String[] values = { “abc”, “def” , “ijk” , “xyz”}; ● Use Adapter – Helper to feed data into the list view
  25. 25. Using Adapter ● What are the parameters to be passed in this adapter ? – First parameter - Context – Second parameter - Layout for the row – Third parameter - ID of the TextView to which the data is written – Forth - the Array of data
  26. 26. ● Define a new Adapter ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_ item_1, android.R.id.text1, values); – These are all generic layouts defined by Android for us ● Set the adapter – listView.setAdapter(adapter); Notice android being referenced at first
  27. 27. ● Set onItemClickListener listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int itemPosition = position; String itemValue = (String) listView.getItemAtPosition(position); Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG).show(); }
  28. 28. ListView Usage
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×