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();
}
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.
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();
}