Fundamentals
Introduction
1st Android Application

OOPS Concepts
Class
Object
Abstraction
Encapsulation

Polymorphism
Inheritance
Message Passing
Dynamic Binding

UI Controls
TextView
Button
Toggle Button
CheckBox
Radio Button
Spinner
ProgressBar
SeekBar
RadioGroup
RatingBar
Switch
EditText
AutoComplete
TextView

MultiAutoComplete
TextView

ImageView
ImageButton
Gallery
MediaPlayer
VideoView
MediaController

TimePicker
DatePicker
CalendarView
Chronometer
Analog Clock
Digital Clock

Layouts
LinearLayout
RelativeLayout
GridLayout
TableLayout
FrameLayout
Fragment

Composite
ListView
ExpandableListView
GridView
ScrollView
SearchView
Sliding Drawer
Tab Widget
WebView

Transitions
Image Switcher
StackView
TextSwitcher
ViewAnimator
View Flipper
View Switcher

Advanced
Request Focus
View
View Stub
TextureView
Gesture Overlay View

SurfaceView
NumberPicker
Zoom Button
Zoom Controls
AbsoluteLayout

Database
SharedPreference
SQLite DB
MySQL DB

Webservices
Check HttpURLConnection
Single Webservice Call
Multi Webservice Call
ListView from Webservice
SQLite from Webservice
Data from Database

Telephone Manager
IMEI
IMSI
Phone Type
Sim Type
Network Type

Content Providers
Contact Provider
BookMark Provider
Own Provider


Message & Networking
Send SMS
SMS with Reports
Group SMS

Send E-Mail
Download Binary Data


Location Based Service
Display Google Map
Events with Google Map

Android Services
Create Service
Create Longtime Service

Asynchronous Task
Repeating Services
IntentService

Activity from a Service
Bind Activity to Service


Sample Projects
HMS
CNB
Login Screen
Camera Event
Browse Option
QR Code Events
Accelerometer Sensor
EditText from Spinner

Multi Webservice Call

  1. Multi Webservice Call in Android
  2. Call Multi Webservice if Connection Available

Note                     Download ADT Plugin Here.
Here I am using,
OS : Linux (Ubuntu 12.04)
Eclipse : Juno (Version 4.2.0)
Android API Level : 3 to 'n' as per need
Emulator API Level : It will be displayed in output image

A. Multi Webservice Call in Android


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:textColor="#ff0000"
        android:textSize="18sp"
        android:text="Multi Webservice" />
 
    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:hint="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp" />
 
    <TextView
        android:id="@+id/textView2"
        android:hint="User ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.multi_webservice_ex1;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
 
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.app.Activity;
 
public class MainActivity extends Activity {	
	
	AutoCompleteTextView name;
	TextView id;
	List<String> list;
	InputStream is = null;
	
	String ip = "http://10.0.2.2/webservice/";
	String db_result = null;
	String line = null;
	String result = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		name = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
		id = (TextView) findViewById(R.id.textView2);
		
		ArrayList <NameValuePair> nm = new ArrayList<NameValuePair>();
		nm.add(new BasicNameValuePair("dummy", "dummy"));
		
		db_result = multi_webservice(ip + "select.php", nm);
		
		try {
			JSONArray ja = new JSONArray(db_result);
			JSONObject jo = null;
			
			list = new ArrayList<String>();
			
			for(int i=0; i<ja.length(); i++) {
				
				jo = ja.getJSONObject(i);
				list.add(jo.getString("uname"));
			}
		}
		catch(Exception e) {
			Log.e("WebService 3", e.toString());
		}
		
		ArrayAdapter<String> adp = new ArrayAdapter<String>
				(this, android.R.layout.simple_list_item_1, list);
		name.setAdapter(adp);
		name.setThreshold(1);
		
		name.setOnItemClickListener(new OnItemClickListener() {
 
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
								
				ArrayList <NameValuePair> nm = new ArrayList<NameValuePair>();
				nm.add(new BasicNameValuePair("uname", name.getText().toString()));
				
				db_result = multi_webservice(ip + "get.php", nm);
				
				try {
					JSONObject jo = new JSONObject(db_result);
					id.setText(jo.getString("id"));
				}
				catch(Exception e) {
					Log.e("WebService 6", e.toString());
				}
			}
		});
	}
 
	private String multi_webservice(String string, ArrayList<NameValuePair> nm) {
		// TODO Auto-generated method stub
		
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(string);
			httpPost.setEntity(new UrlEncodedFormEntity(nm));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch (Exception e) {
			Log.e("Webservice 1", e.toString());
		}
		try {
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			
			while((line = reader.readLine()) != null) {
				
				sb.append(line + "\n");
			}
			
			is.close();
			result = sb.toString();			
		}
		catch (Exception e) {
			Log.e("Webservice 2", e.toString());
		}
		
		return result;
	}
}

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.multi_webservice_ex1"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.multi_webservice_ex1.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>
    </application>
 
</manifest>

Step 5 : select.php

<?php
 
$host = '127.0.0.1';
$uname = 'root';
$pwd = 'password';
$db = 'Sample';
 
$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
 
$query = mysql_query("SELECT * FROM student", $con);
 
while($row = mysql_fetch_array($query)) {
 
	$flag[] = $row;
}
 
print(json_encode($flag));
mysql_close($con);
 
?>

Step 6 : get.php

<?php
 
$host = '127.0.0.1';
$uname = 'root';
$pwd = 'password';
$db = 'Sample';
 
$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
 
$uname = $_REQUEST['uname'];
 
$query = mysql_query("SELECT id FROM student where uname = '$uname'", $con);
 
while($row = mysql_fetch_array($query)) {
 
	$flag = $row;
}
 
print(json_encode($flag));
mysql_close($con);
 
?>

Step 7 : Our output will be like this :


Output


Output


Output









B. Call Multi Webservice if Connection Available


Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click "Finish" button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :

<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"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:textColor="#ff0000"
        android:textSize="18sp"
        android:text="Multi Webservice" />
 
    <AutoCompleteTextView
        android:id="@+id/autoCompleteTextView1"
        android:hint="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp" />
 
    <TextView
        android:id="@+id/textView2"
        android:hint="User ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
 
</RelativeLayout>

Step 3 : Open src -> package -> MainActivity.java and add following code :

package balaji.multi_webservice_ex2;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
 
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
 
public class MainActivity extends Activity {	
	
	AutoCompleteTextView name;
	TextView id;
	List<String> list;
	InputStream is = null;
	
	String ip = "http://10.0.2.2/webservice/";
	String db_result = null;
	String line = null;
	String result = null;
	boolean connection = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		name = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
		id = (TextView) findViewById(R.id.textView2);
		
		try {
			
			URL url = new URL(ip);
			executeReq(url);
			connection = true;
        }
        catch(Exception e) {
        	connection = false;
        }
		
		// If Connection is Available, Execute the below code.
		if(connection == true) {
			
			ArrayList <NameValuePair> nm = new ArrayList<NameValuePair>();
			nm.add(new BasicNameValuePair("dummy", "dummy"));
			
			db_result = multi_webservice(ip + "select.php", nm);
			
			try {
				JSONArray ja = new JSONArray(db_result);
				JSONObject jo = null;
				
				list = new ArrayList<String>();
				
				for(int i=0; i<ja.length(); i++) {
					
					jo = ja.getJSONObject(i);
					list.add(jo.getString("uname"));
				}
			}
			catch(Exception e) {
				Log.e("WebService 3", e.toString());
			}
			
			ArrayAdapter<String> adp = new ArrayAdapter<String>
					(this, android.R.layout.simple_list_item_1, list);
			name.setAdapter(adp);
			name.setThreshold(1);
			
			name.setOnItemClickListener(new OnItemClickListener() {
 
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					// TODO Auto-generated method stub
									
					ArrayList <NameValuePair> nm = new ArrayList<NameValuePair>();
					nm.add(new BasicNameValuePair("uname", name.getText().toString()));
					
					db_result = multi_webservice(ip + "get.php", nm);
					
					try {
						JSONObject jo = new JSONObject(db_result);
						id.setText(jo.getString("id"));
					}
					catch(Exception e) {
						Log.e("WebService 6", e.toString());
					}
				}
			});
		}
		else {
			Toast.makeText(getBaseContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
		}		
	}
 
	private void executeReq(URL url) throws IOException {
		// TODO Auto-generated method stub
		
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		con.setReadTimeout(3000);
		con.setConnectTimeout(3500);
		con.setRequestMethod("GET");
		con.setDoInput(true);
		
		// Connect
		con.connect();
	}
 
	private String multi_webservice(String string, ArrayList<NameValuePair> nm) {
		// TODO Auto-generated method stub
		
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(string);
			httpPost.setEntity(new UrlEncodedFormEntity(nm));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch (Exception e) {
			Log.e("Webservice 1", e.toString());
		}
		try {
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			
			while((line = reader.readLine()) != null) {
				
				sb.append(line + "\n");
			}
			
			is.close();
			result = sb.toString();			
		}
		catch (Exception e) {
			Log.e("Webservice 2", e.toString());
		}
		
		return result;
	}
}

Step 4 : Open AndroidManifest.xml and add following code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="balaji.multi_webservice_ex2"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="3"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="balaji.multi_webservice_ex2.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>
    </application>
 
</manifest>

Step 5 : select.php

<?php
 
$host = '127.0.0.1';
$uname = 'root';
$pwd = 'password';
$db = 'Sample';
 
$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
 
$query = mysql_query("SELECT * FROM student", $con);
 
while($row = mysql_fetch_array($query)) {
 
	$flag[] = $row;
}
 
print(json_encode($flag));
mysql_close($con);
 
?>

Step 6 : get.php

<?php
 
$host = '127.0.0.1';
$uname = 'root';
$pwd = 'password';
$db = 'Sample';
 
$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
 
$uname = $_REQUEST['uname'];
 
$query = mysql_query("SELECT id FROM student where uname = '$uname'", $con);
 
while($row = mysql_fetch_array($query)) {
 
	$flag = $row;
}
 
print(json_encode($flag));
mysql_close($con);
 
?>

Step 7 : Our output will be like this :


Output









SHARE THIS PAGE



product 2

product 3

product 4

Feedbacks : balaji.scz@gmail.com