Wednesday, April 16, 2014

How To Call Java Web Service From Android Using KSOAP2

Calling Java Web Service With Parameters From Android

 

package com.mnbd.movieticket;
public class common

 {
    public static String pName = "com.mnbd.movieticket";
    public static String CardNo = "EC400044";
    public static String UserID = "gs001";
    public static String Password = "1234";

}



package com.mnbd.movieticket;
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;


public class WebService {


    //Namespace of the Webservice - can be found in WSDL
     private static String NAMESPACE = "http://ws.apache.org/axis2";
        //Webservice URL - WSDL File location  
        private static String URL = "http://27.147.140.234:8082/axis2/services/CineplexService?wsdl";
   
        //SOAP Action URI again Namespace + Web method name
        private static String SOAP_ACTION = "http://ws.apache.org/axis2";
    
    public static String invokeWS(String json, String webMethName) {
        String resTxt = null;
        // Create request
        SoapObject request = new SoapObject(NAMESPACE, webMethName);
        // Property which holds input parameters
        PropertyInfo sayHelloPI = new PropertyInfo();
        // Set Name
       
        sayHelloPI.setName("args0");
        // Set Value
        sayHelloPI.setValue(json);
        // Set dataType
        sayHelloPI.setType(String.class);
        // Add the property to request object
        request.addProperty(sayHelloPI);
        // Create envelope
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        // Set output SOAP object
        envelope.setOutputSoapObject(request);
        // Create HTTP call object
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            // Invoke web service
            androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
            // Get the response
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
            // Assign it to resTxt variable static variable
            resTxt = response.toString();

        } catch (Exception e) {
            //Print error
            e.printStackTrace();
            //Assign error message to resTxt
            resTxt = "Error";
        }
        //Return resTxt to calling object
        return resTxt;
    }
}




package com.mnbd.movieticket;
import java.util.StringTokenizer;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.Activity;


public class JavaWebserviceCallByAndroid extends Activity {
    private TextView txtBalance ;
    ProgressBar pg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_java_webservice_call_by_android);
       
txtBalance = (TextView) findViewById(R.id.txtBal);
       
pg= (ProgressBar) findViewById(R.id.progressBar1);

        SetBalance();
    }
   
    private void SetBalance() {
        String reponse = "";
        AsyncCallWS task = new AsyncCallWS();
        task.execute();

    }
   
   
    private class AsyncCallWS extends AsyncTask<String, Void, Void> {
     

    @Override
         protected void onPreExecute() {
            pg.setVisibility(View.VISIBLE);
        }

       

    @Override
         protected void onProgressUpdate(Void... values) {
                   //  super.onProgressUpdate(values);
        }

       

    @Override
         protected void onPostExecute(Void result) {
                      if (returnstring.equalsIgnoreCase("Error"))
                txtBalance.setText("Couldn't establish connection");

            if (code.equalsIgnoreCase("100"))
                txtBalance.setText("Balance Amount:" + Bal);
            else if (code.equalsIgnoreCase("101"))
                txtBalance.setText("Not Found");
            else if (code.equalsIgnoreCase("102"))
               
txtBalance.setText("Authentication Failed");
            else if (code.equalsIgnoreCase("109"))
               
txtBalance.setText("Network Adapter couldn't establish connection");

            pg.setVisibility(View.INVISIBLE);
        }

        private String MethodName, jsonstring, returnstring;
        String Bal =
"";
        String code = "";

       

    @Override
         protected Void doInBackground(String... arg0) {
            // Invoke webservice

                        try {
                            jsonstring = "{'cardnumber':'" + Common.CardNo
                                    + "','username':'" + Common.UserID + "', 'password':'"
                                    + Common.Password + "', 'other':'1'}";
                           
                            returnstring = WebService.invokeWS(jsonstring, "Get_Balance");
                           
                            JSONArray jsa;

                            if (!returnstring.equalsIgnoreCase("Error")) {
                                JSONObject object = (JSONObject) new JSONTokener(
                                        returnstring).nextValue();
                                // Response Data
                                String query = object.getString("responseData");
                                StringTokenizer tokens = new StringTokenizer(query, ":");
                                String first_string = tokens.nextToken();
                                String second_string = tokens.nextToken();
                                tokens = new StringTokenizer(second_string, "\"");
                                Bal = tokens.nextToken();

                                // Response Code
                                String queryCode = object.getString("responseCode");
                                StringTokenizer tokensCode = new StringTokenizer(query,
                                        "\"");
                                code = tokensCode.nextToken();

                                // JSONArray locations = object.getJSONArray("query");
                                txtBalance.setText("Balance Amount:" + Bal);
                            }
                        } catch (Exception e) {
                                                       e.printStackTrace();
                        }

                        return null;
        }
       
    }

   
}
 


Monday, March 24, 2014

How To Disable The Button Click When The EditText is Empty in Android App

Disabling The Send Button When The EditText is Empty 

 

        buttonSend.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                if (!(editTextUserName.getText().toString().equalsIgnoreCase(""))) {

                   
                    Intent intent = new Intent(); 

                  //Package Name(com.cineplexbd.movieticket)

                   intent .setClassName("com.cineplexbd.movieticket",             
                      "com.cineplexbd.movieticket.NextActivity");  
                    context.startActivity(
intent )    

                } 


              else {
                    Toast.makeText(getApplicationContext(),
                            "Please Enter The User Name.)", Toast.LENGTH_LONG)
                            .show();
                   
                   
                     }

           
            }

        });

Wednesday, March 19, 2014

How to call a simple .net webservice using Android App.

To call an WebService using android 

package com.cineplexbd.movieticket;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MnWebService extends Activity {
     TextView result;
     final String SOAP_ACTION = "http://tempuri.org/HelloWorld";
     final String METHOD_NAME = "HelloWorld";
     final String NAMESPACE = "http://tempuri.org/";
     final String URL = "http://192.168.10.13/WebService/TestWebService.asmx";
//Or //use any 1 String URL
//final String URL = "http://mmm.com/SampleService.svc?wsdl";

     Object response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mn_web_service);
         result = new TextView(this);

         setContentView(result);
         new backMethod().execute();
    }
    public class backMethod extends AsyncTask<String, Object, Object > {

       
         private final ProgressDialog dialog = new ProgressDialog(MnWebService.this);   
                                    
                                        @Override
                                        protected void onPreExecute() {
                                    
                                                        this.dialog.setMessage("Checking...");             
                                                         this.dialog.show(); 
                                        }

                                        @Override
                                        protected void onCancelled(Object result) {
                                                    
                                                        super.onCancelled(result);
                                        }

                                        @Override
                                        protected void onPostExecute(Object result) {
                                       //Here All your UI part is Done
                                    
                             if (result != null) {
                                                                        String myOutput=result.toString();
                                                                        MnWebService.this.result.setText(myOutput);
                                                                        setContentView(MnWebService.this.result);
                                                    
                                                        }

                                                   else {
                                                                      
                                                             Toast.makeText(getApplicationContext(),
                                                           
                         "Result Found is ==  " + result + "", Toast.LENGTH_LONG) .show();
                                                                                                      
                                                        }
                                                        super.onPostExecute(result);
                                                        if (this.dialog.isShowing()) {

                                                                        this.dialog.dismiss();
                                                        }
                                                        super.onPostExecute(result);
                                        }

                                    
                                        @Override
                                        protected Object doInBackground(String... params) {
                                                                                    
                                        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                                       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                                                                                        SoapEnvelope.VER11);
                                                        envelope.dotNet = true;
                                                        envelope.setOutputSoapObject(request);
                                                        try {

                                                                      
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);androidHttpTransport.call(SOAP_ACTION, envelope);
  response = (SoapPrimitive) envelope.getResponse();  //here SoapPrimitive is an important part 
                         
                                                                                           
                                                        }

                          catch (Exception e) {
                                                                        e.printStackTrace();
                                                           }
                                                        return response;
                                        }
                        }
   
}


To  Download Ksoap2, Click here