AsyncTask

AsyncTask class allows performing all the background operations. It also publishes results on the User Interface thread without having to manipulate the threads or handlers or both. An asynchronous task is defined by three generic types. These types are known as Params, Progress, and Result.

There are four methods which must be overridden when you use AsyncTask. You must also implement the functionality of these methods also.

onPreExecute

doInBackground

onProgressUpdate

onPostExecute

Either you need to override onPostExecute(Result) method or doInBackground(Params…). Most often you need to override onPostExecute(Result).

MainActivity.java

Implement the button onClick event i.e. loadCountryInfo(View view) to get the data in the TextEdit

Within your MainActivity class, create a subclass named wsAsyncTask which will extend AsyncTask to run the background task. This class will help you to perform background tasks. In doInBackground(String[] strURL) method return requestWebService(strURL[0]). In the pre-execution of the of wsAsyncTasks, display a progress bar showing the loading. Dismiss the progress bar when the task is complete i.e. in onPostExecute() method.

Also, implement a method to request the web service in the wsAsyncTask class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

publicclassMainActivityextendsAppCompatActivity{

@Override

protectedvoidonCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

publicvoidloadCountryInfo(View view){

EditText cn=(EditText)findViewById(R.id.CountryName);

StringcountryName=cn.getText().toString();

StringstrURL="http://restcountries.eu/rest/v1/name/"+countryName;

if(countryName.length()==0){

//check if the length of the country name is null

Toast.makeText(this,"No Country Specified",Toast.LENGTH_SHORT).show();

}else{

//execute wsAyncTask by its instance

wsAsyncTask ws=newwsAsyncTask();

ws.execute(strURL);

}

}

//..................wsAsyncTask subclass.....................

privateclasswsAsyncTask extendsAsyncTask<String,Void,String>{

@Override

protectedStringdoInBackground(String[]strURL){

returnrequestWebService(strURL[0]);

}

@Override

protectedvoidonPreExecute(){

//displaying progress bar to ask the user to wait until the loading is not complete

super.onPreExecute();

dialog=newProgressDialog(MainActivity.this);

dialog.setTitle("Please Wait..");

dialog.setMessage("Loading...");

dialog.setCancelable(false);

dialog.show();

}

@Override

protectedvoidonPostExecute(Stringresult){

//do something

dialog.dismiss();//dismiss the loading dialog

}

//Requesting the web service

publicStringrequestWebService(StringserviceUrl){

returnnull;

}

}

}

requestWebService()

Create Connection

Pass the URL as a string in the method. Create an instance of URL class and put the serviceURL value from the parameters in URL class constructor. Create an instance of HttpURLConnection and initialize the connection with.(HttpURLConnection) urlToRequest.openConnection() Set the connect timeout and read timeout for the connection.

Get the JSON Data

Use InputStream for URL connection Input Stream. Instantiate InputStream class and call the constructor of BufferedInputStream(urlConnection.getInputStream()). Use Scanner class to convert input stream to the string. After conversion close the Scanner.