Many times your Android app need 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 stand for extensible Markup Language, and
its syntax somewhat resembles HTML (Hyper Text Markup Language), in that they
are both markup languages. Sample XML representation of a human can be.
Let us drive to destination.
This is an API which have data in JSON format from where we will
fetch.
Process to fetch data from API.
- Create a list view xml file which have a list that will show when you finish it.
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
- <ListView android:id="@+id/list_title_list" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView>
- </LinearLayout>
- 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.
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="80dp"
-
- android:orientation="vertical"
- android:padding="5dp" >
-
- <ImageView
- android:id="@+id/iv_icon_social"
- android:layout_width="60dp"
- android:layout_height="60dp"
- android:layout_centerVertical="true"
-
- android:visibility="gone" />
-
- <LinearLayout
- android:id="@+id/thumbnail"
- android:layout_width="fill_parent"
- android:layout_height="85dp"
- android:layout_marginRight="50dp"
- android:layout_marginTop="0dp"
- android:layout_toRightOf="@+id/iv_icon_social"
- android:gravity="center_vertical"
- android:orientation="vertical"
- android:padding="5dip"
- android:visibility="visible" >
-
- <TextView
- android:id="@+id/txt_ttlsm_row"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:paddingLeft="10dp"
- android:text="Sample text"
- android:textSize="18dp"
- android:textStyle="bold" />
-
- <TextView
- android:id="@+id/txt_ttlcontact_row2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginBottom="0dp"
- android:layout_marginTop="3dp"
- android:paddingLeft="10dp"
- android:maxEms="20"
- android:maxLines="2"
- android:singleLine="false"
- android:ellipsize="end"
- android:text="Sample text2"
- android:textColor="#808080"
- android:textSize="15dp"
- android:textStyle="normal" />
- </LinearLayout>
- </RelativeLayout>
- 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 thread to do process in background and show result in UI. This is because when you do all network process in main thread that will crash the application so we will use this.
- class DownloadFilesTask extends AsyncTask < Void, Void, String >
- {
- private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
- @Override
- protected void onPreExecute()
- {
- super.onPreExecute();
- this.dialog.setMessage("Signing in...");
- this.dialog.show();
- }
- @Override
- protected String doInBackground(Void...params)
- {
- ServiceHandler sh = new ServiceHandler();
- String jsonStr = sh.makeServiceCall("http://jsonplaceholder.typicode.com/albums/", ServiceHandler.GET);
- Log.d("res1", jsonStr);
- return jsonStr;
- }
- @Override
- protected void onPostExecute(String response)
- {
- super.onPostExecute(response);
- Log.d("res2", response);
- dialog.dismiss();
- if (response != null)
- {
- try
- {
- JSONArray arr = new JSONArray(response);
- DataModel mDatModel = new DataModel();
- for (int i = 0; i < arr.length(); i++)
- {
- JSONObject c = arr.getJSONObject(i);
- String id = c.getString(ID);
- String title = c.getString(TITLE);
- String uid = c.getString(USER_ID);
- id_array.add(id);
-
- }
- adapter = new AAdapter(MainActivity.this, id_array);
- l.setAdapter(adapter);
- }
- catch (Exception e)
- {}
- }
- }
- }
- MainActivity.java
- public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener
- {
- AAdapter adapter;
- ArrayList < String > id_array = new ArrayList < String > ();
- ArrayList < String > notice_array = new ArrayList < String > ();
- Button b1;
- ListView l;
- private final static String SERVICE_URI = "http://jsonplaceholder.typicode.com/albums/";
- private static final String TAG_QUESTIONS = "Questions";
- private static final String USER_ID = "userId";
- private static final String ID = "id";
- private static final String TITLE = "title";
- JSONArray questions = null;
- protected void onSaveInstanceState(Bundle outState)
- {
- super.onSaveInstanceState(outState);
- }
- protected void onRestoreInstanceState(Bundle savedInstanceState)
- {
- super.onRestoreInstanceState(savedInstanceState);
- }
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- l = (ListView) findViewById(R.id.list);
- new DownloadFilesTask().execute();
- l.setOnItemClickListener(new AdapterView.OnItemClickListener()
- {
- @Override
- public void onItemClick(AdapterView < ? > parent, View view, int position, long id)
- {
- String abc = id_array.get(position);
- Toast.makeText(getBaseContext(), id_array.get(position), Toast.LENGTH_LONG).show();
- Intent n = new Intent(MainActivity.this, Titleshow.class);
- n.putExtra("id", id_array.get(position));
- startActivity(n);
- }
- });
- }
- @Override
- public void onItemClick(AdapterView < ? > parent, View view, int position, long id)
- {}
- Response in your main activity; there is a code as in the following,
- ServiceHandler sh = new ServiceHandler();
- String jsonStr = sh.makeServiceCall("http://jsonplaceholder.typicode.com/albums/", ServiceHandler.GET);
- 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.
- ServiceHandler.java
- class ServiceHandler
- {
- static String response = null;
- public final static int GET = 1;
- public final static int POST = 2;
- public ServiceHandler()
- {}
-
-
-
-
-
-
- public String makeServiceCall(String url, int method)
- {
- return this.makeServiceCall(url, method, null);
- }
-
-
-
-
-
-
-
- public String makeServiceCall(String url, int method, List < NameValuePair > params)
- {
- try
- {
-
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpEntity httpEntity = null;
- HttpResponse httpResponse = null;
-
- if (method == POST)
- {
- HttpPost httpPost = new HttpPost(url);
-
- if (params != null)
- {
- httpPost.setEntity(new UrlEncodedFormEntity(params));
- }
- httpResponse = httpClient.execute(httpPost);
- }
- else if (method == GET)
- {
-
- if (params != null)
- {
- String paramString = URLEncodedUtils.format(params, "utf-8");
- url += "?" + paramString;
- }
- HttpGet httpGet = new HttpGet(url);
- httpResponse = httpClient.execute(httpGet);
- }
- httpEntity = httpResponse.getEntity();
- response = EntityUtils.toString(httpEntity);
- }
- catch (UnsupportedEncodingException e)
- {
- e.printStackTrace();
- }
- catch (ClientProtocolException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- return response;
- }
- }
- 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.
- public class AAdapter extends BaseAdapter
- {
- private Activity activity;
-
- private static ArrayList title;
- private static LayoutInflater inflater = null;
- public AAdapter(Activity a, ArrayList b)
- {
- activity = a;
- this.title = b;
- inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
- public int getCount()
- {
- return title.size();
- }
- public Object getItem(int position)
- {
- return position;
- }
- public long getItemId(int position)
- {
- return position;
- }
- public View getView(int position, View convertView, ViewGroup parent)
- {
- View vi = convertView;
- if (convertView == null) vi = inflater.inflate(R.layout.abcd, null);
- TextView title2 = (TextView) vi.findViewById(R.id.txt_ttlsm_row);
- String song = title.get(position).toString();
- title2.setText(song);
- TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2);
- String song2 = title.get(position).toString();
- title22.setText(song2);
- return vi;
- }
- }
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,
- 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.
- public class MyAdapter extends BaseAdapter
- {
- ImageLoader imageLoader;
- private Context ctx;
- ArrayList < AlbumData > list;
- public MyAdapter(Context ctx, ArrayList < AlbumData > mDataList)
- {
- list = mDataList;
- this.ctx = ctx;
- }
- public int getCount()
- {
- return list.size();
- }
- public Object getItem(int position)
- {
- return position;
- }
- public long getItemId(int position)
- {
- return position;
- }
- public View getView(int position, View convertView, ViewGroup parent)
- {
-
- ViewHolder viewHolder;
- if (convertView == null)
- {
- LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- convertView = vi.inflate(R.layout.abcde, null);
- viewHolder = new ViewHolder();
- viewHolder.imageView = (ImageView) convertView.findViewById(R.id.image);
- viewHolder.textView = (TextView) convertView.findViewById(R.id.txt_ttlsm_row);
- convertView.setTag(viewHolder);
- }
- else
- {
- viewHolder = (ViewHolder) convertView.getTag();
- }
- AlbumData data = list.get(position);
- String a = data.getThumbnailUrl();
- if (data != null)
- {
- viewHolder.textView.setText(data.getTitle());
- String url = a;
- Glide.with(ctx).load(url).centerCrop().placeholder(R.drawable.abhi).crossFade().into(viewHolder.imageView);
-
-
-
-
-
- }
- return convertView;
- }
- public class ViewHolder
- {
- ImageView imageView;
- TextView textView;
- }
Code commented is nothing but 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 universal Image loader or glid image loader and we are using here glid image loader .
- public class ViewHolder
- {
- ImageView imageView;
- TextView textView;
- }
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 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 array list made very easy and manage project and help in future to handle the project.
- public class AlbumData
- {
- int albumId;
- int id;
- String title;
- String url;
- String thumbnailUrl;
- public int getAlbumId()
- {
- return albumId;
- }
- public void setAlbumId(int albumId)
- {
- this.albumId = albumId;
- }
- public int getId()
- {
- return id;
- }
- public void setId(int id)
- {
- this.id = id;
- }
- public String getTitle()
- {
- return title;
- }
- public void setTitle(String title)
- {
- this.title = title;
- }
- public String getUrl()
- {
- return url;
- }
- public void setUrl(String url)
- {
- this.url = url;
- }
- public String getThumbnailUrl()
- {
- return thumbnailUrl;
- }
- public void setThumbnailUrl(String thumbnailUrl)
- {
- this.thumbnailUrl = thumbnailUrl;
- }
- }
Output
Onclick on a list element.