SlideShare una empresa de Scribd logo
1 de 28
Android Apps Development – Training
Day 5
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();
}
}
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().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
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
Class that extends the AsyncTask
public class DBAsync extends AsyncTask <String, String,
String>{
// code here
}
What are these?
● 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()
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();
}
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;
}
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);
}
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
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.
DistanceMatrix API
● URL –
http://maps.googleapis.com/maps/api/distancematrix/json?
params
● Parameters:
– origins
● origins=Jamal,Kathmandu
– destinations
● destinations=Kalanki,Kathmandu
– sensor
● sensor=false
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
– 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
Extracting results from the API's
response
● To get the JSON output we use:
– JSONObject
● '{' represents the JSONObject
– JSONArray
● '[' represents the JSONArray
JSONObject
JSONArray
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();
}
●
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
ListViews
● Displays a group of scrollable items
● The items are automatically inserted to list
using an Adapter that pull content from a
source
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>
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
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
● 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
● 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();
}
ListView Usage

Más contenido relacionado

La actualidad más candente

Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxVisual Engineering
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsDiego Grancini
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React HooksFelix Kühl
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionVisual Engineering
 
jQuery Plugin
jQuery PluginjQuery Plugin
jQuery Pluginrbiggs
 
Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2 Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2 Ross Dederer
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0Jeado Ko
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016Mike Nakhimovich
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and reduxCuong Ho
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlOdoo
 

La actualidad más candente (20)

Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Android App Development - 04 Views and layouts
Android App Development - 04 Views and layoutsAndroid App Development - 04 Views and layouts
Android App Development - 04 Views and layouts
 
React hooks
React hooksReact hooks
React hooks
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React Hooks
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
jQuery Plugin
jQuery PluginjQuery Plugin
jQuery Plugin
 
Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2 Migrating an application from Angular 1 to Angular 2
Migrating an application from Angular 1 to Angular 2
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
준비하세요 Angular js 2.0
준비하세요 Angular js 2.0준비하세요 Angular js 2.0
준비하세요 Angular js 2.0
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
Introduction to react and redux
Introduction to react and reduxIntroduction to react and redux
Introduction to react and redux
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Extend sdk
Extend sdkExtend sdk
Extend sdk
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
 
Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
 

Similar a Android training day 5

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageabilityDaniel Fisher
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfEngmohammedAlzared
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!DataArt
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo Ali Parmaksiz
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application ArchitectureMark Trostler
 

Similar a Android training day 5 (20)

Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Android Pro Recipes
Android Pro RecipesAndroid Pro Recipes
Android Pro Recipes
 
Android 3
Android 3Android 3
Android 3
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 
GWT
GWTGWT
GWT
 

Más de Vivek Bhusal

Training Session 2 - Day 2
Training Session 2 - Day 2Training Session 2 - Day 2
Training Session 2 - Day 2Vivek Bhusal
 
Training Session 2
Training Session 2 Training Session 2
Training Session 2 Vivek Bhusal
 
Android training day 3
Android training day 3Android training day 3
Android training day 3Vivek Bhusal
 
Android training day 1
Android training day 1Android training day 1
Android training day 1Vivek Bhusal
 
Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Vivek Bhusal
 
Wisevote - opendataweek @
Wisevote - opendataweek @Wisevote - opendataweek @
Wisevote - opendataweek @Vivek Bhusal
 
Android training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampAndroid training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampVivek Bhusal
 

Más de Vivek Bhusal (9)

Training Session 2 - Day 2
Training Session 2 - Day 2Training Session 2 - Day 2
Training Session 2 - Day 2
 
Training Session 2
Training Session 2 Training Session 2
Training Session 2
 
Android training day 3
Android training day 3Android training day 3
Android training day 3
 
Android training day 1
Android training day 1Android training day 1
Android training day 1
 
Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)Stores munk presentation_aug10 (1)
Stores munk presentation_aug10 (1)
 
Mybudget
MybudgetMybudget
Mybudget
 
Wisevote - opendataweek @
Wisevote - opendataweek @Wisevote - opendataweek @
Wisevote - opendataweek @
 
Android training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcampAndroid training at GDG kathmandu Startup weekend bootcamp
Android training at GDG kathmandu Startup weekend bootcamp
 
My medical info
My medical infoMy medical info
My medical info
 

Último

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 

Último (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 

Android training day 5

  • 1. Android Apps Development – Training Day 5
  • 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. AsyncTask ● Perform operations on a different thread and also do this
  • 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. 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. Class that extends the AsyncTask public class DBAsync extends AsyncTask <String, String, String>{ // code here } What are these?
  • 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. 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. 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. 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. 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. 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. DistanceMatrix API ● URL – http://maps.googleapis.com/maps/api/distancematrix/json? params ● Parameters: – origins ● origins=Jamal,Kathmandu – destinations ● destinations=Kalanki,Kathmandu – sensor ● sensor=false
  • 15. Application UI Call on the AsyncTask on click Do NOT FORGET to use the INTERNET permission
  • 16. ● How do we implement this ? – Get the JSONObject – Extract Results from the API's response – Putting it all together
  • 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. Extracting results from the API's response ● To get the JSON output we use: – JSONObject ● '{' represents the JSONObject – JSONArray ● '[' represents the JSONArray
  • 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. 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. ListViews ● Displays a group of scrollable items ● The items are automatically inserted to list using an Adapter that pull content from a source
  • 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. 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. 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. ● 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. ● 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(); }