Android training day 5
Upcoming SlideShare
Loading in...5

Android training day 5



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

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



Total Views
Views on SlideShare
Embed Views



3 Embeds 281 229 41
http://localhost 11



Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Android training day 5 Android training day 5 Presentation Transcript

    • 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());; 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 ...");; }
    • doInBackground @Override protected String doInBackground(String... string) { // TODO Auto-generated method stub dbhelper db = new dbhelper(getApplicationContext());; 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 – 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="" 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(; ● 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,, 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