In Android Tab Layout Tutorial i explained how to implement a tab view. This tutorial is about implementing list view inside a tab layout. Everything is same except tabs will have listview inside it. List data is displayed by fetching json by making http request. I took an example of simple mailbox which will contains two list views for inbox, outbox messages and a profile tab.

Download Code

In this example i am displaying list view in each tab where the list data is fetched from a JSON.

Get Inbox JSON here

{
    "messages": [
        {
                "id": "1",
                "from": "Android Hive",
                "email": "androidhive@gmail.com",
                "subject": "New Subscriber..",
                "message" : "Tutorial about combing Android Tabview and ListView",
                "date": "May 9"
        },
		{
                "id": "2",
                "from": "Pay Pal",
                "email": "paypal@paypal.com",
                "subject": "Payment Notification",
                "message" : "Tutorial about combing Android Tabview and ListView",
                "date": "May 7"
        },
        .
        .

    ]
}

Get Outbox JSON here.

{
    "messages": [
        {
                "id": "1",
                "to": "dine@gmail.com",
                "subject": "Movie Tickets Confirmation..",
                "message" : "Tutorial about combing Android Tabview and ListView",
                "date": "May 22"
        },
		{
                "id": "2",
                "to": "william@gmail.com",
                "subject": "Project estimataion details",
                "message" : "Tutorial about combing Android Tabview and ListView",
                "date": "May 21"
        },
        .
        .
        .
    ]
}

And get Profile JSON here

{
    "profile": {
        "id": "1",
        "name": "Ravi Tamada",
        "email": "ravi8x@gmail.com",
        "mobile": "+91 0000000000",
        "address": "xxx - xxx -xxxxxx"
    }
}

Create new Project

So let’s start with creation of new project in Eclipse IDE.

1. Create a new project File -> New -> Android Project and fill out required details.
2. Open your Main Activity and extend the class from TabActivity.

public class AndroidTabAndListView extends TabActivity {

3. Now open your main.xml under res -> layout folder and type the following code to create a tabview.

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    </LinearLayout>
</TabHost>

4. Create three activities for 3 tabs. I am creating 3 activities as InboxActivity.java, OutboxActvity.java and ProfileActivity.java and extend the classes from ListActivity.

package com.example.androidhive;

import android.app.ListActivity;
import android.os.Bundle;

public class InboxActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inbox_list);
    }
}
package com.example.androidhive;

import android.app.ListActivity;
import android.os.Bundle;

public class OutboxActivity extends ListActivity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.outbox_list);
    }
}

Note that ProfileActivity.java in not ListActivity.

package com.example.androidhive;

import android.app.Activity;
import android.os.Bundle;

public class ProfileActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
    }
}

5. Now create xml layouts for the list views. Here we have two list views and a normal layout. So create totally 5 xml layouts. inbox_list.xml, outbox_list.xml, profile.xml, inbox_list_item.xml (inbox listview single row item), outbox_list_item.xml (outbox listview single row item)

inbox_list.xml

<?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"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

inbox_list_item.xml

<?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="wrap_content"
    android:orientation="vertical" >

    <!-- From Label -->
    <TextView
        android:id="@+id/from"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="8dip"
        android:paddingLeft="8dip"
        android:paddingBottom="4dip"
        android:textSize="20dip"
        android:textStyle="bold" />
    
    <!-- Mail Subject -->
    <TextView android:id="@+id/subject"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:paddingLeft="8dip"
        android:paddingBottom="6dip"
        android:textSize="15dip"
        android:layout_below="@id/from"/>
    
    <!-- Mail date -->
    <TextView android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:padding="8dip"/>/
 
</RelativeLayout>

outbox_list.xml

<?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"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

outbox_list_item.xml

<?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="wrap_content"
    android:orientation="vertical" >

    <!-- Subject Label -->
    <TextView
        android:id="@+id/subject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="8dip"
        android:paddingLeft="8dip"
        android:paddingBottom="4dip"
        android:textSize="18dip"
        android:textStyle="bold" />
    
    <!-- To email -->
    <TextView android:id="@+id/to"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:paddingLeft="8dip"
        android:paddingBottom="6dip"
        android:textSize="15dip"
        android:layout_below="@id/subject"/>
    
    <!-- Mail date -->
    <TextView android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:padding="8dip"/>
 
</RelativeLayout>

profile.xml

<?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"
    android:orientation="vertical">
    
    <!-- Name -->
    <TextView android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="28dip"
        android:paddingLeft="15dip"
        android:layout_marginTop="15dip"/>
    
    <TextView android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip"
        android:paddingLeft="15dip"/>
    
    <TextView android:id="@+id/mobile"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="21dip"
        android:paddingLeft="15dip"/>
    
    <TextView android:id="@+id/address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20dip"
        android:paddingLeft="15dip"/>
 
</LinearLayout>

6. Each and every tab needs an icon so design icons for each tab. We need three dimensions of each icon. Design each icon in 48 x 48 px, 32 x 32 px and 24 x 24 px and place them in drawable-hdpi, drawable-mdpi and drawable-ldpi respectively. See following diagram for your guidance

android tab layout icon sizes

7. Android icon states will be define in xml files with default and hover state configurations. For three icons we need the icon state configuration files. So create three 3 xml files under drawable-hdpi directory. Type the following code for icon states.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/inbox_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/inbox_white" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/outbox_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/outbox_white" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/profile_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/profile_white" />
</selector>

8. Now open AndroidTabAndListView.java which is Main Activity and type the following code. In the following code we are creating three TabSepcs and adding them to TabHost.

package com.example.androidhive;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class AndroidTabAndListView extends TabActivity {
	// TabSpec Names
	private static final String INBOX_SPEC = "Inbox";
	private static final String OUTBOX_SPEC = "Outbox";
	private static final String PROFILE_SPEC = "Profile";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TabHost tabHost = getTabHost();
        
        // Inbox Tab
        TabSpec inboxSpec = tabHost.newTabSpec(INBOX_SPEC);
        // Tab Icon
        inboxSpec.setIndicator(INBOX_SPEC, getResources().getDrawable(R.drawable.icon_inbox));
        Intent inboxIntent = new Intent(this, InboxActivity.class);
        // Tab Content
        inboxSpec.setContent(inboxIntent);
        
        // Outbox Tab
        TabSpec outboxSpec = tabHost.newTabSpec(OUTBOX_SPEC);
        outboxSpec.setIndicator(OUTBOX_SPEC, getResources().getDrawable(R.drawable.icon_outbox));
        Intent outboxIntent = new Intent(this, OutboxActivity.class);
        outboxSpec.setContent(outboxIntent);
        
        // Profile Tab
        TabSpec profileSpec = tabHost.newTabSpec(PROFILE_SPEC);
        profileSpec.setIndicator(PROFILE_SPEC, getResources().getDrawable(R.drawable.icon_profile));
        Intent profileIntent = new Intent(this, ProfileActivity.class);
        profileSpec.setContent(profileIntent);
        
        // Adding all TabSpec to TabHost
        tabHost.addTab(inboxSpec); // Adding Inbox tab
        tabHost.addTab(outboxSpec); // Adding Outbox tab
        tabHost.addTab(profileSpec); // Adding Profile tab
    }
}

9. Now open your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below. Also don’t forgot to add INTERNET Permissions as we are getting JSON by making http request.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:configChanges="keyboardHidden|orientation"
            android:name=".AndroidTabAndListView"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Inbox Activity -->
        <activity android:name=".InboxActivity" />

        <!-- Outbox Activity -->
        <activity android:name=".OutboxActivity" />

        <!-- Profile Activity -->
        <activity android:name=".ProfileActivity" />
    </application>

    <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

10. If you run your project now you will see tabs running without listviews. So all we need to do is implement listview in each tab activity. So open you individual tab activity classes and try to implement listview. If you are new to ListView i suggest you to go through Android ListView Tutorial once.

InboxActivity.java

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class InboxActivity extends ListActivity {
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();

	ArrayList<HashMap<String, String>> inboxList;

	// products JSONArray
	JSONArray inbox = null;

	// Inbox JSON url
	private static final String INBOX_URL = "https://api.androidhive.info/mail/inbox.json";
	
	// ALL JSON node names
	private static final String TAG_MESSAGES = "messages";
	private static final String TAG_ID = "id";
	private static final String TAG_FROM = "from";
	private static final String TAG_EMAIL = "email";
	private static final String TAG_SUBJECT = "subject";
	private static final String TAG_DATE = "date";
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox_list);
		
		// Hashmap for ListView
        inboxList = new ArrayList<HashMap<String, String>>();
 
        // Loading INBOX in Background Thread
        new LoadInbox().execute();
	}

	/**
	 * Background Async Task to Load all INBOX messages by making HTTP Request
	 * */
	class LoadInbox extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(InboxActivity.this);
			pDialog.setMessage("Loading Inbox ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			// getting JSON string from URL
			JSONObject json = jsonParser.makeHttpRequest(INBOX_URL, "GET",
					params);

			// Check your log cat for JSON reponse
			Log.d("Inbox JSON: ", json.toString());

			try {
				inbox = json.getJSONArray(TAG_MESSAGES);
				// looping through All messages
				for (int i = 0; i < inbox.length(); i++) {
					JSONObject c = inbox.getJSONObject(i);

					// Storing each json item in variable
					String id = c.getString(TAG_ID);
					String from = c.getString(TAG_FROM);
					String subject = c.getString(TAG_SUBJECT);
					String date = c.getString(TAG_DATE);

					// creating new HashMap
					HashMap<String, String> map = new HashMap<String, String>();

					// adding each child node to HashMap key => value
					map.put(TAG_ID, id);
					map.put(TAG_FROM, from);
					map.put(TAG_SUBJECT, subject);
					map.put(TAG_DATE, date);

					// adding HashList to ArrayList
					inboxList.add(map);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							InboxActivity.this, inboxList,
							R.layout.inbox_list_item, new String[] { TAG_FROM, TAG_SUBJECT, TAG_DATE },
							new int[] { R.id.from, R.id.subject, R.id.date });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}

OutboxActivity.java

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

public class OutboxActivity extends ListActivity {
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();

	ArrayList<HashMap<String, String>> outboxList;

	// products JSONArray
	JSONArray outbox = null;

	// Outbox JSON url
	private static final String OUTBOX_URL = "https://api.androidhive.info/mail/outbox.json";
	
	// ALL JSON node names
	private static final String TAG_MESSAGES = "messages";
	private static final String TAG_ID = "id";
	private static final String TAG_TO = "to";
	private static final String TAG_SUBJECT = "subject";
	private static final String TAG_DATE = "date";
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.outbox_list);
		
		// Hashmap for ListView
        outboxList = new ArrayList<HashMap<String, String>>();
 
        // Loading OUTBOX in Background Thread
        new LoadOutbox().execute();
	}

	/**
	 * Background Async Task to Load all OUTBOX messages by making HTTP Request
	 * */
	class LoadOutbox extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(OutboxActivity.this);
			pDialog.setMessage("Loading Outbox ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Outbox JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			// getting JSON string from URL
			JSONObject json = jsonParser.makeHttpRequest(OUTBOX_URL, "GET",
					params);

			// Check your log cat for JSON reponse
			Log.d("Outbox JSON: ", json.toString());

			try {
				outbox = json.getJSONArray(TAG_MESSAGES);
				// looping through All messages
				for (int i = 0; i < outbox.length(); i++) {
					JSONObject c = outbox.getJSONObject(i);

					// Storing each json item in variable
					String id = c.getString(TAG_ID);
					String to = c.getString(TAG_TO);
					String subject = c.getString(TAG_SUBJECT);
					String date = c.getString(TAG_DATE);
					
					// subject taking only first 23 chars
					// to fit into screen
					if(subject.length() > 23){
						subject = subject.substring(0, 22) + "..";
					}

					// creating new HashMap
					HashMap<String, String> map = new HashMap<String, String>();

					// adding each child node to HashMap key => value
					map.put(TAG_ID, id);
					map.put(TAG_TO, to);
					map.put(TAG_SUBJECT, subject);
					map.put(TAG_DATE, date);

					// adding HashList to ArrayList
					outboxList.add(map);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							OutboxActivity.this, outboxList,
							R.layout.outbox_list_item, new String[] { TAG_SUBJECT, TAG_TO, TAG_DATE },
							new int[] { R.id.subject, R.id.to, R.id.date });
					// updating listview
					setListAdapter(adapter);
				}
			});

		}

	}
}

ProfileActivity.java

package com.example.androidhive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class ProfileActivity extends Activity {
	// All xml labels
	TextView txtName;
	TextView txtEmail;
	TextView txtMobile;
	TextView txtAddress;
	
	// Progress Dialog
	private ProgressDialog pDialog;

	// Creating JSON Parser object
	JSONParser jsonParser = new JSONParser();
	
	// Profile json object
	JSONObject profile;
	
	// Profile JSON url
	private static final String PROFILE_URL = "https://api.androidhive.info/mail/profile.json";
	
	// ALL JSON node names
	private static final String TAG_PROFILE = "profile";
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "name";
	private static final String TAG_EMAIL = "email";
	private static final String TAG_MOBILE = "mobile";
	private static final String TAG_ADDRESS = "address";
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);
		
		txtName = (TextView) findViewById(R.id.name);
		txtEmail = (TextView) findViewById(R.id.email);
		txtMobile = (TextView) findViewById(R.id.mobile);
		txtAddress = (TextView) findViewById(R.id.address);
		
        // Loading Profile in Background Thread
        new LoadProfile().execute();
	}

	/**
	 * Background Async Task to Load profile by making HTTP Request
	 * */
	class LoadProfile extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ProfileActivity.this);
			pDialog.setMessage("Loading profile ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting Profile JSON
		 * */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			
			// getting JSON string from URL
			JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "GET",
					params);

			// Check your log cat for JSON reponse
			Log.d("Profile JSON: ", json.toString());

			try {
				// profile json object
				profile = json.getJSONObject(TAG_PROFILE);
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					// Storing each json item in variable
					try {
						String id = profile.getString(TAG_ID);
						String name = profile.getString(TAG_NAME);
						String email = profile.getString(TAG_EMAIL);
						String mobile = profile.getString(TAG_MOBILE);
						String address = profile.getString(TAG_ADDRESS);
						
						// displaying all data in textview
						txtName.setText(name);
						txtEmail.setText("Email: " + email);
						txtMobile.setText("Mobile: " + mobile);
						txtAddress.setText("Add: " + address);
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});

		}

	}
}

11. Finally create a class called JSONParser.java and paste the following code as we need a parser class to parse the json.

package com.example.androidhive;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
 
        // Making HTTP request
        try {
 
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
 
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
 
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }            
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
}

12. Now Run & Test your project.

android tab layout and list view
android tab layout and list view
android tab layout and list view
This image is for thumbnail purpose
android combining tab layout and list view
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Pingback: FrAndroid DevSharing #3 | FrAndroid Communauté Android()

  • Pingback: FrAndroid DevSharing #3 : Freamware()

  • Rohit

    Sir, i want to know that if i click on any item from the list view and one child activity opens but tabs remain on the same position. how can we handle this problem?

  • Labidi4

    Nice Tut, but when i add OnItemClickListener to start a new activity so i can show some details about the clicked item i loose the TabHost , is there a way i can start a new activity within the tabhost ?

    • gandos

      you can’t start a new activity inside a tabview. instead you could replace the content by calling setContentView. i’ve tried this and work

      • Guest

        Can you give an example. I tried setContentView with an intent but it did nothing. I was able to do as the person said above or switch the tab but not stay on the same tab and switch out the content section.

        • Zeus

          can u give an eg for setContentView

  • netX

    your tutorial works great but is there anyway i can link this project with “Android Login and Registration with PHP, MySQL and SQLite” project. i will like to use the registration info to create the profile data for profile.json

  • James

    Nice write up!

  • Andrei B.

    Actually, no. You can use the later SDKs (which include fragments) and still compile for 2.3. I’ve done it, there’s no trick to it.

    http://stackoverflow.com/questions/6528691/fragments-in-android-2-2-1-2-3-2-0-is-this-possible

    • Guest

      What about 2.2?

      • Andrei B.

        I think it also works for 2.2. I remember I compiled for that version also a while back.

        • anon

          And the fragment way totally blows. Way more work, more files and not nearly as concise. I can see why so many developers have a gripe with android development.

  • amay

    Hello, how if add combine with Fragment Tabhost ?

  • Roneykakkanatt

    Learn ANDROID from the very beginning

    VISIT ANDROIDITUTS

    http://www.androidituts.com

  • puneet kumar

    nice tutorial it is very helpful

  • Imran

    Can you please give me implementation of itemClickLister on inboxActivity List please…..

  • pappu

    very good ….. Nyc

  • MikeP

    Thanks. I appreciate your tutorials to get me started with android. I picked up quick. From Desktop now to mobile.

  • zee zee lukman

    thank you, good tut, can you help me, how to create a charts?
    your help means a lot to me..

  • Preety Pie

    i’m getting an error in the ProfileActivity.java class. how can i correct it?

  • Birat

    Can I use array adapter list view with tab layout??

  • James

    how do i write the JSON Parsed Data?

  • Virender

    how to open other activity under the tab host? please reply me asap.
    thanks

  • priya

    Your tutorials works perfectly. could you send the code behind http://api.androidhive.info/mail/inbox.json ??
    I’m new to Android and i need your help.
    thanks

  • Ahmadraza

    Some clear which URL is passing to JSONParser.java to
    String paramString = URLEncodedUtils.format(params, “utf-8”);
    url += “?” + paramString;
    HttpGet httpGet = new HttpGet(url);

  • george

    Hi all. I am a novice in developing app and thanks to
    Ravi for all good work that is doing . I’m working at a simple app and I get
    stuck . if you have knowledge of
    building android apps, and make team
    with me please replay to george.celsie@gmail.com . Thanks ang
    good luck for all your projects..

  • Cuong Rio

    Many thanks

  • Praveen

    Thanks for this good tutorial. It really helped me.
    I have a question:
    Can we add swipe feature to this app? If yes please explain that…

  • Puneet

    How do I start another activity from say ProfileActivity.java within same tab (Profile in my example)?

  • Yuri Rodrigues

    dont work in android studio.

  • Abeer

    ListAdapter adapter = new SimpleAdapter(
    InboxActivity.this, inboxList,
    R.layout.inbox_list_item, new String[] { TAG_FROM, TAG_SUBJECT, TAG_DATE },
    new int[] { R.id.from, R.id.subject, R.id.date });
    // updating listview
    setListAdapter(adapter);

    kindly how to change that above with the (class extends ListFragment)

  • Gandhali

    The app is gr8..the logic and everything…however in my case its not going beyond “Loading Inbox” n then it force closes…i think may be its about internet proxy settings…can u elaborate on setting proxy settings here…

  • ak

    please How can I add onclick listener to the Listadapter. pls and pls. respond. I know this project is old. need that ans like air.

    • meme

      please if u know how apply onclick listener tell me 🙁

  • reza

    hi i need to combine grideviw combining with swipe tabhost layout can you help me.? tx reza

  • Gusti Bimo

    What if i want to show listVIew in tab layout using fragment not tabActivity, how to implement listview in fragment?

    • Aditya Mehta

      I also want to know the same if you find the answer please let me know too

  • Aditya Mehta

    I have implement tabs using fragement. How I can handle listview event in that?

  • bala chander

    Hi Friends i need surveillance camera app source code could you pls help me.

  • Shankar Ganesh

    {

    “messages”: [

    {

    “id”: “1”,

    “from”: “Android Hive”,

    “email”: “androidhive@gmail.com”,

    “subject”: “New Subscriber..”,

    “message” : “Tutorial about combing Android Tabview and ListView”,

    “date”: “May 9”

    },

    {

    “id”: “2”,

    “from”: “Pay Pal”,

    “email”: “paypal@paypal.com”,

    “subject”: “Payment Notification”,

    “message” : “Tutorial about combing Android Tabview and ListView”,

    “date”: “May 7”

    },

    .

    .

    ]

    }

    how to generate this model of array by selecting values from mysql database using select statement and send it in JSON response??

  • kavya shree

    hi ravi sir, i m doing android project and its “Greeting sending app”… can i get the source code for customizing greetind card..

  • andhy fauzi

    thx bro.. this is so help me

  • Kranthi kumar

    Thank you so much and it is very helpful for me.

  • Sanyog Nishandar

    hi sir , i want to create tabs in fragments and then attach it another main project as my work is to design front end.. i have 2 different layouts , can i use recycler for it ?

  • Aditya

    Hi Ravi, i have created Gmail and Facebook Login and i fetched data like profile image and email and name to another activity using shared preferences now i need show that data into Tab Activity , i’m confused now where to use shared preferences to display both in Fragments, plzzzzzzz Help soon…

    • You have to call shared preferences in Fragment onCreate method. Learn about Fragments.

  • ankur bhut

    hello ravi i need to same example using sqlite database.
    how it posible…..

    • TabWidget are not deprecated. you should use Tablayout instead.

  • MrJawlon

    Great author for beginners. Respect!

  • chetan

    i want to change the second one is my default one Tab,so i did like this..
    tabHost.getTabWidget().setCurrentTab(1); ,
    but its not showing , it’s shoing same one what to do