Mar 15, 2014

Android Connect ASP.NET web services Ksoap

package adapter;

import helper.dbHelper;
import model.Customer;

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

import com.example.mobilesalesapp.R;


import android.app.Activity;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncWebServicesAdapter extends AsyncTask<String,String, Void> {
   
    Activity context;   
    dbHelper db;
   
    private String NAMESPACE = "http://tempuri.org/";   
    private String URL = "http://10.0.2.2:9000/Service.asmx";

    private String METHOD_GetCustomerList = "GetCustomerList";
   
    public AsyncWebServicesAdapter(Activity context) {
       
        this.context = context;
        db = new dbHelper(context);
    }       
    //private static String ACTION_GetCustomerList = "http://tempuri.org/GetCustomerList";
    /*
    public static SoapObject InvokeMethod(String URL,String MethodName)
    {
        SoapObject request = GetSoapObject(MethodName);
        SoapSerializationEnvelope envelope = GetEnvelope(request);
        return  MakeCall(URL,envelope,NAMESPACE,MethodName);
    }
    */
    public SoapObject GetSoapObject(String MethodName)
    {
        return new SoapObject(NAMESPACE,MethodName);
    }
    public SoapSerializationEnvelope GetEnvelope(SoapObject Soap)
    {
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Soap);
        envelope.bodyOut = Soap;
        return envelope;
    }
    /**
     *
     * @param URL - The complete URL where the web service resides
     * @param Envelope - The envelope to be passed
     * @param NAMESPACE - The web method namespace
     * @param METHOD_NAME - The method name
     * @return - SoapObject containing the resultset
     */
    public SoapObject MakeCall(String URL, SoapSerializationEnvelope Envelope, String NAMESPACE, String METHOD_NAME)
    {
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
         try
            {
                androidHttpTransport.call(NAMESPACE + METHOD_NAME, Envelope);
                // This step: get file XML
                SoapObject response = (SoapObject)Envelope.getResponse();
                // remove information XML,only retrieved results that returned
                response = (SoapObject) response.getProperty(1);
                return response;
            }
         catch(Exception e)
         {
             e.printStackTrace();
            
         }
         return null;
    }
    /**
     *
     * @param soap - represents the entering Soap object
     * @return returns the list of categories extracted from the response
     */   
    private void SyncCustomers(String company)
    {
        SoapObject request = GetSoapObject(METHOD_GetCustomerList);
        //Use this to add parameters
        request.addProperty("company",company);
        SoapSerializationEnvelope envelope = GetEnvelope(request);
        SoapObject response = MakeCall(URL,envelope,NAMESPACE,METHOD_GetCustomerList);
        if(response != null)
        {
            // get information XMl of tables that is returned
            SoapObject table = (SoapObject) response.getProperty(0);
            int RowCount = table.getPropertyCount();
            if(RowCount > 0)
            {
                db.DeleteCustomers();
            }
            for (int i = 0; i < RowCount; i++)
            {
                //Get information each row in table
                SoapObject pii = (SoapObject)table.getProperty(i);
                Customer obj = new Customer();
                obj.setCustID(pii.getProperty(0).toString());
                obj.setCustName(pii.getProperty(1).toString());
                obj.setAddressLine1(pii.getProperty(2).toString());
                obj.setAddressLine2(pii.getProperty(3).toString());
                obj.setAddressLine3(pii.getProperty(4).toString());
                obj.setTelephoneNo(pii.getProperty(5).toString());                   
                db.InsertCustomer(obj);   
                int percent = (int) (((i+1) / (float) RowCount) * 100);
                String[] status = new String[2];
                status[0]="Update Customer";
                status[1]=String.valueOf(percent);
                publishProgress(status);
            }
        }
    }
    @Override
    protected Void doInBackground(String... params) {
        // TODO Auto-generated method stub
        int count = params.length;
       
        for (int n = 0; n < count; n++)
        {
            String company = params[n];
            if(company.length()>0)
            {
                SyncCustomers(company);
            }           
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }

       
       
        return null;
    }
    protected void onProgressUpdate(String... progress) {
        super.onProgressUpdate(progress);
        setProgressPercent(progress);
    }
    private void setProgressPercent(String... status)
    {
        int giatri = Integer.parseInt(status[1]);
        ProgressBar paCha=(ProgressBar) context.findViewById(R.id.progressBar1);
        TextView txtmsg=(TextView)context.findViewById(R.id.textView1);
        TextView txtpercent=(TextView)context.findViewById(R.id.textView2);
       
        paCha.setProgress(giatri);
       
        txtmsg.setText(status[0]);
        txtpercent.setText(giatri+"%");
    }
    protected void onPostExecute(Void result) {
         super.onPostExecute(result);
         Toast.makeText(context, "Synchronization is successfully !",     Toast.LENGTH_LONG).show();
         context.finish();
    }

   
}
package com.example.mobilesalesapp;


import adapter.AsyncWebServicesAdapter;
import adapter.WebServicesAdapter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;


public class Synchronize extends Activity {

    WebServicesAdapter adapter;
    AsyncWebServicesAdapter Asynadapter;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_synchronize);
       
        //adapter = new WebServicesAdapter(this);
        //adapter.getCustomers("01");   
        //Toast.makeText(this, "Customer is Inserted", Toast.LENGTH_LONG).show();
       
        Asynadapter = new AsyncWebServicesAdapter(this);
        Asynadapter.execute("01");
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.synchronize, menu);
        return true;
    }
   
   
   
   
}

Importance Note:
use this on Androidmanifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />

if your android app > 8
then use this on MainActivy
//if (android.os.Build.VERSION.SDK_INT > 9) {
        //    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        //    StrictMode.setThreadPolicy(policy);
        //}
but it makes your app is heavy

Or use AsyncTask like AsyncWebServicesAdapter extends AsyncTask<String,String, Void> is better

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib