How To Fetch Data From Web API In Android

, , Leave a comment

Introduction

 Many times your Android app needs to fetch data from the internet, to provide users with fresh information and/or data. There are different ways your app could achieve this. You could set up your own web service/API, or you could be fetching from an already existing service/API. In this article, we will discuss how to use a Web API within your Android app, to fetch data for your users. There are two major methods for retrieving data from most web services, XML or JSON. XML stands for extensible Markup Language, and its syntax somewhat resembles HTML (Hyper Text Markup Language), in that they are both markup languages. The sample XML representation of a human can be. 

 Let us drive to the destination.  This is an API that has data in JSON format from where we will fetch. The process to fetch data from API.

  1. Create a list view XML file which has a list that will show when you finish it.
    1. <?xml version=”1.0″ encoding=”utf-8″?>    
    2.     <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent”>    
    3.     <ListView android:id=”@+id/list_title_list” android:layout_width=”match_parent” android:layout_height=”match_parent”> </ListView>    
    4. </LinearLayout>   
  2. Create an XML file; it will have the element which you want to show in your list. That means in a section of list what do you want to show meant TextView, ImageView and so on.
    1. <?xml version=”1.0″ encoding=”utf-8″?>    
    2.    <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”    
    3.       android:layout_width=”fill_parent”    
    4.       android:layout_height=”80dp”    
    5.     
    6.       android:orientation=”vertical”    
    7.       android:padding=”5dp” >    
    8.     
    9.    <ImageView    
    10.       android:id=”@+id/iv_icon_social”    
    11.       android:layout_width=”60dp”    
    12.       android:layout_height=”60dp”    
    13.       android:layout_centerVertical=”true”    
    14.     
    15.       android:visibility=”gone” />    
    16.     
    17.    <LinearLayout    
    18.       android:id=”@+id/thumbnail”    
    19.       android:layout_width=”fill_parent”    
    20.       android:layout_height=”85dp”    
    21.       android:layout_marginRight=”50dp”    
    22.       android:layout_marginTop=”0dp”    
    23.       android:layout_toRightOf=”@+id/iv_icon_social”    
    24.       android:gravity=”center_vertical”    
    25.       android:orientation=”vertical”    
    26.       android:padding=”5dip”    
    27.       android:visibility=”visible” >    
    28.     
    29.    <TextView    
    30.       android:id=”@+id/txt_ttlsm_row”    
    31.       android:layout_width=”fill_parent”    
    32.       android:layout_height=”wrap_content”    
    33.       android:paddingLeft=”10dp”    
    34.       android:text=”Sample text”    
    35.       android:textSize=”18dp”    
    36.       android:textStyle=”bold” />    
    37.     
    38.    <TextView    
    39.       android:id=”@+id/txt_ttlcontact_row2″    
    40.       android:layout_width=”fill_parent”    
    41.       android:layout_height=”wrap_content”    
    42.       android:layout_marginBottom=”0dp”    
    43.       android:layout_marginTop=”3dp”    
    44.       android:paddingLeft=”10dp”    
    45.       android:maxEms=”20″    
    46.       android:maxLines=”2″    
    47.       android:singleLine=”false”    
    48.       android:ellipsize=”end”    
    49.       android:text=”Sample text2″    
    50.       android:textColor=”#808080″    
    51.       android:textSize=”15dp”    
    52.       android:textStyle=”normal” />    
    53.    </LinearLayout>    
    54. </RelativeLayout>   
  3. Now we will go to the main activity where we will find how to fetch data from API. There we should understand two things when we are going to work on networking. We could not do this on main thread so we will use AsyncTask and we have to get response from network as it is the response of request. AsyncTask- It is nothing but a thread to do process in background and show result in UI. This is because when you do all network process in the main thread that will crash the application so we will use this.
    1. class DownloadFilesTask extends AsyncTask < Void, Void, String >    
    2. {    
    3.     private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);    
    4.     @Override    
    5.     protected void onPreExecute()    
    6.     {    
    7.         super.onPreExecute();    
    8.         this.dialog.setMessage(“Signing in…”);    
    9.         this.dialog.show();    
    10.     }    
    11.     @Override    
    12.     protected String doInBackground(Void…params)    
    13.     {    
    14.         ServiceHandler sh = new ServiceHandler();    
    15.         String jsonStr = sh.makeServiceCall(“http://jsonplaceholder.typicode.com/albums/”, ServiceHandler.GET);    
    16.         Log.d(“res1”, jsonStr);    
    17.         return jsonStr;    
    18.     }    
    19.     @Override    
    20.     protected void onPostExecute(String response)    
    21.     {    
    22.         super.onPostExecute(response);    
    23.         Log.d(“res2”, response);    
    24.         dialog.dismiss();    
    25.         if (response != null)    
    26.         {    
    27.             try    
    28.             {    
    29.                 JSONArray arr = new JSONArray(response);    
    30.                 DataModel mDatModel = new DataModel();    
    31.                 for (int i = 0; i < arr.length(); i++)    
    32.                 {    
    33.                     JSONObject c = arr.getJSONObject(i);    
    34.                     String id = c.getString(ID);    
    35.                     String title = c.getString(TITLE);    
    36.                     String uid = c.getString(USER_ID);    
    37.                     id_array.add(id);    
    38.                     // Toast.makeText(getApplicationContext(), title, Toast.LENGTH_LONG).show();    
    39.                 }    
    40.                 adapter = new AAdapter(MainActivity.this, id_array);    
    41.                 l.setAdapter(adapter);    
    42.             }    
    43.             catch (Exception e)    
    44.             {}    
    45.         }    
    46.     }    
    47. }    
    48. MainActivity.java    
    49. public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener    
    50.     {    
    51.         AAdapter adapter;    
    52.         ArrayList < String > id_array = new ArrayList < String > ();    
    53.         ArrayList < String > notice_array = new ArrayList < String > ();    
    54.         Button b1;    
    55.         ListView l;    
    56.         private final static String SERVICE_URI = “http://jsonplaceholder.typicode.com/albums/”;    
    57.         private static final String TAG_QUESTIONS = “Questions”;    
    58.         private static final String USER_ID = “userId”;    
    59.         private static final String ID = “id”;    
    60.         private static final String TITLE = “title”;    
    61.         JSONArray questions = null;    
    62.         protected void onSaveInstanceState(Bundle outState)    
    63.         {    
    64.             super.onSaveInstanceState(outState);    
    65.         }    
    66.         protected void onRestoreInstanceState(Bundle savedInstanceState)    
    67.         {    
    68.             super.onRestoreInstanceState(savedInstanceState);    
    69.         }    
    70.         @Override    
    71.         protected void onCreate(Bundle savedInstanceState)    
    72.         {    
    73.             super.onCreate(savedInstanceState);    
    74.             setContentView(R.layout.activity_main);    
    75.             l = (ListView) findViewById(R.id.list);    
    76.             new DownloadFilesTask().execute();    
    77.             l.setOnItemClickListener(new AdapterView.OnItemClickListener()    
    78.             {    
    79.                 @Override    
    80.                 public void onItemClick(AdapterView < ? > parent, View view, int position, long id)    
    81.                 {    
    82.                     String abc = id_array.get(position);    
    83.                     Toast.makeText(getBaseContext(), id_array.get(position), Toast.LENGTH_LONG).show();    
    84.                     Intent n = new Intent(MainActivity.this, Titleshow.class);    
    85.                     n.putExtra(“id”, id_array.get(position));    
    86.                     startActivity(n);    
    87.                 }    
    88.             });    
    89.         }    
    90.         @Override    
    91.         public void onItemClick(AdapterView < ? > parent, View view, int position, long id)    
    92.         {}   
  4. Response in your main activity; there is a code as in the following, 
    1. ServiceHandler sh = new ServiceHandler();    
    2. String jsonStr = sh.makeServiceCall(“http://jsonplaceholder.typicode.com/albums/”, ServiceHandler.GET);    
    3. this nothing but a service handle class to request and get the respose from web api so we will do all this from web api.    
    4. ServiceHandler.java    
    5. class ServiceHandler    
    6. {    
    7.     static String response = null;    
    8.     public final static int GET = 1;    
    9.     public final static int POST = 2;    
    10.     public ServiceHandler()    
    11.         {}    
    12.         /**  
    13.          * Making service call  
    14.          *  
    15.          * @url – url to make request  
    16.          * @method – http request method  
    17.          */    
    18.     public String makeServiceCall(String url, int method)    
    19.         {    
    20.             return this.makeServiceCall(url, method, null);    
    21.         }    
    22.         /**  
    23.          * Making service call  
    24.          *  
    25.          * @url – url to make request  
    26.          * @method – http request method  
    27.          * @params – http request params  
    28.          */    
    29.     public String makeServiceCall(String url, int method, List < NameValuePair > params)    
    30.     {    
    31.         try    
    32.         {    
    33.             // http client    
    34.             DefaultHttpClient httpClient = new DefaultHttpClient();    
    35.             HttpEntity httpEntity = null;    
    36.             HttpResponse httpResponse = null;    
    37.             // Checking http request method type    
    38.             if (method == POST)    
    39.             {    
    40.                 HttpPost httpPost = new HttpPost(url);    
    41.                 // adding post params    
    42.                 if (params != null)    
    43.                 {    
    44.                     httpPost.setEntity(new UrlEncodedFormEntity(params));    
    45.                 }    
    46.                 httpResponse = httpClient.execute(httpPost);    
    47.             }    
    48.             else if (method == GET)    
    49.             {    
    50.                 // appending params to url    
    51.                 if (params != null)    
    52.                 {    
    53.                     String paramString = URLEncodedUtils.format(params, “utf-8”);    
    54.                     url += “?” + paramString;    
    55.                 }    
    56.                 HttpGet httpGet = new HttpGet(url);    
    57.                 httpResponse = httpClient.execute(httpGet);    
    58.             }    
    59.             httpEntity = httpResponse.getEntity();    
    60.             response = EntityUtils.toString(httpEntity);    
    61.         }    
    62.         catch (UnsupportedEncodingException e)    
    63.         {    
    64.             e.printStackTrace();    
    65.         }    
    66.         catch (ClientProtocolException e)    
    67.         {    
    68.             e.printStackTrace();    
    69.         }    
    70.         catch (IOException e)    
    71.         {    
    72.             e.printStackTrace();    
    73.         }    
    74.         return response;    
    75.     }    
    76. }   
  5. In your async Task you will get Adapter class which have set adapter method in the following Adapter. We will make our custom adapter here, so here’s the code.
    1. public class AAdapter extends BaseAdapter    
    2. {    
    3.     private Activity activity;    
    4.     // private ArrayList<HashMap<String, String>> data;    
    5.     private static ArrayList title;    
    6.     private static LayoutInflater inflater = null;    
    7.     public AAdapter(Activity a, ArrayList b)    
    8.     {    
    9.         activity = a;    
    10.         this.title = b;    
    11.         inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
    12.     }    
    13.     public int getCount()    
    14.     {    
    15.         return title.size();    
    16.     }    
    17.     public Object getItem(int position)    
    18.     {    
    19.         return position;    
    20.     }    
    21.     public long getItemId(int position)    
    22.     {    
    23.         return position;    
    24.     }    
    25.     public View getView(int position, View convertView, ViewGroup parent)    
    26.     {    
    27.         View vi = convertView;    
    28.         if (convertView == null) vi = inflater.inflate(R.layout.abcd, null);    
    29.         TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row); // title    
    30.         String song = title.get(position).toString();    
    31.         title2.setText(song);    
    32.         TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice    
    33.         String song2 = title.get(position).toString();    
    34.         title22.setText(song2);    
    35.         return vi;    
    36.     }    
    37. }   

Adapter class is abstract class in android so you have to implement all our methods given in that class or make it abstract but we will implement all methods. The method getview is important because we will write code here to show the second XML file,

  1. inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);   

Layout info later class is here to take XML element into android or in scr type to which we will set our required field. To load image from internet our adapter (something like that) and the entire code for this is given in zip file where we have other adapter service handler and different file for same task. We have not represented it here because it will create redundancy, so Adapter class for Load image is here.

  1. public class MyAdapter extends BaseAdapter    
  2. {    
  3.     ImageLoader imageLoader;    
  4.     private Context ctx;    
  5.     ArrayList < AlbumData > list;    
  6.     public MyAdapter(Context ctx, ArrayList < AlbumData > mDataList)    
  7.     {    
  8.         list = mDataList;    
  9.         this.ctx = ctx;    
  10.     }    
  11.     public int getCount()    
  12.     {    
  13.         return list.size();    
  14.     }    
  15.     public Object getItem(int position)    
  16.     {    
  17.         return position;    
  18.     }    
  19.     public long getItemId(int position)    
  20.     {    
  21.         return position;    
  22.     }    
  23.     public View getView(int position, View convertView, ViewGroup parent)    
  24.     {    
  25.         // View vi = convertView;    
  26.         ViewHolder viewHolder;    
  27.         if (convertView == null)    
  28.         {    
  29.             LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
  30.             convertView = vi.inflate(R.layout.abcde, null);    
  31.             viewHolder = new ViewHolder();    
  32.             viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image);    
  33.             viewHolder.textView = (TextView) convertView.findViewById(R.id.txt_ttlsm_row);    
  34.             convertView.setTag(viewHolder);    
  35.         }    
  36.         else    
  37.         {    
  38.             viewHolder = (ViewHolder) convertView.getTag();    
  39.         }    
  40.         AlbumData data = list.get(position);    
  41.         String a = data.getThumbnailUrl();    
  42.         if (data != null)    
  43.         {    
  44.             viewHolder.textView.setText(data.getTitle());    
  45.             String url = a;    
  46.             Glide.with(ctx).load(url).centerCrop().placeholder(R.drawable.abhi).crossFade().into(viewHolder.imageView);    
  47.             /* Picasso.with(ctx)  
  48.             .load(“http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg”)  
  49.             .into(viewHolder.imageView);*/    
  50.             /* ImageLoader imageLoader = ImageLoader.getInstance();  
  51.             imageLoader.displayImage(“http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg”, viewHolder.imageView);*/    
  52.         }    
  53.         return convertView;    
  54.     }    
  55.     public class ViewHolder    
  56.     {    
  57.         ImageView imageView;    
  58.         TextView textView;    
  59.     }   

Code commented is nothing but a suggestion for Picasso image loader. Picasso is not supporting sort URL so if you are using this then you have to convert the sort url to real URL for easy implementation. You can use a universal Image loader or glid image loader and we are using here glid image loader.

  1. public class ViewHolder    
  2. {    
  3.     ImageView imageView;    
  4.     TextView textView;    
  5. }   

View holder class is used to create a static instance of the ViewHolder and attach it to the view item the first time it is loaded, and then it will be retrieved from that view tag on the future calls. As we know getView() method is called very frequently, especially when lots of elements in the listview to scroll, in fact, it is called each time a listview item becomes visible on scroll. We will implement the data model class in which we write the set and get method. This will help us to get the element of the array list made very easy and manage projects and help in the future to handle the project. 

  1. public class AlbumData    
  2. {    
  3.     int albumId;    
  4.     int id;    
  5.     String title;    
  6.     String url;    
  7.     String thumbnailUrl;    
  8.     public int getAlbumId()    
  9.     {    
  10.         return albumId;    
  11.     }    
  12.     public void setAlbumId(int albumId)    
  13.     {    
  14.         this.albumId = albumId;    
  15.     }    
  16.     public int getId()    
  17.     {    
  18.         return id;    
  19.     }    
  20.     public void setId(int id)    
  21.     {    
  22.         this.id = id;    
  23.     }    
  24.     public String getTitle()    
  25.     {    
  26.         return title;    
  27.     }    
  28.     public void setTitle(String title)    
  29.     {    
  30.         this.title = title;    
  31.     }    
  32.     public String getUrl()    
  33.     {    
  34.         return url;    
  35.     }    
  36.     public void setUrl(String url)    
  37.     {    
  38.         this.url = url;    
  39.     }    
  40.     public String getThumbnailUrl()    
  41.     {    
  42.         return thumbnailUrl;    
  43.     }    
  44.     public void setThumbnailUrl(String thumbnailUrl)    
  45.     {    
  46.         this.thumbnailUrl = thumbnailUrl;    
  47.     }    
  48. }   

Output

 Onclick on a list element. 

 

Leave a Reply