Lec. #9:Working with Web Services - Part 2
Mobile Applications Development 2
SECOND SEMESTER OF THE ACADEMIC YEAR 2020/2021
Handling API in Android
2
Ways to handle API in Android
1. AsynkTask (Deprecated)
2. Volley
3. Retrofit
 In this course, we will cover AsynkTask.
3
AsyncTask in Android
WORKING WITH API
AsyncTask in Andoid
AsyncTask (Asynchronous Task) is an abstract class provided by Android
which gives the liberty to perform heavy tasks in the background and keep
the UI thread light. Thus making the application more responsive.
 Android application runs on a single thread when launched.
 Due to this single thread model tasks that take longer time to fetch the
response can make the application non-responsive.
 To avoid this, AsyncTask is used to perform heavy tasks in background on
a dedicated thread and passing the results back to the UI thread.
Hence use of AsyncTask in android application, keeps the UI thread
responsive at all times.
NOTE: This class was deprecated in API level 30.
5
AsyncTask Generic Types
The three generic types used in an android AsyncTask class are:
AsyncTask <Params, Progress, Result>
Params: The type of the parameters sent to the task upon execution
Progress: The type of the progress units published during the background
computation
Result: The type of the result of the background computation
 All types are always used by an asynchronous task.
 To mark a type as unused, simply use the type Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
6
AsyncTask Methods
 doInBackground(): This method contains the code which needs to be executed in the
background.
 In this method we can send results multiple times to the UI thread by publishProgress()
method.
To notify that the background processing has been completed we just need to use the return
statements.
onPreExecute() : This method contains the code which is executed before the background
processing starts.
onPostExecute() : This method is called after doInBackground() method completes processing.
Result from doInBackground() is passed to this method.
onProgressUpdate() : This method receives progress updates from doInBackground() method,
which is published via publishProgress() method, and this method can use this progress update
to update the UI thread.
7
AsyncTask Methods
 doInBackground(): It contains the code which needs to be executed in the background.
 In this method we can send results multiple times to the UI thread by
publishProgress() method.
To notify that the background processing has been completed we just need to use
the return statements.
 onPreExecute(): This method contains the code which is executed before the
background processing starts.
 onPostExecute(): This method is called after doInBackground() method completes
processing. Result from doInBackground() is passed to this method.
 onProgressUpdate(): This method receives progress updates from doInBackground()
method, which is published via publishProgress() method, and this method can use this
progress update to update the UI thread.
8
AsyncTask Execution Steps
9
1
4
3
2
AsyncTask Execution Steps (Cont.)
 Step 1 - onPreExecute(): invoked on the UI thread before the task is executed.
This step is normally used to setup the task.
For instance by showing a progress bar/dialog (Loading image or text) in the user
interface.
 Step 2 - doInBackground(Params...): invoked on the background thread immediately
after onPreExecute() finishes executing.
This step is used to perform background computation that can take a long time.
The parameters of the asynchronous task are passed to this step.
The result of the computation must be returned by this step and will be passed
back to the last step (step 4).
This step can also use publishProgress(Progress...) to publish one or more units of
progress. These values are published on the UI thread, in the Step 3 -
onProgressUpdate(Progress...)
10
AsyncTask Execution Steps (Cont.)
 Step 3 - onProgressUpdate(Progress...): invoked on the UI thread after a call to
publishProgress(Progress...).
 The timing of the execution is undefined.
This method is used to display any form of progress in the user interface for good
user experience while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in a text field.
 Step 4 - onPostExecute(Result): invoked on the UI thread after the background
computation finishes. The result of the background computation is passed to this
step as a parameter and then we can easily update our UI to show the results.
11
AsyncExample
HANDLING API USING ASYNCTASK
12
AsyncExample: Steps
1. Testing the given API
2. Add Internet permission in AndroidManifest.xml file
3. Create java class “HttpHandler” to get the raw json from given url.
4. Create main xml layout and item layout
5. Create classes inside model package based on the received json – (json parser)
6. Create ContactAdapter for the RecyclerView inside adapter package
7. In MainActivity.java, Create inner java class GetContacts that extends AsyncTask and
override its methods
8. Create object of GetContacts then call execute()
13
AsyncExample: Step 1 - Testing API
https://api.androidhive.info/contacts/
 The API URL can be tested using postman or web
browser since the request method is GET.
 As shown in the Figure, it retrieves JSON object
called “contacts” and we handle it in java using
JSONObject.
 The contacts object contains JSON array that
contains many objects and we handle it in java
using JSONArray.
14
AsyncExample: Step 2 - Add Internet
Permission
 Since we are fetching the JSON by making HTTP calls, we need to
add INTERNET permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
15
AsyncExample: Step 3 - Create
HTTPHandler Class
 java.net libraries is imported
(which are natively supported
in android) to make the http
call and fetch the JSON from
URL.
 makeServiceCall() makes http
call to particular URL and
fetches the response.
16
public static String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
AsyncExample: Step 3 - Create
HTTPHandler Class (Cont.)
convertStreamToString():
converts the given stream of
the response into a string
using StringBuilder object.
17
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
AsyncExample: Step 4 -
Create Main Xml Layout
And Item Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvContacts"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Main Layout
18
Contact Item Layout
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
app:cardCornerRadius="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tvName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dp"
android:paddingBottom="2dp"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tvEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dp"
android:textColor="@color/colorAccent" />
<TextView
android:id="@+id/tvMobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
AsyncExample: Step 5 - Create Classes inside Model
Package based on the Received JSON – (JSON Parser)
 To install android studio plugin follow
these instructions:
1- from file, go to settings
2- go to plugins, and open marketplace tab
3- type the plugin name inside the search
field and press enter
4- from search results, press the install
button next to the plugin you want.
 Retrieved dated are model using one of the
following ways:
Classes are manually created based on
the received JSON from the API as noticed
from step 1.
 Using android studio plugins like
GsonFormat or RoboPOJOGenerator to
do this step for us
 Visit Plugins homepage
• https://plugins.jetbrains.com/plugin/7
654-gsonformat
• https://plugins.jetbrains.com/plugin/8
634-robopojogenerator
19
AsyncExample: Step 5 - Create Classes inside Model
Package based on the Received JSON – (JSON Parser)
Using RoboPOJOGenerator plugin
1. Create model package
2. Mouse right click on model, go to
New, then go to Generate POJO
from JSON.
20
AsyncExample: Step 5 - Create Classes inside Model
Package based on the Received JSON – (JSON Parser)
Using RoboPOJOGenerator plugin
3. From RoboPOJOGenerator window:
Set language to JAVA
Set framework to None
Copy JSON response from browser and paste inside the black
region.
Check create setters and create getters
Rename the root object name to Contacts
Finally, press Generate
 Three classes were generated inside the model package:
 Contacts: the root object from json response contain array of
ContactsItem objects
 ContactsItem: item object
 Phone: phone object for each ContactsItem
21
AsyncExample:
Step 6 - Create
ContactAdapter for
the RecyclerView
inside the adapter
package
22
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private ArrayList<ContactsItem> data;
private Activity activity;
public ContactAdapter(ArrayList<ContactsItem> data, Activity activity) {
this.data = data;
this.activity = activity;
}
public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View root = LayoutInflater.from(activity).inflate(R.layout.contact_item_layout, null, false);
return new ContactViewHolder(root);
}
public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
ContactsItem contact = data.get(position);
holder.tvName.setText(String.valueOf(contact.getName()));
holder.tvEmail.setText(contact.getEmail());
holder.tvMobile.setText(contact.getPhone().getMobile());
}
public int getItemCount() {
return data.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
TextView tvName, tvEmail,tvMobile;
public ContactViewHolder(@NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvName);
tvEmail = itemView.findViewById(R.id.tvEmail);
tvMobile = itemView.findViewById(R.id.tvMobile);
}
}
}
23
class GetContacts extends AsyncTask<Void,Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pb.setVisibility(ProgressBar.VISIBLE);
}
@Override
protected Void doInBackground(Void... voids) {
String response = HttpHandler.makeServiceCall(BaseURi);
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray contactsArray = jsonObject.getJSONArray("contacts");
for(int i=0; i< contactsArray.length(); i++){
JSONObject c = contactsArray.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
AsyncExample: Step 7 -
In MainActivity.java,
Create inner java
class GetContacts
that extends
AsyncTask and
override its methods
AsyncExample: Step 7 -
In MainActivity.java,
Create inner java
class GetContacts
that extends
AsyncTask and
override its methods
24
ContactsItem contact = new ContactsItem();
Phone phoneObj = new Phone();
phoneObj.setMobile(mobile);
phoneObj.setHome(home);
phoneObj.setOffice(office);
contact.setName(name);
contact.setEmail(email);
contact.setPhone(phoneObj);
contact.setId(id);
contact.setAddress(address);
contact.setGender(gender);
data.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void voids) {
super.onPostExecute(voids);
pb.setVisibility(ProgressBar.GONE);
ContactAdapter pa = new ContactAdapter(data, MainActivity.this);
RecyclerView.LayoutManager manager=new LinearLayoutManager(MainActivity.this);
rvContacts.setAdapter(pa);
rvContacts.setLayoutManager(manager);
}
}
AsyncExample: Step 8 - Create object of
GetContacts and call execute() method
 In MainActivity.java, inside onCreate()
 After binding the views (recyclerView and progressBar), we create
an object of GetContacts and call the execute()
// new GetContacts().execute();
GetContacts getContacts = new GetContacts();
getContacts.execute();
25
Lets Pratice
Develop an android application that handle the following fake api
that retrieve products details where request method is GET using
AsyncTask.
26
https://5ef6eaac2c0f2c0016949dae.mockapi.io/products

Session 9 Android Web Services - Part 2.pdf

  • 1.
    Lec. #9:Working withWeb Services - Part 2 Mobile Applications Development 2 SECOND SEMESTER OF THE ACADEMIC YEAR 2020/2021
  • 2.
    Handling API inAndroid 2
  • 3.
    Ways to handleAPI in Android 1. AsynkTask (Deprecated) 2. Volley 3. Retrofit  In this course, we will cover AsynkTask. 3
  • 4.
  • 5.
    AsyncTask in Andoid AsyncTask(Asynchronous Task) is an abstract class provided by Android which gives the liberty to perform heavy tasks in the background and keep the UI thread light. Thus making the application more responsive.  Android application runs on a single thread when launched.  Due to this single thread model tasks that take longer time to fetch the response can make the application non-responsive.  To avoid this, AsyncTask is used to perform heavy tasks in background on a dedicated thread and passing the results back to the UI thread. Hence use of AsyncTask in android application, keeps the UI thread responsive at all times. NOTE: This class was deprecated in API level 30. 5
  • 6.
    AsyncTask Generic Types Thethree generic types used in an android AsyncTask class are: AsyncTask <Params, Progress, Result> Params: The type of the parameters sent to the task upon execution Progress: The type of the progress units published during the background computation Result: The type of the result of the background computation  All types are always used by an asynchronous task.  To mark a type as unused, simply use the type Void: private class MyTask extends AsyncTask<Void, Void, Void> { ... } 6
  • 7.
    AsyncTask Methods  doInBackground():This method contains the code which needs to be executed in the background.  In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements. onPreExecute() : This method contains the code which is executed before the background processing starts. onPostExecute() : This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method. onProgressUpdate() : This method receives progress updates from doInBackground() method, which is published via publishProgress() method, and this method can use this progress update to update the UI thread. 7
  • 8.
    AsyncTask Methods  doInBackground():It contains the code which needs to be executed in the background.  In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements.  onPreExecute(): This method contains the code which is executed before the background processing starts.  onPostExecute(): This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method.  onProgressUpdate(): This method receives progress updates from doInBackground() method, which is published via publishProgress() method, and this method can use this progress update to update the UI thread. 8
  • 9.
  • 10.
    AsyncTask Execution Steps(Cont.)  Step 1 - onPreExecute(): invoked on the UI thread before the task is executed. This step is normally used to setup the task. For instance by showing a progress bar/dialog (Loading image or text) in the user interface.  Step 2 - doInBackground(Params...): invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step (step 4). This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the Step 3 - onProgressUpdate(Progress...) 10
  • 11.
    AsyncTask Execution Steps(Cont.)  Step 3 - onProgressUpdate(Progress...): invoked on the UI thread after a call to publishProgress(Progress...).  The timing of the execution is undefined. This method is used to display any form of progress in the user interface for good user experience while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.  Step 4 - onPostExecute(Result): invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter and then we can easily update our UI to show the results. 11
  • 12.
  • 13.
    AsyncExample: Steps 1. Testingthe given API 2. Add Internet permission in AndroidManifest.xml file 3. Create java class “HttpHandler” to get the raw json from given url. 4. Create main xml layout and item layout 5. Create classes inside model package based on the received json – (json parser) 6. Create ContactAdapter for the RecyclerView inside adapter package 7. In MainActivity.java, Create inner java class GetContacts that extends AsyncTask and override its methods 8. Create object of GetContacts then call execute() 13
  • 14.
    AsyncExample: Step 1- Testing API https://api.androidhive.info/contacts/  The API URL can be tested using postman or web browser since the request method is GET.  As shown in the Figure, it retrieves JSON object called “contacts” and we handle it in java using JSONObject.  The contacts object contains JSON array that contains many objects and we handle it in java using JSONArray. 14
  • 15.
    AsyncExample: Step 2- Add Internet Permission  Since we are fetching the JSON by making HTTP calls, we need to add INTERNET permission in AndroidManifest.xml file. <uses-permission android:name="android.permission.INTERNET" /> 15
  • 16.
    AsyncExample: Step 3- Create HTTPHandler Class  java.net libraries is imported (which are natively supported in android) to make the http call and fetch the JSON from URL.  makeServiceCall() makes http call to particular URL and fetches the response. 16 public static String makeServiceCall(String reqUrl) { String response = null; try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } return response; }
  • 17.
    AsyncExample: Step 3- Create HTTPHandler Class (Cont.) convertStreamToString(): converts the given stream of the response into a string using StringBuilder object. 17 private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append('n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
  • 18.
    AsyncExample: Step 4- Create Main Xml Layout And Item Layout <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"/> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rvContacts" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Main Layout 18 Contact Item Layout <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" app:cardCornerRadius="20dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tvName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="6dp" android:paddingBottom="2dp" android:textColor="@color/colorPrimaryDark" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/tvEmail" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dp" android:textColor="@color/colorAccent" /> <TextView android:id="@+id/tvMobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#5d5d5d" android:textStyle="bold" /> </LinearLayout> </androidx.cardview.widget.CardView>
  • 19.
    AsyncExample: Step 5- Create Classes inside Model Package based on the Received JSON – (JSON Parser)  To install android studio plugin follow these instructions: 1- from file, go to settings 2- go to plugins, and open marketplace tab 3- type the plugin name inside the search field and press enter 4- from search results, press the install button next to the plugin you want.  Retrieved dated are model using one of the following ways: Classes are manually created based on the received JSON from the API as noticed from step 1.  Using android studio plugins like GsonFormat or RoboPOJOGenerator to do this step for us  Visit Plugins homepage • https://plugins.jetbrains.com/plugin/7 654-gsonformat • https://plugins.jetbrains.com/plugin/8 634-robopojogenerator 19
  • 20.
    AsyncExample: Step 5- Create Classes inside Model Package based on the Received JSON – (JSON Parser) Using RoboPOJOGenerator plugin 1. Create model package 2. Mouse right click on model, go to New, then go to Generate POJO from JSON. 20
  • 21.
    AsyncExample: Step 5- Create Classes inside Model Package based on the Received JSON – (JSON Parser) Using RoboPOJOGenerator plugin 3. From RoboPOJOGenerator window: Set language to JAVA Set framework to None Copy JSON response from browser and paste inside the black region. Check create setters and create getters Rename the root object name to Contacts Finally, press Generate  Three classes were generated inside the model package:  Contacts: the root object from json response contain array of ContactsItem objects  ContactsItem: item object  Phone: phone object for each ContactsItem 21
  • 22.
    AsyncExample: Step 6 -Create ContactAdapter for the RecyclerView inside the adapter package 22 public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> { private ArrayList<ContactsItem> data; private Activity activity; public ContactAdapter(ArrayList<ContactsItem> data, Activity activity) { this.data = data; this.activity = activity; } public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View root = LayoutInflater.from(activity).inflate(R.layout.contact_item_layout, null, false); return new ContactViewHolder(root); } public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) { ContactsItem contact = data.get(position); holder.tvName.setText(String.valueOf(contact.getName())); holder.tvEmail.setText(contact.getEmail()); holder.tvMobile.setText(contact.getPhone().getMobile()); } public int getItemCount() { return data.size(); } public class ContactViewHolder extends RecyclerView.ViewHolder { TextView tvName, tvEmail,tvMobile; public ContactViewHolder(@NonNull View itemView) { super(itemView); tvName = itemView.findViewById(R.id.tvName); tvEmail = itemView.findViewById(R.id.tvEmail); tvMobile = itemView.findViewById(R.id.tvMobile); } } }
  • 23.
    23 class GetContacts extendsAsyncTask<Void,Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); pb.setVisibility(ProgressBar.VISIBLE); } @Override protected Void doInBackground(Void... voids) { String response = HttpHandler.makeServiceCall(BaseURi); if (response != null) { try { JSONObject jsonObject = new JSONObject(response); JSONArray contactsArray = jsonObject.getJSONArray("contacts"); for(int i=0; i< contactsArray.length(); i++){ JSONObject c = contactsArray.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); AsyncExample: Step 7 - In MainActivity.java, Create inner java class GetContacts that extends AsyncTask and override its methods
  • 24.
    AsyncExample: Step 7- In MainActivity.java, Create inner java class GetContacts that extends AsyncTask and override its methods 24 ContactsItem contact = new ContactsItem(); Phone phoneObj = new Phone(); phoneObj.setMobile(mobile); phoneObj.setHome(home); phoneObj.setOffice(office); contact.setName(name); contact.setEmail(email); contact.setPhone(phoneObj); contact.setId(id); contact.setAddress(address); contact.setGender(gender); data.add(contact); } } catch (JSONException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void voids) { super.onPostExecute(voids); pb.setVisibility(ProgressBar.GONE); ContactAdapter pa = new ContactAdapter(data, MainActivity.this); RecyclerView.LayoutManager manager=new LinearLayoutManager(MainActivity.this); rvContacts.setAdapter(pa); rvContacts.setLayoutManager(manager); } }
  • 25.
    AsyncExample: Step 8- Create object of GetContacts and call execute() method  In MainActivity.java, inside onCreate()  After binding the views (recyclerView and progressBar), we create an object of GetContacts and call the execute() // new GetContacts().execute(); GetContacts getContacts = new GetContacts(); getContacts.execute(); 25
  • 26.
    Lets Pratice Develop anandroid application that handle the following fake api that retrieve products details where request method is GET using AsyncTask. 26 https://5ef6eaac2c0f2c0016949dae.mockapi.io/products