49
HELLO DIVING INTO DAY FIVE

Day 5

Embed Size (px)

DESCRIPTION

Revision of SQlite Asynctask Httpconnection API Sharedpreferences

Citation preview

Page 1: Day 5

HELLODIVING INTO DAY FIVE

Page 2: Day 5

AsyncTask

Page 3: Day 5

Simple AsyncTask Basic UI:

− TextView, EditText and Button

Goal: To display the input typed in by the user in the free space below.

Timer here will call a thread that delays the execution of the AsyncTask

Page 4: Day 5

Simple AsyncTask Call the AsyncTask on button click:

execute.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

// TODO Auto-generated method stub

new ViewFiller().execute(input.getText().toString(), timer.getText().toString());

}

});

Implementing an AsyncTask with parameters

execute here is the button shown in the earlier layout

Page 5: Day 5

AsyncTask Perform operations on a different thread. Used to prevent heavy processing from

freezing the UI and also do this

Page 6: Day 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

Page 7: Day 5

ViewFiller extends AsyncTaskpublic class ViewFiller extends AsyncTask<String, Integer, String> {

//code here

}What are the parameters

being defined here ?

Page 8: Day 5

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()

Page 9: Day 5

onPreExecute@Override

protected void onPreExecute() {

// TODO Auto-generated method stub

super.onPreExecute();

execute.setText("Running...");

displayProgress("Updating field ... ");

// Start the progress dialog

progress.show();

}

Page 10: Day 5

doInBackgroundprotected String doInBackground(String... input) {

try {

int time;

if (input[1].equalsIgnoreCase("")) {

time = 0;} else {time = Integer.parseInt(input[1]) * 1000;for (int i = 1; i <= time / 1000; i++) {publishProgress(i, time);Thread.sleep(1000);

}

}

} catch (InterruptedException e) {

e.printStackTrace();

}

return input[0];

}

Call to onProgressUpdate

Passing parameter to onPostExecute

Page 11: Day 5

onProgressUpdate@Override

protected void onProgressUpdate(Integer... values) {

// TODO Auto-generated method stub

super.onProgressUpdate(values);

displayProgress("Updating field ... " + values[0] + " of "+ values[1] / 1000);

}Interaction with the UI

Page 12: Day 5

onPostExecute@Override

protected void onPostExecute(String result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

execute.setText("Execute");

progress.dismiss();

tvInput.setText(result);

}

Full code: http://bit.ly/1eG57hY

Page 13: Day 5

Deeper with AsyncTask The first think you should understand:

− They rely on Java concepts of GENERICS and VARARGSGENERICS: Can declare of any typeVARARGS: Arrays… you can pass in number of values

Page 14: Day 5

Adding AsyncTask to our app

Page 15: Day 5

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.smsList);

progress = (ProgressBar) findViewById(R.id.progress);

cursor = dbAdapter.getAllRows();

new DBAsync().execute(cursor);

}

Page 16: Day 5

Class that extends the AsyncTaskpublic class DBAsync extends AsyncTask <Cursor, String,

Cursor>{

// code here

}

Page 17: Day 5

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("Loading from Database ...");

progress.show();

}

Page 18: Day 5

doInBackground@Override

protected Cursor doInBackground(Cursor... cursor) {

// TODO Auto-generated method stub

return cursor[0];

}

Page 19: Day 5

onPostExecute

@Override

protected void onPostExecute(String result) {

// TODO Auto-generated method stub

super.onPostExecute(result);

progress.dismiss();

String[] from = new String[] { dbAdapter.KEY_ROWID, dbAdapter.KEY_NAME, dbAdapter.KEY_ADD };

int[] to = new int[] { R.id.list_id, R.id.list_name, R.id.list_address };

SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.result_layout, result, from, to, 1);

listView.setAdapter(adapter);

}

Page 20: Day 5

On click event on ListView

listView.setOnItemClickListener(new OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position,

long id) {

// TODO Auto-generated method stub

TextView refId = (TextView)view.findViewById(R.id.list_id);

TextView refName = (TextView)view.findViewById(R.id.list_name);

TextView refAdd = (TextView)view.findViewById(R.id.list_address);

String sd_id = refId.getText().toString();

String sd_name = refName.getText().toString();

String sd_add = refAdd.getText().toString();

buildAlert(sd_id, sd_name, sd_add);

}

});

This view is the parameter defined in the onItemClick method

Method to create an AlertDialog

Page 21: Day 5

BuildAlert Method

public void buildAlert(String id, String name, String add){

AlertDialog dialog = new AlertDialog.Builder(ClassName.this).create();

dialog.setTitle("View on Alert Dialog");

dialog.setIcon(android.R.drawable.ic_dialog_info);

dialog.setMessage("id = "+id+"; name = "+name+"; address = "+add);

dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,

int which) {

dialog.dismiss();

return;

}

});

dialog.show();

}

We also have to create the object prior to declaring it

refers to default android resources

POSITIVE, NEGATIVE and NEUTRAL allcontribute to the positioning of the buttons.

Till Honeycomb, the button order (left to right) is POSITIVE - NEUTRAL - NEGATIVE.

On newer devices, the button order (left to right) is now NEGATIVE - NEUTRAL - POSITIVE.

Always remember to show me :)

Page 22: Day 5

Another example using the AsyncTask and SimpleCursorAdapter:

http://bit.ly/17ipnE4

Page 23: Day 5

TYPESOF MOBILE APPS

Page 24: Day 5

Mobile Apps Two categories of mobile apps:

− View-heavy (data-driven) Social, news.

− Graphics-heavy (drawing-based) Games, photo editing.

Focus on data-driven− Heart of mobile development− Graphics-heavy are more specialized and more

advanced.

Page 25: Day 5

Data driven apps

Instagram Tumblr Facebook

Page 26: Day 5

Developing View-Heavy apps Making view-heavy apps rest on a few core

concept − Common controls and View Layout

Android's view system. − Interaction and event handling

All the touch interactions made by users.− Screen flows and Navigation

Application's overall structure.− Data modeling, Networking and Persistence

Network requests (API interaction), data storage.− Accessing the mobile features

Page 27: Day 5

API interaction Interaction through

− XML Java parser: SAX and the DOM XML parsers Android provides XmlPullParser which is less

complicated.− JSON

JSONObject and JSONArray are used.

Page 28: Day 5

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.

Page 29: Day 5

DistanceMatrix API URL –

http://maps.googleapis.com/maps/api/distancematrix/json?params

Parameters:

− origins origins=Jamal,Kathmandu

− destinations destinations=Kalanki,Kathmandu

− sensor sensor=false

Page 30: Day 5

API Response

Page 31: Day 5

Application UI

Call on the AsyncTask

on click

Do NOT FORGET to use the INTERNET permission

Page 32: Day 5

How do we implement this ?−Get the JSONObject−Extract Results from the API's response−Putting it all together

Page 33: Day 5

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

Page 34: Day 5

Extracting results from the API's response To get the JSON output we use:

− JSONObject '{' represents the JSONObject

− JSONArray '[' represents the JSONArray

Page 35: Day 5

JSONObject

JSONArray

Page 36: Day 5

Accessing JSONJSONObject 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();

}

Full code: http://bit.ly/HTGTm1

Page 37: Day 5

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

Page 38: Day 5

SharedPreferences

Page 39: Day 5

Android Storage How do you save your application data ?

− SharedPreferences* Storage in key-value pairs.

− Internal Storage Storage on device memory

− External Storage Storage on shared external storage

− SQLite Databases* Store structured data in a private database

− Network Connections Store data on web

Page 40: Day 5

SharedPreferences The way android stores users preferences But why SharedPreferences ?

− Ease of implementation− Faster in terms of coding− Accessibility of key values− Suitable for the small things

e.g. Game difficulty level, user name, user accounts, etc.

Page 41: Day 5

SharedPreferences Every thing is saved in terms of key-value

− e.g. “NAME”, “Android”“PhoneNumber”, “1234”

For the implementation we will be using the:− SharedPreferences

General framework to save and retrieve persistent key-value pairs

− Editor Interface used for modifying values in a SharedPreferences object

Use of commit() or apply() to make changes persist

Page 42: Day 5

Implementationpublic class ProjectPreference{

SharedPreferences pref;

Editor editor;

Context _context;

int PRIVATE_MODE = 0;

private static final String PREF_NAME = “prefmyapp”;

... (A)

public ProjectPreference(Context context){

this._context = context;

pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

editor = pref.edit();

} ... (B)

We are creating a separate class

here

Page 43: Day 5

A: Define Variables Suppose we have a contact to save:

− Name− Address− Number

Declare them:public static final String KEY_NAME = “name”;

public static final String KEY_ADD = “address”;

public static final String KEY_NUM = “number”;

Page 44: Day 5

B: Define Getters and Setters Defining setters and getters

− void for setterspublic void setName(String key, String value){

editor.putString(key, value);editor.commit();

}

− <types> for getters public String getName(String key){

return pref.getString(key, “”);}

You candefine your default

values here

Page 45: Day 5

Accessing SharedPreferences Create an object

ProjectPreference SM;

InitializeSM = new ProjectPreference(Class.this);

Access variables and methodsSM.getName(SM.KEY_NAME);

Set valuesSM.setName(SM.KEY_NAME, “Android”);

Page 46: Day 5

Building an application

Spinner

Make a simple application that displays what the

user sets in the preferences page onto the application's launcher activity

Page 47: Day 5

Spinner

<Spinner

...

android:entries="@array/colors" />

Defines the entries inside Spinner

Declared in strings under values

Page 48: Day 5

Spinner<string-array name="colors">

<item>Blue</item>

<item>Purple</item>

<item>Red</item>

<item>Orange</item>

<item>Green</item>

<item>Yellow</item>

<item>Black</item>

<item>White</item>

</string-array>

Page 49: Day 5

Building our application In our MainActivity :

− Call for the SharedPreferences.

− Check if there is any value stored.

If yes:Display the stored

value.

If no:Call on another class

that allows users to store value.

Full code: http://bit.ly/HKrhBm