Saturday, December 8, 2012

Create java web service in Eclipse using Axis2 (Part 03)

This is the third part of create java web service using Axis2 tutorial. In this post I'm going to create a simple client program for the web service developed in previous tutorial. Before creating this program you have to complete my previous tutorials.

1. Create java web service in Eclipse using Axis2 (Part 01)
2. Create java web service in Eclipse using Axis2 (Part 02)

Before implementing the client first we have to find the wsdl file.
First run the created project on Tomcat server. To do this right click on project select Run As then select Run on Server.


Click on Services

Select Hello which is your web service class name. Under Available Operations you can see your web service operation.

 After clicking on Hello you can see the  WSDL file. Copy WSDL link to the clip board.



OK. We coppied the WSDL link.

Now we have to create the web service client.
Right click the web service class select New >> Other >> Web Services >> Web service Client. 



Click Next. Paste link of the wsdl file to the Service definition box. (If you want to access the wsdl in another computer via a net work replace "localhost" in the WSDL url with the ip address of the server machine)
Make sure that the Server runtime is Tomcat & the Web service runtime is Axis2 by clicking the links underlined red color in the following diagram.

Client type : Java Proxy




 


Click finish to generate Callback Handler & the Stub in same package where the web service class exists.(If you want to change the client package click next & give a package name to Custom package name as you wish)

Then create new class. Class name that I used is Client. Here is the project structure.



Following code shows how we can invoke the web service method using auto generated Stub. Paste this code to newly created class. This client class also in the same package with  web service class. 

 
package org.webapp.ws;
import org.webapp.ws.HelloStub.SayHello;

public class Client {
 public static void main(String[] args) throws Exception {
     HelloStub stub = new HelloStub();
    
     //Creating the request
     org.webapp.ws.HelloStub.SayHello  request = new  org.webapp.ws.HelloStub.SayHello();
     request.setName("Java web");
   
     //Invoking the service
     org.webapp.ws.HelloStub.SayHelloResponse response  = stub.sayHello(request);
     System.out.println("Response : " + response.get_return());
    }
}


Right click Client class and run the client as a java application.



Result :


Click here to download the complete project with client.

If you find this post helpful don't forget to leave a comment. Your comments always encourage me to write more!

Happy coding!

Create java web service in Eclipse using Axis2 (Part 02)

This is the second part of create java web service using Axis2 tutorial. In this post I'm going to demonstrate the configuration of Apache Axis2 in Eclipse and create a simple java web service using Apache Axis2 SOAP engine. (If you want to see the first part click here.)

1. First you need to download and extract Apache Axis2 SOAP engine.

 Apache Axis2 Binary Distribution - DOWNLOAD

2. Configure Axis2

In Eclipse go to Window >> Preferences >> Web Services >> Axis2 Preferences




 Then Browse to axis2 extracted location. If you configure correctly Eclipse will show this message "Axis2 runtime loaded successfully" then click on Apply button.


To set server & runtime in the same Preferences window click on Server & Runtime.



 Then select Tomcat 7 as Server runtime & Axis2 as Web service runtime.



To complete configurations finally click Apply and OK.

3. Creating the Dynamic web project
After completing those configurations we can directly jump in to the web service development part. Here I'm going to implement very simple project. You can change it as you want.

In Eclipse EE create new Dynamic web project. Give project name



- You have to select Tomcat 7 as Target runtime.
- Select 2.5 in Dynamic web module version drop down menu.
- Then click Modify... button appears just after the Configuration.
- I gave the "WebApp" as project name.


- Select Axis2 web services in opening window.


Click Finish to create the Dynamic web project.

Right click on src folder then New >> Class


- Give class name as well as package name
- I gave package name as "org.webapp.ws" and class name as "Hello"


- Then click finish to crate the class.

Add following code to the class


public class Hello {
 public String sayHello(String name) {
    return "Hello !!! " + name;
 }
}

4. Creating the web service

Right click on your service class (not the project).
Select Web Services >> Create Web Service



In Web Service window tick to the Monitor the Web service check box. Other default settings are OK. No need to change those to this web service.


Click Next.
Next window, select Generate a default services.xml file.



Then click Next and finally click Finish.

4. Testing the project
Perfect...... Now you should have a web service. To set the service Right click on your project and select Run As >> Run on Server.


Click next & click Finish.

If everything went fine you should see following page in Eclipse internal web browser.


Click here to download the project.
In my next post I hope to demonstrate the implementation of the client program.

If you find this post helpful don't forget to leave a comment. Your comments always encourage me to write more!

Thank you for watching.
Happy coding!

Create java web service in Eclipse using Axis2 (Part 01)

This series of tutorials will explain how to create a simple java web service in Eclipse using Axis2. Finally I hope to create a client program for the web service.
This is the part 01.
Here I'm going to explain how we can configure Tomcat 7 for Eclipse 4.2 (Juno) because before create a java web service we need to setup development environment and configure the server. Here I use Tomcat 7 server for this tutorial.

1. Setup the development environment.
To setup the development environment you need to download and extract Eclipse EE and Tomcat servlet container.
1. Eclipse IDE for Java EE Developers - Download
2. Apache  Tomcat (Download zip archive not the windows service installer) - Download.

2. Here is the steps to configure Tomcat 7 in eclipse
2.1 Double click to open Eclipse. You should be able to see the Servers tab.


If you can't see the Servers tab then ;

 Window >> Show View and select Servers


2.2 Right click on Servers tab
Select ; New >> Server


 

Then from the new server window select ; Apache >> Tomcat v7.0 Server and click next 



In next window browse to extracted Tomcat files, that is Tomcat installation directory and select the jre that installed in your system and click finish to create the new server.



2.3 To start the server right click on Tomcatv7 server in Servers tab and select Start.



2.4 To check the server open Chrome and go to localhost:8080 you should be able to see Tomcat start page.


If you are getting "requested resource is not available" error you need to change the file location of the Tomcat.

 
In order to do that right click on server in the Servers tab and select properties. Then from the server properties window click Switch Location and Apply , OK.



Next double click on the server to open Overview.



 In the Overview window  change Server locations to Use Tomcat installation and save changes. (If you want you can change ports from the Overview window).


Restart the server and check. Now you should be able to see the default start page.



To open Eclipse Internal web browser select ;
Window >> Show View >> Other >> General >> Internal web Browser 


 

PART 02 (Configuration of Axis2 and creating simple web service)

Thanks!
Post your ideas.
 

Tuesday, November 27, 2012

MySQL FULL JOIN

Here is a quick example on FULL JOIN in MySQL database.
FULL JOIN concept in MySQL is to return rows when there is a match in one of the tables. Further FULL JOIN or FULL OUTER JOIN is UNION of LEFT JOIN and the RIGHT JOIN of the both tables.
Consider that you have following two tables.

Table 1 : Persons

Eg : queries to create and populate the Persons table.

CREATE TABLE Persons
 (P_Id int, Name varchar(1));
 
INSERT INTO Persons
 (P_Id, Name)
VALUES
 (1, 'A'),
 (2, 'B'),
 (3, 'C'),
 (4, 'D'),
 (5, 'E');


Table 2 : Invoice


Eg : queries to create and populate Invoice table.

CREATE TABLE Invoice
 (Id int, P_Id int);
 
INSERT INTO Invoice
 (Id, P_Id)
VALUES
 (111, 3),
 (112, 3),
 (113, 1),
 (114, 1),
 (115, 15);

Now think that we want to join rows of both these tables on the condition of same P_Id. To perform that we need to get the UNION of RIGHT JOIN and the LEFT JOIN of both tables.
Here is the query to FULL JOIN operation.

SELECT Persons.Name, Persons.P_Id, Invoice.Id
FROM Persons
LEFT JOIN Invoice
  ON Persons.P_Id=Invoice.P_Id
UNION
SELECT Persons.Name, Persons.P_Id, Invoice.Id
FROM Persons
RIGHT JOIN Invoice
  ON Persons.P_Id=Invoice.P_Id


Resulting table :


I think that you can understand what happened here.

1. First result of LEFT OUTER JOIN of both tables.


2. Then result of RIGHT OUTER JOIN of both tables.


3. UNION of these two tables means rows when there is a match in one of the tables or FULL JOIN of these two tables.


If you understand the concept try to use following query to FULL JOIN these tables. Same concept and same result.

SELECT Persons.Name, Persons.P_Id, Invoice.Id
FROM Persons
LEFT JOIN Invoice
  ON Persons.P_Id=Invoice.P_Id
UNION
SELECT Persons.Name, Persons.P_Id, Invoice.Id
FROM Invoice
LEFT JOIN Persons
  ON Persons.P_Id=Invoice.P_Id

Thank you for watching. Always your ideas are welcome.
Happy coding!

Saturday, November 17, 2012

Make Android Edit text field allows only for selected characters

There is a simple method to make a restrict or a limit on allowed characters in Android edit text field.
Eg: Suppose that you want to make a restrict where user only allows to type  a,e,i,o,u. You can easily do this by using following line in your layout.xml file
android:digits="aeiou"

Eg: (I used edit text in relative layout)
     <EditText
         android:id="@+id/editText1"
         android:digits="aeiou"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:layout_marginLeft="54dp"
         android:layout_marginTop="123dp" >
         <requestFocus />
     </EditText>

Monday, November 12, 2012

How to enable internal web browser in Eclipse Juno on Ubuntu

Some times Eclipse default internal web browser will not work in your Ubuntu environment. Is that the case, you need to install webkit library for Ubuntu.
In order to install webkit libraries got to your terminal and run this command.

sudo apt-get install libwebkitgtk-1.0-0

This may take a while. After finishing the installation you should be able to open Eclipse internal web browser.

Window >> Show View >> Other >> General >> Internal Web Browser.

Enjoy :D

Thursday, November 1, 2012

Android PHP JSON tutorial

Here I'm going to demonstrate how we can decode JSON encoded data in Android using very simple example. I used Android 2.2 for this.

First here is some extra information about JSON:

1. What is JSON

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is language independent 
  • JSON is "self-describing" and easy to understand
                                                           (from w3schools)  
2. Click here to know benefits of JSON over XML

Now let's see simple example of JSON reading in Android.
In my project there is a PHP web service which encodes a string array in to JSON format. I'm going to access that web service using Android http client and then it decodes json data. I have tested this on Android 2.2

1. Here is the code for PHP

<?php
$data = array('name' => 'Froyo', 'version' => 'Android 2.2'); 
print (json_encode($data)); 
?> 

2. Contents of Android Layout Manifest and Activity files
 main.xml file
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="216dp"
        android:layout_height="36dp"
        android:layout_weight="1"
        android:layout_x="66dp"
        android:layout_y="192dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</AbsoluteLayout>

manifest.xml 
You need to add internet permissions 
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.json.php"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".JSONExampleActivity"
            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>

Android activity 

package com.json.php;

import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONExampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://codeincloud.tk/json_android_example.php");
        TextView textView = (TextView)findViewById(R.id.textView1);
  try {
   
   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONObject object = new JSONObject(jsonResult);

   String name = object.getString("name");
      String verion = object.getString("version");
      textView.setText(name + " - " + verion);
      
  } 
  catch (JSONException e) {
   e.printStackTrace();
  } 
  catch (ClientProtocolException e) {
   e.printStackTrace();
  } 
  catch (IOException e) {
   e.printStackTrace();
  }


       }
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
         
        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        }
         
        catch (IOException e) {
            e.printStackTrace();
         }
        return answer;
       }
}

 Result

Click here to download the Android project.

That's it
 Happy coding! :)

Friday, August 10, 2012

Load image from URL to Android

Once I needed to display an image loading from URL in my Android application. After referring some resources I was success. Here I post what I did. This is for future references. I did this for Android 2.2 platform.

This Android application load an image from a server using HttpURLConnection and show it in image view when you click load image button.
(I have used  image located here http://www.codeincloud.tk/play.png)

Download this project


Here is the layout file.

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn_imgload"
        android:layout_width="208dp"
        android:layout_height="wrap_content"
        android:layout_x="57dp"
        android:layout_y="322dp"
        android:text="Load Image" />

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_x="131dp"
        android:layout_y="179dp" />

</AbsoluteLayout>

This is the java code

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class LoadImageActivity extends Activity {
 
 ImageView image_view;
 Button btnLoadImg ;
    final static String imageLocation="http://www.codeincloud.tk/play.png"; //Use any image location. 
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        image_view = (ImageView)findViewById(R.id.imageview);
        btnLoadImg = (Button)findViewById(R.id.btn_imgload);
        
        btnLoadImg.setOnClickListener(loadImage);
    }
    
    
    View.OnClickListener loadImage = new View.OnClickListener(){
     public void onClick(View view) {
         loadImage(imageLocation);
            }
     };
    
     Bitmap bitmap;
    void loadImage(String image_location){
      
          URL imageURL = null;
          
          try {
           imageURL = new URL(image_location);
           } 
          
          catch (MalformedURLException e) {
              e.printStackTrace();
           }
          
          try {
           HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
           connection.setDoInput(true);
           connection.connect();
              InputStream inputStream = connection.getInputStream();
               
              bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
              image_view.setImageBitmap(bitmap);
          }
          catch (IOException e) {
              
               e.printStackTrace();
          }
    }
  }

Add internet permission to Manifest file

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

Monday, July 16, 2012

Android Login activity with MySQL database connection

Here I'm going to create a simple Android log in application  which can post data to a java web service and read data from MySQL database using a java web service to authenticate the user. Tested on Android 2.2.
(In latest versions of Android you cannot access the web in same way mentioned here. if you are planning implement web access for version 3.0 or higher than that follow one of below methods
1.Async Task
 http://codeoncloud.blogspot.com/2013/07/android-web-service-access-using-async.html
2.Handlers
http://codeoncloud.blogspot.com/2013/06/android-java-soap-web-service-access.html )

Quick demo :



The complete project has three main components

1. A MySQL database which holds user name and password.
2. A java web service deployed on Tomcat server.
3.Android application to access the database through the java web service to verify the user.

1. Databse
First we have to create a database and table to store user information. To create the database I used MySQL command line client. (If you like you can use phpmyadmin it is easier)
In order to create the database, a table and to populate the database run following queries.
a. Create the database
CREATE DATABSE androidlogin;
b. Select the database
USE androidlogin;
c. Create a table
CREATE TABLE user(
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL);
d.Populate the database
INSERT INTO user(username,password)
VALUES('admin','123');

2. Java webservice
Create the java web service in Eclipse. Follow the steps mentioned here. Additionally you have to import JDBC connector to the web service project.  
Here is the content for java web service.
package com.userlogin.ws;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Login {
 public String authentication(String userName,String password){
  
  String retrievedUserName = "";
  String retrievedPassword = "";
  String status = "";
  try{
   
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","chathura");
   PreparedStatement statement =  con.prepareStatement("SELECT * FROM user WHERE username = '"+userName+"'");
   ResultSet result = statement.executeQuery();
   
   while(result.next()){
    retrievedUserName = result.getString("username");
    retrievedPassword = result.getString("password");
    }
   
   if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password)){
    status = "Success!";
   }
   
   else{
    status = "Login fail!!!";
   }
   
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return status;
 
 }

}

> For more details read my first post.
> "root" and "chathura" in line 17 are user and the password of the database. You need to change those according to your settings.

3. Android application.
a. Code for main activity
package com.androidlogin.ws;

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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidLoginExampleActivity extends Activity {
 private final String NAMESPACE = "http://ws.userlogin.com";
    private final String URL = "http://111.223.128.10:8085/AndroidLogin/services/Login?wsdl";
    private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
    private final String METHOD_NAME = "authentication";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button login = (Button) findViewById(R.id.btn_login);
        login.setOnClickListener(new View.OnClickListener() {
   
   public void onClick(View arg0) {
    loginAction();
    
   }
  });
    }
    
    private void loginAction(){
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
     
        EditText userName = (EditText) findViewById(R.id.tf_userName);
        String user_Name = userName.getText().toString();
        EditText userPassword = (EditText) findViewById(R.id.tf_password);
        String user_Password = userPassword.getText().toString();
        
      //Pass value for userName variable of the web service
        PropertyInfo unameProp =new PropertyInfo();
        unameProp.setName("userName");//Define the variable name in the web service method
        unameProp.setValue(user_Name);//set value for userName variable
        unameProp.setType(String.class);//Define the type of the variable
        request.addProperty(unameProp);//Pass properties to the variable
       
      //Pass value for Password variable of the web service
        PropertyInfo passwordProp =new PropertyInfo();
        passwordProp.setName("password");
        passwordProp.setValue(user_Password);
        passwordProp.setType(String.class);
        request.addProperty(passwordProp);
          
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        
        try{
            androidHttpTransport.call(SOAP_ACTION, envelope);
               SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
                
               TextView result = (TextView) findViewById(R.id.tv_status);
               result.setText(response.toString());
          
        }
        catch(Exception e){
          
        }
       }
    
}

> You need to import ksoap2 library for the Android project.
> You cannot access the URL in above code because the web service is deployed in Tomcat server installed in my computer not in a cloud server therefore you have to replace that with an URL for your own web service. 
>  For more details check these posts.
 1. Post 1
 2. Post 2

b. Content of main.xml


    

        
    

    



    

    


    

c. You need to add internet permission to the project
Manifest.xml


    
    

    
        
            
                

                
            
        
    



You can download Android project here
(After downloading the project first remove imported ksoap2 library from the project and re import ksoap2 from your hard disk )

Please post your ideas :)

Thursday, July 12, 2012

Android MySQL Client (Part 2)

Insert data to a database.

My first tutorial Android MySQL client is about read data from a MySQL database. Here I'm going to insert data to MySQL database using an Android program. Concept is same as before (Before start test this read first tutorial.)

Program has three main parts.
1. Database (MySQL)
2. Java web service.
3. Android application.

Java web service deployed on Tomcat server has a method which accepts two values and it runs a quarry on database to insert data & also this method returns a string.
The Android application calls that web service method remotely with two values using ksoap library. Then web service runs a query on database table and inserts data




1. First create the database and table.

CREATE DATABASE login;

USE login;

CREATE TABLE users(
name varchar(20),
password  varchar(20)
);

2. Then create the web service
Here is the content of my web service
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Users {
 
 public String insertData(String userName,String userPassword){
  
  try{
   
   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","chathura");
   PreparedStatement statement =  con.prepareStatement("INSERT INTO users(name,password) VALUES ('"+userName+"','"+userPassword+"');");
   int result = statement.executeUpdate();
  }
  
   catch(Exception exc){
    System.out.println(exc.getMessage());
    }

  return "Insertion successfull!!";
  }

}
In line 12 root and chathura are user and the password. Change those with your username and the password.
This java web service has JDBC connector to access the database. Click here to download the connector.Import JDBC connector to your project. This tutorial is about importing the ksaop library. In the same way you can import JDBC library also. It is simple
You can implement the web service easily by following my these posts.
1. Create java web service in Eclipse using Axis2 (Part 01) 
2. Create java web service in Eclipse using Axis2 (Part 02) 

3. Android application.

The Android application uses ksoap2 library to access java web service. You can find More details about implementation of Android client applications from here. If you are planning to use new Android version read this tutorial.

Here is the code for Android application.
You need to change name space, url, soap action and method name according to your web service.

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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidMySQLClientActivity extends Activity{
    private final String NAMESPACE = "http://ws.login.com";
    private final String URL = "http://175.157.3.42:8085/InsertToUsers/services/Users?wsdl";
    private final String SOAP_ACTION = "http://ws.login.com/insertData";
    private final String METHOD_NAME = "insertData";
    Button btninsert;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btninsert = (Button)findViewById(R.id.btn_insert);
        btninsert.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
             insertValues();
            }
        });
    }
    
    public void insertValues(){
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
     EditText userName = (EditText) findViewById(R.id.editText1);
     String user_Name = userName.getText().toString();
     EditText userPassword = (EditText) findViewById(R.id.editText2);
     String user_Password = userPassword.getText().toString();
     
     //Pass value for userName variable of the web service
        PropertyInfo unameProp =new PropertyInfo();
        unameProp.setName("userName");//Define the variable name in the web service method
        unameProp.setValue(user_Name);//Define value for fname variable
        unameProp.setType(String.class);//Define the type of the variable
        request.addProperty(unameProp);//Pass properties to the variable
      
      //Pass value for userPassword variable of the web service
        PropertyInfo passwordProp =new PropertyInfo();
        passwordProp.setName("userPassword");
        passwordProp.setValue(user_Password);
        passwordProp.setType(String.class);
        request.addProperty(passwordProp);
         
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
     
        try{
         androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            
            TextView result = (TextView) findViewById(R.id.textView2);
            result.setText(response.toString());
      
     }
     catch(Exception e){
      
     }
    }

}

4.Code for main.xml file


    

    

    

        
    

    


    

5. Content of the Manifest.xml (Add internet permission)

    
    
    
        
            
                
                
            
        
    


Note : Click here to download the Android project.
Do you think this is helpful ? Please write your ideas :)

Wednesday, July 11, 2012

Android Httpclient

In this tutorial I'm going to build a simple BMI calculator to show how we can post data to a URL using HTTP POST.

Here is the sample php code that you can use
<?php
       $userWeight = $_POST['weight'];
       $userHeight = $_POST['height'];
       $powerOfHeight = pow($userHeight,2);
       echo($userWeight/$powerOfHeight);
?>

Android activity
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.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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class AndroidWebActivity extends Activity implements OnClickListener {
 Button calculate;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        calculate = (Button)findViewById(R.id.button1);
        calculate.setOnClickListener((OnClickListener) this);
    }
   
    public void bmi(){
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://codeincloud.tk/bmi.php");
     
        try{
     EditText weight = (EditText) findViewById(R.id.editText1);
     String myWeight = weight.getText().toString();
     
     EditText height = (EditText) findViewById(R.id.EditText01);
     String myHeight = height.getText().toString();
     
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
         nameValuePairs.add(new BasicNameValuePair("weight", myWeight));
         nameValuePairs.add(new BasicNameValuePair("height", myHeight));
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         HttpResponse response = httpclient.execute(httppost);
         
         String bmiResult = inputStreamToString(response.getEntity().getContent()).toString();
         TextView result = (TextView) findViewById(R.id.textView4);
         result.setText("Your BMI : "+bmiResult);
     }
     
        catch(Exception e){
      e.printStackTrace();
     }
    }
    
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        
        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        } 
        
        catch (IOException e) {
            e.printStackTrace();
         }
        return answer;
       }
    
    public void onClick(View view) {
        if(view == calculate){
         bmi();
        }
      }
}

Here is the code of main.xml used in above application

    
    
   
    
       
    
    
    
   
    

Add internet permission to the Manifest file


    
    

    
        
            
                

                
            
        
    


Click here download the Android project.

Monday, July 9, 2012

Android php web service client

In this post I'm going to show you how we can access a very simple php web service from an Android application.
You can host your web service on wamp server installed in your machine or you can simply use a cloud server like 000webhost.

1. To keep things simple I'm going to use a dummy php code as follows
    <?php
        echo "Hello world!!!!"
  ?>
Create this php file and copy it in to www directory of wamp server or upload it in to a cloud server.

2. Here is the code for Android activity
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class AndroidWebActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
        try {
           HttpResponse response = httpclient.execute(httppost);
           final String str =  EntityUtils.toString(response.getEntity());
           TextView tv = (TextView) findViewById(R.id.textView1);
           tv.setText(str);
        } 
       catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
    }
}

Note : If you are using wamp server don't use local host for the url in line 18, use 10.0.2.2.
           Eg: http://10.0.2.2/android_connect/first.php
Don't forget to add internet permission.
Output of the program :

Saturday, June 30, 2012

Send sms from Android application

This tutorial demonstrate how we can implement a simple Android application which can send SMS. To check this application I used two emulators. If you are planning to  use emulator to check this you need to create two emulators first. I have tested this using Android 2.2 two emulators.


1. First create two emulators
    One should be emulator-5554 and the other one should be emulator-5556

2. Here is the Activity code for send SMS using intent.

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
public class TestSMSActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String number = "5556";
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", number, null)));
    }
}

The variable "number" in line 11 is the the recipient of the SMS activity. I'm going test this application using two emulators therefore I used one emulator number for that variable. If you are going to send SMS to mobile phone replace number with mobile phone number, but remember that sending SMS from emulator to a cell phone is difficult.

Don't forget to add send SMS permission to your Manifest file.


3. Run the project.
Android device chooser window will appear. Choose an AVD. If you assigned 5556 to number variable then choose emulator-5554 to run program, other vice select emulator-5554.



Then compose message window will open. Type a simple text (Eg:-"Hello world!") there and click on send.

emulator-5554


You can see received SMS on the other emulator

emulator-5556