1

Android: Displaying data in listView fetched from a webservice

 Displaying data in listView fetched from a webservice

Description: In this tutorial, we learn how to fetch images from web service and display those images in a list view. This all processes include concepts such as URL connection, Parsing data, Panel java objects, Adapters.

Introduction:

Android mobile application is no doubt one of the most interesting fields when it comes to  application development. Often working with android application development, you will have to fetch data from an online server and display that in your app to be presented to the user. Since mobile application have limited, resources we would need a connection to online server in order fetch the necessary data that is intended to be presented in an android application.

Web services are made in programming languages such as PHP, ASP.net or other web development languages. Android application using any web service primary goal is to fetch data, and display it accordingly. Web services are no thing, but data providers this data can be text, images etc.

Let me give you an example, suppose i make a server script page, that comprises of the following code.

 

Before we start any sort of programming stuff, let’s have a look at the basic architecture that will make you familiar with how things work.

fetch data from webservice to listview

The basic architecture we will be learning in this tutorial (we make an android application that will perform the task) is shown above.

Screen Shots 

Here are screen shots that will let you know, what will be our end result once we apply all of the code mentioned in this tutorial. The first screen shot show how our home screen will look like containing a welcome message and button to fetch data. The second screen shot Fetch activity containing a list view with data that is retrieved from a web service.

Android webservice and listview

populate list view from webservice

 

Android application:

The android applications we build in this tutorial consist of simply two activities and some other java classes.

  • Home screen (MainActivity) with button to fetch data.
  • java activity (that contains list view to display fetched data from the web url)
  • Inner AyscTask class
  • Class for HTTP connection
  • Class for Data
  • Adapter Class

 

Download the complete source code here to test your self.

Home Screen (MainActivity.java)

Our home screen java class contains code that responds to the onclick event. Once the button is clicked, we will be prompted to the fetch.jav activity. Plus we have a textview that displays a welcome message.

main_activy.xml


<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"

android:background="#FFBB00">

 

<TextView android:text="Welcome to FetchDATA App" android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="30sp"

android:id="@+id/textView" />

 

<Button

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="New Button"

android:id="@+id/button"

android:layout_marginTop="56dp"

android:layout_below="@+id/textView"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

</RelativeLayout>

MainActivty.java

Here is the code for home screen of our application.


package com.example.khan_pti.mfetchdata;

import android.content.Intent;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

public class MainActivity extends ActionBarActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button b = (Button)findViewById(R.id.button);

b.setOnClickListener( new View.OnClickListener() {

@Override

public void onClick(View view) {

startActivity(new Intent(getBaseContext(),Fetch.class));

}

});

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

}

return super.onOptionsItemSelected(item);

}

}

 

Fetch.java class

The next class in our list is Fetch.java  that contains the main functionality of our application. When the user clicks on the button on the home screen, fetch.java activity will be prompted, and our background task that is explained below will be executed. Once the data is fetched from the server from using http URL connection we simply parse the data, store in in list array, and then populate our list view with data.

fetch.xml

Here is the xml representation of the fetch.java class, you clearly see, it contains list view.


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height="match_parent">

 

<ListView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/listView"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

</RelativeLayout>

Fetch.java


package com.example.khan_pti.mfetchdata;

import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.text.method.ScrollingMovementMethod;

import android.util.Log;

import android.widget.ListView;

import android.widget.TextView;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.net.HttpURLConnection;

import java.util.ArrayList;

/**

* Created by khan-pti on 30/03/2015.

*/

public class Fetch extends Activity {

ArrayList<Flowers> flowersList = new ArrayList<Flowers>();

String url ="http://services.hanselandpetal.com/feeds/flowers.json";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.fetch);

new BackTask().execute(url);

}

public class BackTask extends AsyncTask<String,String,String>{

@Override

protected void onPreExecute() {

super.onPreExecute();

}

@Override

protected String doInBackground(String... strings) {

String content =HttpULRConnect.getData(url);

return content;

}

@Override

protected void onPostExecute(String s) {

try {

JSONArray ar = new JSONArray(s);

for (int i=0; i<ar.length(); i++){

JSONObject jsonobject = ar.getJSONObject(i);

Flowers  flowers = new Flowers();

flowers.setName(jsonobject.getString("name"));

flowersList.add(flowers);

}

}

catch (JSONException e){

e.printStackTrace();

}

FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flowers_list_items, flowersList);

ListView lv = (ListView) findViewById(R.id.listView);

lv.setAdapter(adapter);

//Log.d("recived",s);

}

}

}

 

Flower_List_item.xml

Please note our list view will need another xml layout file that will specify how the items are placed in each row of the list. Since in this example we only want to mention the name of the flower, therefore we require single text view to show the name of the flowers.

 


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height="match_parent">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceMedium"

android:text="Medium Text"

android:id="@+id/textView3" />

</LinearLayout>

 

Explaination to Android AsyncTask Class:

In android programming, each activity runs on its main thread. That means the UI elements etc. run on the main thread of the activity. An android programmer should take care of this main thread , and should never freeze the main thread for so long that it is discarded by the android operating system.

What about long running tasks, how they should be performed, well to perform long running, task that last for few seconds, android provides a class that is called, Asynctsak class.

You may be thing, why don’t we use, the java threads, etc. that is because, when we deal with threads, we would not be able to access the android UI elements, to overcome this problem, and similar android has a special type of class know as AysncTask.

Android AsyncTask can be used as an inner class, and usually contains three overridden methods that are of most important.


@Override

protected void onPreExecute() {

//method is Before Starting Background thread/task

//starts progress bar

}

@Override

protected String doInBackground(String... params) {

//Background task running

&nbsp;

return "Task complete";

}

@Override

protected void onPostExecute(String result) {

//stop progress bar

//Method is used after task completed, update UI compenents

}

&nbsp;



<strong>Json Parser:</strong>

In Fetch.java class with in our inner class, onPostExecute() method the data is parsed, and then added to the flower list. Since we get the data in json array , we will need to first parse the data, in order to use it .



try {

JSONArray ar = new JSONArray(s);

for (int i=0; i&lt;ar.length(); i++){

JSONObject jsonobject = ar.getJSONObject(i);

Flowers  flowers = new Flowers();

flowers.setName(jsonobject.getString("name"));

flowersList.add(flowers);

}

}

catch (JSONException e){

e.printStackTrace();

}

Explanation to the code:

Make a new instance of JSONArray (), Passing the data received as an argument. Use loop to access each object, which can be used by instance of Flowers class and eventually we add the Flower’s object flowers to the FlowerList.

 

Flower Adapter class:

Flower Adapter class it used in order to fetch data from the Fetch.java class and inflate data into the listview the way we want. We have created our own custom Adapter class .


package com.example.khan_pti.mfetchdata;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ArrayAdapter;

import android.widget.TextView;

import java.util.ArrayList;

/**

* Created by khan-pti on 01/04/2015.

*/

public class FlowerAdapter extends ArrayAdapter<Flowers> {

private  ArrayList<Flowers> items;

private Context mContext;

public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){

super(context,textViewResourceID,items);

mContext = context;

this.items = items;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;

Flowers flowers = items.get(position);

if(v==null){

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

v=inflater.inflate(R.layout.flowers_list_items,null);

}

TextView title = (TextView)v.findViewById(R.id.textView3);

if (title != null) {

title.setText(flowers.getName());

}

return v;

}

}



Explanation to code:

We create our own adapter class that extends ArrayAdapter, with data type of our Flower class.

The constructor gets parameters that are passed with instance of FlowerAdapter .



public class FlowerAdapter extends ArrayAdapter<Flowers> {

private  ArrayList<Flowers> items;

private Context mContext;

public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){

super(context,textViewResourceID,items);

mContext = context;

this.items = items;

}

getView is the method, where we inflate the data into each of the row of our listview.


public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;

Flowers flowers = items.get(position);

if(v==null){

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

v=inflater.inflate(R.layout.flowers_list_items,null);

}

TextView title = (TextView)v.findViewById(R.id.textView3);

if (title != null) {

title.setText(flowers.getName());

}

return v;

}


 

Class for data model:

Now in this example we are going to make a class that will contain private members based on the the data we recive from the json URL. In our example we are getting data for flowers.

The data come with key value pairs, we need to make our containing private members for keys.I will be only including the names of the flowers to make it short, and easy for you.

In your case, what ever data you are getting you may do it accordingly.

Flowers.java


package com.example.khan_pti.mfetchdata;

/**

* Created by khan-pti on 30/03/2015.

*/

public class Flowers {

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

private String name;

}


Http URL Connection

Here we could use http client connection as well, but since android development team recommends using http URL connection, therefore we use URL connection method to connect to the server. Secondly http client is no more updated, where as http URL connection will be updated further since android development team is working on this.

HttpURL.java


package com.example.khan_pti.mfetchdata;

import android.util.Log;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpULRConnect {

public static String getData(String uri){

BufferedReader reader = null;

try {

URL url = new URL(uri);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

StringBuilder sb = new StringBuilder();

reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

Log.d("testhtt2","test");

String line;

while ((line= reader.readLine())!=null) {

sb.append(line+"\n");

}

Log.d("test44", sb.toString());

return sb.toString();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

return null;

}

finally{

 

if (reader!=null) {

try {

reader.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return null;

}

 

}

}}}

 


 

Android Manifest file:

In end here is the manifest file, don’t forget adding permission of using internet, without this your application will not work. We don’t have much to do, here accept for couple of lines added for permission, and declaring activity, in our case Fetch Activity.

 


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.khan_pti.mfetchdata" >

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

<activity android:name=".Fetch"></activity>

</application>

 

</manifest>


 

 

 

Conclusion:

Most of the android application, uses Listview, plus json, to fetch data .Most of the application rely on online server, in order fetch data, authenticate in fact application need to be connected to internet all the time to get user the latest updates. It is therefore on the most important topic that each and every programmer should know to develop an efficient android application. In this tutorial we have simply shown a text in the listview, where this can be further enhanced by adding images , and other text views to make it more complex and more informative. One can also add progress bar that can be set to visible in the onPreExecute () method, where as can be set invisible onPostExecute (). This can be one good enhancement.

Secondly we have no mechanism , about what happen when the user clicks on the listview items, while making android application you will obviously take care of that, you will only need to implement onclickListner that is it nothing else.

From here now, you can start looking to learn fragments, how to use fragments in list, view, and fragments providing best re usage and other advanced topics that will help you have quality application programmed.

At the conclusion I hope, you have learned some thing useful in this tutorial please let me know about you thoughts.

 

admin
 

student of computer Science , having interest and experience in C++,Java,Php,Html,Css,JavaScript, wordpress and android development

  • Adnan Khan

    Work like charm…thanks trustingeeks.com