Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Consuming Data from a Web Service with Android

In this article, you will learn aboutaccessing a web service RandomUser with Android, consuming, interpreting and displaying its contents

Currently, Android applications are increasingly common and with that comes the need for them to do some generic tasks, such as access to a Web Service. For example, you can access an application server and retrieve database information.

Something very important to remember is that an Android application should never directly access a database to retrieve or add information, primarily for security reasons. A system would not be safe if an Android application is conected to a remote database and work with the data without any intermediary layer. Another point to remember is that access to a web service is very important for standardization issues because the same customer SPA (Single Page Application) can access the same server with an Android or iOS application just following a pattern of requests and correctly interpreting the answers.

To create a web service, there are many ways and the simplest of them are with the GET and POST requests, which can be made through an HTML form. There is also the REST format, which is very used today and its return value is usually a JSON containing the information. This runs on top of the HTTP application protocol. There is also the SOAP protocol, but this is not very used because it has somewhat an exaggerated response to mobile systems.

The HTTP protocol is defined by RFCs 1945 and 2616, which define the structure of messages to be exchanged between the application server client. The general format of a request is very simple because it has a request line where the method will request the URL and version of the protocol.

In Listing 1 we see the example of the header lines that have the host and make the HTTP request, asking that particular page appears in the browser.

Listing 1. Typical HTTP request

 GET /diretorio/pagina1.htm HTTP/1.1
  Host: www.seusite.com.br
  Connection: close
  User-agent: Mozilla/2.0
  Accept-language: en 

As every request, a response is tied to it after processing and the structure of the HTTP response is very similar to the request. First there is the state line, where the version exists followed by the state code and the sentence. Subsequent lines are very similar, as shown in Listing 2, with a typical HTTP response.

Listing 2. Typical HTTP response

HTTP/1.1 200 OK
  Connection: close
  Date: Wed. 04 Nov 2015 11:31:24 GMT
  Server: Apache/2.0 (Unix)
  Last-Modified: Wed. 04 Nov 2015 11:31:24 GMT
  Content-Length: 2134
  Content-type: text/html
  (Data to be displayed in the browser) 

To understand how they work in practice requests, we will do a test by opening the terminal in Linux or Mac, or Windows prompt. Enter the Listing 3 content and see the result of the request.

Listing 3. Telnet

telnet google.com 80
  GET / HTTP1.1
  Host: google.com 

Since the goal of the article is not the development of a web service, but the consumption of its data, an online API will be used and the request will be made to that server. Your response will be interpreted, manipulated and displayed in the Android application screen.

The API to use is the randomuser.me site, an API that generates random information about people. When the request is made, a JSON is returned with the information to be worked. Listing 4 shows the structure of the JSON file that is returned in random when access is made.

Listing 4. Structure JSON file

{
      "results": [
          {
              "user": {
                  "gender": "female",
                  "name": {
                      "title": "mrs",
                      "first": "jetske",
                      "last": "van steen"
                  },
                  "location": {
                      "street": "1379 twijnstraat aan de werf",
                      "city": "delfzijl",
                      "state": "gelderland",
                      "zip": 51641
                  },
                  "email": "jetske.van steen@example.com",
                  "username": "heavyladybug279",
                  "password": "stoner",
                  "salt": "48ECNLyZ",
                  "md5": "cb3075f0e4f756bc8b65e366dc24335b",
                  "sha1": "c1be88f6529f468c975803fabada5ff4d0feae44",
                  "sha256": "8d8e3929260010615d804a6feb0fcc42db6e0cbc6ca613087f456d509dedda01",
                  "registered": 916019317,
                  "dob": 191584837,
                  "phone": "(407)-180-6810",
                  "cell": "(043)-907-1117",
                  "BSN": "65431107",
                  "picture": {
                      "large": "https://randomuser.me/api/portraits/women/24.jpg",
                      "medium": "https://randomuser.me/api/portraits/med/women/24.jpg",
                      "thumbnail": "https://randomuser.me/api/portraits/thumb/women/24.jpg"
                  }
              }
          }
      ],
      "nationality": "NL",
      "seed": "0933cf33c4bf81d506",
      "version": "0.7"
  }

Note that the various information returned a JSON file that can be handled and displayed without any problems.

In order to capture and interpret the information, first we analyze the class responsible for connecting to the server and receiving these data provided. Listing 5 shows the code responsible for this.

Listing 5. Code responsible for the network layer

package com.home.webservice;
   
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.net.HttpURLConnection;
  import java.net.MalformedURLException;
  import java.net.URL;
   
  /**
   * Created by anil on 11/4/15.
   */
  public class NetworkUtils {
   
      public static String getJSONFromAPI(String url){
          String result = "";
          try {
             URL apiEnd = new URL(url);
              int responseCode;
              HttpURLConnection connection;
              InputStream is;
   
              connection = (HttpURLConnection) apiEnd.openConnection();
              connection.setRequestMethod("GET");
              connection.setReadTimeout(15000);
              connection.setConnectTimeout(15000);
              connection.connect();
   
              responseCode = connection.getResponseCode();
              if(responseCode < HttpURLConnection.HTTP_BAD_REQUEST){
                  is = connection.getInputStream();
              }else{
                  is = connection.getErrorStream();
              }
   
              result = converterInputStreamToString(is);
              is.close();
              connection.disconnect();
   
          } catch (MalformedURLException e) {
              e.printStackTrace();
          }catch (IOException e){
              e.printStackTrace();
          }
   
          return result;
      }
   
      private static String converterInputStreamToString(InputStream is){
          StringBuffer buffer = new StringBuffer();
          try{
              BufferedReader br;
              String line;
   
              br = new BufferedReader(new InputStreamReader(is));
              while((line = br.readLine())!=null){
                  buffer.append(line);
              }
   
              br.close();
          }catch(IOException e){
              e.printStackTrace();
          }
   
          return buffer.toString();
      }
  }

By analyzing the getJSONFromAPI() method, note that a URL type of the object is instantiated. This object is responsible for opening a connection to the address where the web service data is located. Already HttpURLConnection type of the object is responsible for establishing the connection using the HTTP protocol.

Listing 6 shows more details about this object: note that an InputStream is declared and will be responsible for receiving the Stream server. Finally, a primitive attribute of type int is keyboard to receive the response code.

Listing 6. Code snippet InputStream

connection = (HttpURLConnection) apiEnd.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.connect();

As the connection object is of type InputStream, we note that a cast is made with apiEnd object URL type and stores the connection object. This means that the open connection processing is performed with the HTTP protocol. The type of request is set to GET and timeout times are also setados to 15000 milliseconds. Finally communication is established with the server using the HTTP protocol and the type of GET request.

Listing 7 shows the continuation of the connection method.

Listing 7. Code snippet receiving data

responseCode = connection.getResponseCode();
if(responseCode < HttpURLConnection.HTTP_BAD_REQUEST){
  is = connection.getInputStream();
}else{
 is = connection.getErrorStream();
}
   
result = converterInputStreamToString(is);
is.close();
connection.disconnect();

The response code is set in responseCode attribute, is an int. Within the if block it can be noted that any response code below the code contained in HTTP_BAD_REQUEST constant, which has a value of 400, will be assigned to the attribute type is InputStream. If the condition is not valid one errorStream will be awarded. The return receives the result of the method that will be analyzed in detail in Listing 8, it is closed and the connection is closed too. Thus the method can now return JSON for use in the application.

Listing 8. Method converterInputStreamToString

private static String converterInputStreamToString(InputStream is){
          StringBuffer buffer = new StringBuffer();
          try{
              BufferedReader br;
              String line;
   
              br = new BufferedReader(new InputStreamReader(is));
              while((line = br.readLine())!=null){
                  buffer.append(line);
              }
   
              br.close();
          }catch(IOException e){
              e.printStackTrace();
          }
   
          return buffer.toString();
      }

As the return obtained previously was an InputStream, our application will work much betterwith a string containing the full JSON and, as it is easier to parse, this helper method will be responsible for converting an InputStream to String.

A StringBuilder is declared and will be responsible for assembling the JSON string to be returned. A BufferedReader is also declared and will be responsible for making reading the InputStream buffer, along with a String to get the line read from BufferedReader.

Then the object br starts getting a new InputStreamReader, which is nothing more than class deals with the InputStream that was passed by parameter. A simple loop is done, getting the current line and if different from zero, this row is inserted in the StringBuffer, if not, the loop ends and mounted String is returned to the main method.

It is worth noting that whenever you want a StringBuffer returned as String is necessary to invoke the toString() on it.

Part of connection and receiving of the web service data is complete. Now what will be done are the necessary changes to the information received by the JSON is interpreted and displayed on the screen for the user.

A simple object was created to receive the information contained in the result of the web wervice, it is a simple POJO that contains various strings and a Bitmap that is responsible for storing an image. Listing 9 shows this code.

Listing 9. POJO code

package com.home.webservice;
   
  import android.graphics.Bitmap;
   
  /**
   * Created by anil on 11/4/15.
   */
  public class PersonPersonObj {
      private String name;
      private String surName;
      private String email;
      private String address;
      private String city;
      private String state;
      private String username;
      private String password;
      private String birthDay;
      private String phone;
      private Bitmap photo;
   
      public String getName() {
          return name;
      }
   
      public void setName(String name) {
          this.name = name;
      }
   
      public String getSurName() {
          return surName;
      }
   
      public void setSobrename(String surName) {
          this.surName = surName;
      }
   
      public String getEmail() {
          return email;
      }
   
      public void setEmail(String email) {
          this.email = email;
      }
   
      public String getAddress() {
          return address;
      }
   
      public void setAddress(String address) {
          this.address = address;
      }
   
      public String getCity() {
          return city;
      }
   
      public void setCity(String city) {
          this.city = city;
      }
   
      public String getState() {
          return state;
      }
   
      public void setState(String state) {
          this.state = state;
      }
   
      public String getUsername() {
          return username;
      }
   
      public void setUsername(String username) {
          this.username = username;
      }
   
      public String getPassword() {
          return password;
      }
   
      public void setPassword(String password) {
          this.password = password;
      }
   
      public String getBirthDay() {
          return birthDay;
      }
   
      public void setBirthDay(String birthDay) {
          this.birthDay = birthDay;
      }
   
      public String getPhone() {
          return phone;
      }
   
      public void setPhone(String phone) {
          this.phone = phone;
      }
   
      public Bitmap getPhoto() {
          return photo;
      }
   
      public void setPhoto(Bitmap photo) {
          this.photo = photo;
      }
  } 

Another class with general methods to perform operations of parse and image download has been created and can be seen in Listing 10.

Listing 10. Class responsible for general operations

 package com.home.webservice;
   
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import android.util.Log;
   
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
   
  import java.io.IOException;
  import java.io.InputStream;
  import java.net.URL;
  import java.text.SimpleDateFormat;
  import java.util.Date;
   
  /**
   * Created by anil on 11/4/15.
   */
  public class Utils {
   
      public PersonPersonObj getInformation(String end){
          String json;
          PersonPersonObj result;
          json = NetworkUtils.getJSONFromAPI(end);
          Log.i("Result", json);
          result = parseJson(json);
   
          return result;
      }
   
      private PersonPersonObj parseJson(String json){
          try {
              PersonPersonObj person = new PersonPersonObj();
   
              JSONObject jsonObj = new JSONObject(json);
              JSONArray array = jsonObj.getJSONArray("results");
   
              SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
              Date data;
   
              JSONObject objArray = array.getJSONObject(0);
   
              JSONObject obj = objArray.getJSONObject("user");
              //Atribui os objetos que estão nas camadas mais altas
              person.setEmail(obj.getString("email"));
              person.setUsername(obj.getString("username"));
              person.setPassword(obj.getString("password"));
              person.setPhone(obj.getString("phone"));
              data = new Date(obj.getLong("dob")*1000);
              person.setBirthDay(sdf.format(data));
   
              //Name da person é um objeto, instancia um novo JSONObject
              JSONObject name = obj.getJSONObject("name");
              person.setName(name.getString("first"));
              person.setSobrename(name.getString("last"));
   
              //Address tambem é um Objeto
              JSONObject address = obj.getJSONObject("location");
              person.setAddress(address.getString("street"));
              person.setState(address.getString("state"));
              person.setCity(address.getString("city"));
   
              //Imagem eh um objeto
              JSONObject photo = obj.getJSONObject("picture");
              person.setPhoto(downloadImage(photo.getString("large")));
   
              return person;
          }catch (JSONException e){
              e.printStackTrace();
              return null;
          }
      }
   
      private Bitmap downloadImage(String url) {
          try{
              URL address;
              InputStream inputStream;
              Bitmap image; address = new URL(url);
              inputStream = address.openStream();
              image = BitmapFactory.decodeStream(inputStream);
              inputStream.close();
              return image;
          }catch (IOException e) {
              e.printStackTrace();
              return null;
          }
      }
  }

The class shown in Listing 10 is divided into three methods: getInformation, parseJson and downloadImage.

The getInformation method returns a PersonPersonObj object type that will be used to populate the user interface. This method is public as it is called out of that class. Note that a call is made to the static method getJSONFromAPI() (already analyzed in Listing 5) and his return is stored in a String object type. A log is invoked so that the developer can see that the information is coming from the server correctly.

The parseJson method stores the result of getJSONFromAPI() method on an object of type PersonPersonObj and this object is returned to those invoked. This method is private, because it will be accessed only within their class of origin. It is also important to note that it takes a String with the complete JSON received from the server.

What we need to do now is to parse, or capture that JSON object and the information that will be displayed in the user interface. Three classes will be used that are embedded in the Android API to parse runs: JSONArray, JSONObject, JSONException. These three classes are located in org.json package.

When analyzing the JSON object contained in Listing 4 can observe a pattern in the creation and from that standard it should be done parse. Listing 11 shows in detail some calls in the most senior levels of the JSON object.

Listing 11. Code to parse the highest levels

JSONObject jsonObj = new JSONObject(json);
JSONArray array = jsonObj.getJSONArray("results");
   
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date data;
   
JSONObject objArray = array.getJSONObject(0);
   
JSONObject obj = objArray.getJSONObject("user");
person.setEmail(obj.getString("email"));
person.setUsername(obj.getString("username"));
person.setPassword(obj.getString("password"));
person.setPhone(obj.getString("phone"));
data = new Date(obj.getLong("dob")*1000);
person.setBirthDay(sdf.format(data));

First a JSONObject is instantiated through parameter string that contains the object. Just below the Array called results is instantiated as a JSONArray; one SimpleDateFormat is instantiated so that you can work with the date of birth, the same with the Object Data. Another JSONObject is declared and all objects that are contained in the first position of this JSON array are placed on that object. Note that this array has only one position is then accessed by the position 0. Now what is done is to assign the JSONObject and the contents of the user object.

Finally the getString and getLong methods are called for information to be uploaded to the fields of PersonPersonObj object.

Note the following line:

data = new Date(obj.getLong(“dob”)*1000);

This is because the date is given in EPOCH format, ie the number of seconds passed from the day January 1, 1970 until the date you want to see, then the amount is multiplied by 1000, it will be working with milliseconds for the date class can view it as a date. See the SimpleDateFormat format day/month/year.

Listing 12. Code to parse at lower levels

personJSONObject name = obj.getJSONObject("name");
person.setName(name.getString("first"));
person.setSobrename(name.getString("last"));
   
JSONObject address = obj.getJSONObject("location");
person.setAddress(address.getString("street"));
person.setState(address.getString("state"));
person.setCity(address.getString("city"));
   
JSONObject photo = obj.getJSONObject("picture");
person.setPhoto(downloadImage(photo.getString("large")));
   
return person; 

Note in the code that new JSON objects must be instantiated, this is because they are in sub-levels, for example, within the user level, there is the sub-level name that contains the name information and last name, the same with Address. In this code snippet is not very secret is just to know what levels and sub-levels and go instantiating. Its contents are also loaded and stored in the attributes of the object PersonPersonObj. Finally it may be noted that when loading the photo attribute, baixarPhoto() method is invoked, it is because JSON brings only the address of the photo is located, therefore, should be to download it, to show in the application, Listing 13 shows the method responsible for downloading the image.

Listing 13. baixarPhoto() Method

 private Bitmap downloadImage(String url) {
       try{
             URL address;
            InputStream inputStream;
            Bitmap image; address = new URL(url);
            inputStream = address.openStream();
            image = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
            return image;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
         }
    }

This is a simple private method responsible for converting an InputStream image of the Bitmap type using the static method decodeStream of BitmapFactory class.

Thus the utility class this finished, remembering that it is only responsible for dealing with the loaded information randomuser.me API.

Will now be studying the activity responsible for controlling the interface with the user, link to the layout XML. A simple layout is being used using RelativeLayout type. Your code is shown in Listing 14.

Listing 14. layout file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
      android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textAppearance="?android:attr/textAppearanceLarge"
          android:text="RandomUser"
          android:id="@+id/textView"
          android:layout_alignParentTop="true"
          android:layout_centerHorizontal="true" />
   
      <ImageView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/imageView"
          android:layout_below="@+id/textView"
          android:layout_alignLeft="@+id/textView"
          android:layout_marginTop="30dp"
          android:layout_alignParentLeft="true"/>
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView2"
          android:layout_below="@+id/textView3"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView3"
          android:layout_below="@+id/textView4"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView4"
          android:layout_below="@+id/textView7"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView5"
          android:layout_below="@+id/imageView"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="71dp"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Name:"
          android:id="@+id/textView6"
          android:layout_marginLeft="24dp"
          android:layout_marginStart="24dp"
          android:layout_alignBaseline="@+id/textView5"
          android:layout_alignBottom="@+id/textView5"
          android:layout_alignParentLeft="true"
          android:layout_alignParentStart="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView7"
          android:layout_below="@+id/textView8"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView8"
          android:layout_below="@+id/textView11"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView9"
          android:layout_below="@+id/textView10"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView10"
          android:layout_below="@+id/textView2"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView11"
          android:layout_below="@+id/textView5"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/textView12"
          android:layout_below="@+id/textView9"
          android:layout_centerHorizontal="true"
          android:layout_alignParentRight="true" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="SurName:"
          android:id="@+id/textView13"
          android:layout_below="@+id/textView6"
          android:layout_alignParentLeft="true"
          android:layout_marginLeft="22dp" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Email:"
          android:id="@+id/textView14"
          android:layout_below="@+id/textView13"
          android:layout_alignLeft="@+id/textView13"
          android:layout_alignStart="@+id/textView13" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Endereço:"
          android:id="@+id/textView15"
          android:layout_below="@+id/textView14"
          android:layout_alignLeft="@+id/textView14"
          android:layout_alignStart="@+id/textView14" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="City:"
          android:id="@+id/textView16"
          android:layout_below="@+id/textView15"
          android:layout_alignLeft="@+id/textView15"
          android:layout_alignStart="@+id/textView15" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="State:"
          android:id="@+id/textView17"
          android:layout_below="@+id/textView16"
          android:layout_alignLeft="@+id/textView14"
          android:layout_alignStart="@+id/textView14" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Username:"
          android:id="@+id/textView18"
          android:layout_below="@+id/textView17"
          android:layout_alignLeft="@+id/textView16"
          android:layout_alignStart="@+id/textView16" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Password:"
          android:id="@+id/textView19"
          android:layout_below="@+id/textView18"
          android:layout_alignLeft="@+id/textView18"
          android:layout_alignStart="@+id/textView18" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="BirthDay:"
          android:id="@+id/textView20"
          android:layout_below="@+id/textView19"
          android:layout_alignLeft="@+id/textView19"
          android:layout_alignStart="@+id/textView19" />
   
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Phone:"
          android:id="@+id/textView21"
          android:layout_alignTop="@+id/textView12"
          android:layout_alignLeft="@+id/textView20"
          android:layout_alignStart="@+id/textView20" />
  </RelativeLayout> 

Listing 15 actually shows the code of the Activity, which will be examined.

Listing 15. Main Activity Code

package com.home.webservice;
   
  import android.app.Activity;
  import android.app.ProgressDialog;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.widget.ImageView;
  import android.widget.TextView;
   
   
  public class MainActivity extends Activity {
      private TextView name;
      private TextView sobrename;
      private TextView email;
      private TextView address;
      private TextView city;
      private TextView state;
      private TextView username;
      private TextView password;
      private TextView birthDay;
      private TextView phone;
      private ImageView photo;
      private ProgressDialog load;
   
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
   
          GetJson download = new GetJson();
   
          name = (TextView)findViewById(R.id.textView5);
          sobrename = (TextView)findViewById(R.id.textView11);
          email = (TextView)findViewById(R.id.textView8);
          address = (TextView)findViewById(R.id.textView7);
          city = (TextView)findViewById(R.id.textView4);
          state = (TextView)findViewById(R.id.textView3);
          username = (TextView)findViewById(R.id.textView2);
          password = (TextView)findViewById(R.id.textView10);
          birthDay = (TextView)findViewById(R.id.textView9);
          phone = (TextView)findViewById(R.id.textView12);
          photo = (ImageView)findViewById(R.id.imageView);
   
          //Chama Async Task
          download.execute();
   
      }
   
      private class GetJson extends AsyncTask<Void, Void, PersonPersonObj> {
   
          @Override
          protected void onPreExecute(){
              load = ProgressDialog.show(MainActivity.this, "Please wait...", "Getting server info...");
          }
   
          @Override
          protected PersonPersonObj doInBackground(Void... params) {
              Utils util = new Utils();
   
              return util.getInformation("https://randomuser.me/api/");
          }
   
          @Override
          protected void onPostExecute(PersonPersonObj person){
              name.setText(person.getName().substring(0,1).toUpperCase()+person.getName().substring(1));
              sobrename.setText(person.getSobrename().substring(0,1).toUpperCase()+person.getSobrename().substring(1));
              email.setText(person.getEmail());
              address.setText(person.getAddress());
              city.setText(person.getCity().substring(0,1).toUpperCase()+person.getCity().substring(1));
              state.setText(person.getState());
              username.setText(person.getUsername());
              password.setText(person.getPassword());
              birthDay.setText(person.getBirthDay());
              phone.setText(person.getPhone());
              photo.setImageBitmap(person.getPhoto());
              load.dismiss();
          }
      }

Note that the onCreate method is very simple just doing the necessary instantiations to bridge the gap between the fields in the XML and the application using the findViewById method, and the end is made to call a Async Task.

Many may wonder now, but because I use the Async Task. The answer is simple, but will not work. One can use any technique of separating the processing type threads, but the async task already implements all for you facilitating their code. If parallel processing is not used an exception of type NetworkOnMainThreadException is thrown. There is a way to solve this problem, but it is a bad solution from the point of view of Android developers, and is mostly used as a palliative, so you can test the apply before separating processing, the code is to change the Android policies with respect to their application, the following code shows what must be done:

StrictMode.ThreadPolicy policy = newStrictMode.ThreadPolicy.Builder().permitAll().build();        
StrictMode.setThreadPolicy(policy);

By using this, you are telling the Android that your application can use network operations in the main thread, but this is bad, imagine yourself in a situation that network operations are taking place on the main thread and the server stops responding in one given time your application is closed or the user will find that everything is locked, but she's just waiting for the server response. Do not use it for real systems, the Async Task is there and solves these problems without causing damage to the navigation.

Within the Async Task three methods are implemented. The method protected void OnPreExecute(), which will be responsible for on-screen display a modal progress, showing the user that his request is running. The method protected PersonPersonObj doInBackground (Void ... params) that will be responsible for executing the first call that will do all the processing, download, parse, photo download in a separate thread. Finally the method protected void onPostExecute(PersonPersonObj person) that receives as parameter the return of doInBackground method, and it is responsible for putting on the screen all the information contained within the PersonPersonObj object and turn the mode of progress. You may notice that in some fields the substring method is called, this is just the first letter capitalized.

Finally we can not forget the manifest file, as the application will access a remote Web Service, the permission of access to the Internet should be given the manifest according to the Listing 16 code.

Listing 16. Android Manifest

<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.home.webservice" >
      <uses-permission android:name="android.permission.INTERNET"/>
      <application
          android:allowBackup="true"
          android:icon="@mipmap/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name=".MainActivity"
              android:label="@string/app_name" >
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />
   
                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>
   
  </manifest>

In Figure 1 may be accompanied by the results of the implementation described

Consuming Data from a Web Service with Android

Figure 1. Application Output

One can learn in this article how to connect to a WebService and consume your information, is simple and straightforward, just being needed some concepts of networks and HTTP protocol.

I hope you enjoyed until the next opportunity.



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login