How to Include an API Fetcher in your Android App

If you’re an app developer, there may be times when you want to include a web API for fetching data to provide your users. It’s not terribly difficult, and it can be done in either XML or JSON. So in this tutorial, we’re going to show you how to build a simple web API data fetcher into your Android app.

For this tutorial, we’ll be using JSON rather than XML.

Writing the code in JSON

First create a new list view XML file, with the following code:

<?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>
Next create a new XML file, and this is where you will list the elements you want shown (ImageView, TextView, etc.)
<?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>

In order to fetch data from the API, we will need to go to the main activity, and we need to use AsyncTask because API fetching is not possible on the main thread. AsyncTask is simply a thread that does background processes, while showing the results in UI. Using the main thread for network processes will typically crash your app. If that sounds a little confusing, check out some highly in-depth API tutorials over on RapidAPI.

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);

// Toast.makeText(getApplicationContext(), title, Toast.LENGTH_LONG).show();
}

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)

{}

You’ll find the response in your main activity

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()

{}

/**

* Making service call

*

* @url - url to make request

* @method - http request method

*/

public String makeServiceCall(String url, int method)

{

return this.makeServiceCall(url, method, null);

}

/**

* Making service call

*

* @url - url to make request

* @method - http request method

* @params - http request params

*/

public String makeServiceCall(String url, int method, List < NameValuePair > params)

{

try

{

// http client

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpEntity httpEntity = null;

HttpResponse httpResponse = null;

// Checking http request method type

if (method == POST)

{

HttpPost httpPost = new HttpPost(url);

// adding post params

if (params != null)

{

httpPost.setEntity(new UrlEncodedFormEntity(params));

}

httpResponse = httpClient.execute(httpPost);

}

else if (method == GET)

{

// appending params to url

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;

}

}

Next in your asyncTask, you’ll find an Adapter class, which will set the adapter method, but for this we need to create a custom adapter.

public class AAdapter extends BaseAdapter

{

private Activity activity;

// private ArrayList<HashMap<String, String>> data;

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); // title

String song = title.get(position).toString();

title2.setText(song);

TextView title22 = (TextView) vi.findViewById(R.id.txt_ttlcontact_row2); // notice

String song2 = title.get(position).toString();

title22.setText(song2);

return vi;

}

}

We need to remember that the adapter class is considered abstract class in Android, so we need to implement all methods. In the code below, the getview method is important, because we’ll add more code there to display the second XML file.

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

And we’ll also need an Adapter class for Load Image, so that the API fetcher can load images from the internet.

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)

{

// View vi = convertView;

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);

/* Picasso.with(ctx)

.load("https://keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image2.jpg")

.into(viewHolder.imageView);*/

/* ImageLoader imageLoader = ImageLoader.getInstance();

imageLoader.displayImage("http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg", viewHolder.imageView);*/

}

return convertView;

}

public class ViewHolder

{

ImageView imageView;

TextView textView;

}

We added a code comment that is really just a suggestion for Picasso image loader, which is a powerful open-source image downloader and caching library for Android, and keeps a lightweight footprint in your app. However, you can also use Glide image loader for more customization, as it offers GIF support and better memory management.

public class ViewHolder

{

ImageView imageView;

TextView textView;

}

What the view holder class does is create a static instance of ViewHolder, and then attach it to the view item on first load. It will then be retrieved from the view tag in future calls.

The getView() method is called a lot such as when there are a lot of elements in the ListView. So we’ll implement a data model class for the set and get method, which will help you to get the element of the array list, and just make your life easier in the future.

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;

}

}

That’s everything you need for now. You can test the output of this API fetcher in an app emulator like BlueStacks.

Tags

Tony Celentano


Tony Celentano is a traveling freelancer originally from New York, and currently resides in the Philippines. While passionate about writing, his other hobbies including tinkering with gadgets, painting, playing guitar, and being a stay-at-home dad.

Expert Tip

How to Include an API Fetcher in your Android App

If the issue is with your Computer or a Laptop you should try using Restoro which can scan the repositories and replace corrupt and missing files. This works in most cases, where the issue is originated due to a system corruption. You can download Restoro by clicking the Download button below.

Download Now

I'm not interested

Close