Wednesday, 25 January 2012

Access webservice from Android device


I have seen many request on forum about web-service and android.Thought of sharing this sample tutorial with you about how to use web-services in android.Following this tutorial you can get an actual understanding about how to share data between mobile device and web-services.

Lets us take an example of login screen. Suppose user is sending request of login from mobile device to the server.Server will verify the request and will return response to the mobile device.Server can send response in either XML or through soap object.
This tutorial  will also explain about request – response model using xml.

Diagram:

Step 1. Create layout for login screen:
<?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"
  android:background="@drawable/background"> 
  <RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:gravity="left"
  android:layout_marginTop="10dip">
  <TextView
      android:text="@string/LoginHeading"
      android:id="@+id/HeadingTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"     
      android:textColor="@android:color/white"
      android:textStyle="bold"
      android:layout_marginLeft="13dip">
</TextView>
  </RelativeLayout>  
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="10dip"
  android:layout_marginTop="10dip"
  android:background="@android:color/white"/>
<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:orientation="horizontal"
  android:gravity="center"
  android:background="@android:color/white">
<TextView
      android:text="User ID "
      android:id="@+id/uNameTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center_vertical"
      android:textColor="#000000">
</TextView>
<EditText
      android:id="@+id/userIDEditText"
      android:layout_height="wrap_content"
      android:layout_width="220dip"
      android:inputType="text"
      android:hint="USERID"
      android:layout_marginLeft="20dip">
</EditText>
</LinearLayout>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="5dip" 
  android:background="@android:color/white"/>
<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:gravity="center"
  android:background="@android:color/white">
<TextView
      android:text="@string/uPass"
      android:id="@+id/uNPassTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center_vertical"
      android:textColor="#000000">
</TextView>
<EditText
      android:id="@+id/passEditText"
      android:layout_height="wrap_content"
      android:layout_width="220dip"
      android:inputType="textPassword"
      android:hint="PASSWORD"
      android:layout_marginLeft="15dip">
</EditText>
</LinearLayout>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="5dip"
  android:background="@android:color/white"/>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:layout_marginTop="25dip"
  android:gravity="center">
   <Button
   android:layout_width="150dip"
   android:layout_height="wrap_content"
   android:text="Login"
   android:id="@+id/loginButton">
   </Button>
   <Button
   android:layout_width="150dip"
   android:layout_height="wrap_content"
   android:text="Cancel"
   android:id="@+id/cancelButton"
   ></Button>
  </LinearLayout>
</LinearLayout>



Step 2. Create login Activity:-
Send login request to the server using login activity. Java code for activity likes,


public class LoginActivity extends Activity{
      /*
       * Global variables
       */
      Button btnLogin =null;
      Button btnCancel =null;
      EditText uNameEditext =null;
      EditText passEditext =null;
      String iemiNumber = null;
      Thread connectionThread = null;
      LoginData loginData =null;
      private Handler loginHandler = null;
      private ProgressDialog progressDialog = null;
      private AlertDialog alert = null;
      ArrayList<ResponseData> responseData = null;
      //public SharedPreferences timeStamp = null; 
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.loginscreen);
            uNameEditext =(EditText)findViewById(R.id.userIDEditText);
            passEditext =(EditText)findViewById(R.id.passEditText);
            //Handler for progress dialog
            loginHandler = new Handler() {
                  @Override
                  public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        super.handleMessage(msg);
                        if(progressDialog.isShowing()){
                              progressDialog.dismiss();
                        }
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LoginActivity.this);
                        alertDialogBuilder.setTitle("Login");
                        alertDialogBuilder.setMessage("The username or password you entered is incorrect");
                        alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    //after testing
                                    passEditext.setText("");
                              }
                        });
                        alert = alertDialogBuilder.create();
                        alert.setCancelable(false);
                        alert.show();
                  }
            };
            btnLogin=(Button)findViewById(R.id.loginButton);
            btnLogin.setOnClickListener(new OnClickListener() {
                  public void onClick(View v) {                       
                        doLogin();
                  }
            });   
            btnCancel =(Button)findViewById(R.id.cancelButton);
            btnCancel.setOnClickListener(new OnClickListener() {             
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                        finish();
                  }
            });
      }
      private void doLogin(){
         mUserName = userNameEditText.getText().toString();
         mUserPswd = userPswdEditText.getText().toString();     
         if(mUserName.length() < 10){            
             Toast.makeText(LoginActivity.this, "Please check Mobile Number you have entered", Toast.LENGTH_SHORT).show();
             return;
         }
         if(mUserPswd.length() < 1){            
             Toast.makeText(LoginActivity.this, "Password field can't be left blank!", Toast.LENGTH_SHORT).show();
             return;
         }
        try{           
            progressDialog = ProgressDialog.show(this, "Connecting!", "Please wait . . .", true, true);
        }catch (Exception e) {
                       // TODO: handle exception
        }       
        if(mUserName.length() >= 10 && mUserPswd.length() > 0){        
                connectcionThread = new Thread(){                   
                    public void run(){                       
                        URL url;                       
                        try {
                            //User name and password is added to the URL
URL(loginUrl+"?name="+mUserName+"&password="+mUserPswd+"&deviceId="+mDeviceId.trim());                           
                            //Trying to connect with the server.
                            loginURLConnection = url.openConnection();
                           //Connection will be timed out in 5 seconds.
                            loginURLConnection.setConnectTimeout(9000);
                            //Getting XML data as input stream from server.
                           inputStream = loginURLConnection.getInputStream();
                            parseLoginResponseXML (new InputStreamReader(inputStream));                           
                            if(isSuccess){                               
                                progressDialog.dismiss();
                                openCategoryList();
                           }else{
                     progressDialog.dismiss();
                                myHandler.sendEmptyMessage(1);
                            }
                           inputStream.close();
                            loginURLConnection = null;
                        } catch (Exception e) {
                            loginResponseMessage = "Huh! Network Error, Can't connect to server, Please try again!";
                            myHandler.sendEmptyMessage(1);
                        }
                    }
                };
                connectcionThread.start();
            //}
        }
    }
      void parseLoginResponseXML(InputStreamReader inputStreamReader) {
            // TODO Auto-generated method stub
            if(inputStreamReader !=null){
                  //Implement parser logic here
            }
      }
}

In login activity ,I am adding entered username and password to the base login url.I have use URLConnection class to send request to server.We will get response in form of InputStream object.The response can be simple xml file.We can parse response xml file.If response is true then allow user to login into application.

Step 3.create manifest file:-
As we are using internet ,we need to mention internet permission in manifest file like,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.webservice"
      android:versionCode="2"
      android:versionName="2.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LoginActivity"
                  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>
    <uses-sdk android:minSdkVersion="3" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Here I have tried to explain how to consume webservice in android.Hope it is helpful.
Happy androing!!!!!


4 comments:

mr.haps said...

Thanks for uploading a new blog, but this stuff showed a lot of errors.

I went through a sample at:
http://sarangasl.blogspot.com/2011/10/android-web-service-access-tutorial.html

By changing this sample to my needs I got the "Login Successful" Response.

Now I want that after the successful login the next Activity that has to be an Application Form, should come from the .NET server in the form of XML file as Android support only XML Files as Layouts.

Can you help with that.

Thanks,
Harpreet.

AndroIndu said...

Harpreet,
firstly above code won't work as it is for your case.This is working for my web service.

secondly,as you said you will get xml as response from server.you can parse the response xml and develop layout.

mr.haps said...

HI.
How should I do that stuff of xml?

Actually I have successfully Login and after that I sent the ServiceId as INT and get the response as STRING from soap service, but now the string contains the html code of the online form.

I used WebView to Load String Data in it and it showed the form successfully but it is just a static form, Form's functionality is not working.

Any Idea? I should do something in this HTML stuff or go for XML stuff?

AndroIndu said...

check out how to use javascript in webview.
You can write javascript for your html component.