Tuesday, October 25, 2011

Android Web Service Access Tutorial

In this post I'm going to illustrate how we can access web service in Android using ksoap2-android project that provides a lightweight and efficient SOAP library for the Android platform.

You can download the jar file from following link;

http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.8/ksoap2-android-assembly-2.5.8-jar-with-dependencies.jar

Here is the sample code that illustrate SOAP web service call. I have access a live web service ConvertWeight from http://www.webserviceX.NET/ which convert weight from one unit to another. I have set "envelope.dotNet = true;" in Line 53 since I'm accessing .NET web service. You can comment that line if your web service is not .NET one.

package com.sencide;
 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
 
public class AndroidWebService extends Activity {
  
    private final String NAMESPACE = "http://www.webserviceX.NET/";
    private final String URL = "http://www.webservicex.net/ConvertWeight.asmx";
    private final String SOAP_ACTION = "http://www.webserviceX.NET/ConvertWeight";
    private final String METHOD_NAME = "ConvertWeight";
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      
        String weight = "3700";
        String fromUnit = "Grams";
        String toUnit = "Kilograms";
      
        PropertyInfo weightProp =new PropertyInfo();
        weightProp.setName("Weight");
        weightProp.setValue(weight);
        weightProp.setType(double.class);
        request.addProperty(weightProp);
         
        PropertyInfo fromProp =new PropertyInfo();
        fromProp.setName("FromUnit");
        fromProp.setValue(fromUnit);
        fromProp.setType(String.class);
        request.addProperty(fromProp);
         
        PropertyInfo toProp =new PropertyInfo();
        toProp.setName("ToUnit");
        toProp.setValue(toUnit);
        toProp.setType(String.class);
        request.addProperty(toProp);
        
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
 
        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            Log.i("myApp", response.toString());
    
            TextView tv = new TextView(this);
            tv.setText(weight+" "+fromUnit+" equal "+response.toString()+ " "+toUnit);
            setContentView(tv);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

You have to add INTERNET permission to AndroidManifest.xml as follows;

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

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidWebService"
                  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-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

You can download the source code of above project (Password:sara).

I have updated my previous code in the post Android Login Screen Using HttpClient to authenticate users from web service. There I have illustrated how you can start new activity if the login is successful.

You can download the updated source code with sample .NET web service application (Password:sara).

Tuesday, June 21, 2011

Android Login Screen Using HttpClient

I have updated this code to use web service and open new screen if the login is successful in my post Android Web Service Access Tutorial.

In Android we can use HTTP POST request with org.apache.http.client.HttpClient to post data to a URL. This sample project illustrate how we can post data to a URL and get the response.


package com.sencide;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidLogin extends Activity implements OnClickListener {
 
 Button ok,back,exit;
 TextView result;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Login button clicked
        ok = (Button)findViewById(R.id.btn_login);
        ok.setOnClickListener(this);
        
        result = (TextView)findViewById(R.id.lbl_result);
        
    }
    
    public void postLoginData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        
        /* login.php returns true if username and password is equal to saranga */
        HttpPost httppost = new HttpPost("http://www.sencide.com/blog/login.php");

        try {
            // Add user name and password
         EditText uname = (EditText)findViewById(R.id.txt_username);
         String username = uname.getText().toString();

         EditText pword = (EditText)findViewById(R.id.txt_password);
         String password = pword.getText().toString();
         
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.w("SENCIDE", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);
            
            String str = inputStreamToString(response.getEntity().getContent()).toString();
            Log.w("SENCIDE", str);
            
            if(str.toString().equalsIgnoreCase("true"))
            {
             Log.w("SENCIDE", "TRUE");
             result.setText("Login successful");   
            }else
            {
             Log.w("SENCIDE", "FALSE");
             result.setText(str);             
            }

        } catch (ClientProtocolException e) {
         e.printStackTrace();
        } catch (IOException e) {
         e.printStackTrace();
        }
    } 
  
    private StringBuilder inputStreamToString(InputStream is) {
     String line = "";
     StringBuilder total = new StringBuilder();
     // Wrap a BufferedReader around the InputStream
     BufferedReader rd = new BufferedReader(new InputStreamReader(is));
     // Read response until the end
     try {
      while ((line = rd.readLine()) != null) { 
        total.append(line); 
      }
     } catch (IOException e) {
      e.printStackTrace();
     }
     // Return full string
     return total;
    }

    @Override
    public void onClick(View view) {
      if(view == ok){
        postLoginData();
      }
    }

}

Following code is the content of mail.xml file that is used in the above code.

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:id="@+id/txt_username" android:layout_y="132dip" android:layout_x="128dip"></EditText>
<EditText android:layout_width="150px" android:layout_height="wrap_content" android:textSize="18sp" android:password="true" android:id="@+id/txt_password" android:layout_x="128dip" android:layout_y="192dip"></EditText>
<Button android:layout_width="100px" android:layout_height="wrap_content" android:id="@+id/btn_login" android:layout_x="178dip" android:layout_y="252dip" android:text="Login"></Button>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_username" android:text="User Name" android:layout_x="37dip" android:layout_y="150dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_password" android:text="Password" android:layout_y="207dip" android:layout_x="50dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lbl_top" android:textSize="16sp" android:typeface="sans" android:text="Please Loggin First" android:layout_x="29dip" android:layout_y="94dip"></TextView>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_y="312dip" android:layout_x="50dip" android:id="@+id/lbl_result"></TextView>
</AbsoluteLayout>
Following code is the content of AndroidManifest.xml file that is used in this project. There note that I have add the line <uses-permission android:name= "android.permission.INTERNET".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.sencide"
      android:versionCode="1"
      android:versionName="1.0">

 <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidLogin"
                  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>

You can download the source code of above project (Password:sara).

Wednesday, June 8, 2011

SQL Server Authentication enabling using Microsoft SQL Server Management Studio

If you install the Microsoft SQL Server using Windows Authentication mode, the "sa" account is disabled by default. So if you plan to use SQL Server Authentication, you have to enable the "sa" account. This tutorial tells you how to enable the "sa" account.

1. First, Login to the SQL Server Management Studio using Windows Authentication. Right-click on the database instance, and go to Properties.

2. Then on Properties page, click on Security and select SQL Server and Windows Authentication mode, and click on OK to close the Server Properties page.

3. Now you will get dialog box saying that you should restart your SQL Server to take the changes take effect. Is is not done yet, you have to done one more thing to enable the "sa" login.

4. Now expand Security folder and go to Logins. You can see the "sa" account is disabled when you install SQL Server using Windows Authentication mode.

5. Then right-click on the "sa" account and go to Login Properties. There you can set a password for the "sa" account.


6. Click on the Status page. There you can see the "sa" account is disabled by default. Click on the Enabled button to enable it. Then click on Ok to close the "sa" Login Properties.

Now "sa" account is enabled and you can login to the SQL instance using the "sa" account after restarting the SQL Server.

Note: SQL Server service needs to be restarted to make this change effective.