Skip to main content

LOAD DATA FROM SOAP WEB SERVICE - ANDROID TUTORIAL

In this post I explain how to load and send data from SOAP web service in your android application.

What is SOAP?
SOAP is a standards-based web services technology that allows providers to abstract data and transport implementations over the web. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.

Now we will see it though an example(here the data is fetch from web and set in drop-down)

Step 1. Create new project in Android Studio.

Step 2. Before we start creating our project we need external library for SOAP to load data from SOAP based web service. I use KSOAP2 library to load and send data to service. You download from here or add the dependencies in build.gradle as given,

compile 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'

and repositories as 
maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }

Step 3. If downloaded the .jar file follow this - After download you need to add KSOAP2 library in 
your project in android studio paste your KSOAP2.jar file in libs folder inside app folder. Right click
on the jar file and select Add As Library...

Step 4. Now open your AndroidManifest.xml and add permission of internet to request server and 
get data.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 5. Now open your activity_main.xml file inside layout folder. Here I created a form in which I send data to server and get response.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    tools:context="mrbrown.com.soap_webservicesample.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@drawable/rectangle_style_safton"
            android:gravity="center_vertical">
            
            <TextView
                android:id="@+id/idHead"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Select Country"
                android:textStyle="bold"
                android:fontFamily="serif"
                android:background="@color/colorSafron"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/colorPrimary"/>
    
            <View
                android:id="@+id/idView"
                android:layout_below="@+id/idHead"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@color/colorSafron"/>
            
            <Spinner
                android:id="@+id/idSpinner"
                android:layout_below="@+id/idView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp">
            </Spinner>
            
        </RelativeLayout>
    </LinearLayout>
</RelativeLayout>

Step 6. Now open your MainActivity.java file. Here we request to server we use Async task to request server. I used separate classes for different functionality.

 public class MainActivity extends AppCompatActivity {

    private Spinner spinCtry;
    ArrayList<String> locationIds = new ArrayList<>();
    List<SpinnerHelper> arrayCountryspinner;
    String Checkcommonspinner=Constant.COUNTRY, returnCountry="Error", countryId, countryName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinCtry = (Spinner) findViewById(R.id.idSpinner);

        /*getLocationFunction*/
        getLocation();

    }

    /*this_check_internet_connection&call_async_*/
    private void getLocation() {
        if (Constant.isConnectingToInternet(MainActivity.this)) {
            new getCountry(MainActivity.this)
                    .execute((Void[]) null);
        } else {
            Constant.alertbox(MainActivity.this,
                    getString(R.string.str_networkmessage),
                    getString(R.string.str_networktitlemessage));
        }
    }

    private class getCountry extends AsyncTask<Void, Void, String>{
        private ProgressDialog dialog;
        private Context context;

        public getCountry(MainActivity context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(context);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setMessage("Please wait...");
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            try {
                Webservice webservice = new Webservice(context);

                if(Checkcommonspinner.equalsIgnoreCase(Constant.COUNTRY)) {
                    returnCountry = webservice.getCountry();
                }
                Log.e("Data", returnCountry);
            } catch (Exception e) {
            }

            return returnCountry;
        }

        @Override
        protected void onPostExecute(String message) {
            dialog.dismiss();
            if (!message.equals("error")) {
                locationIds.clear();
                ApiParsing parsing =new ApiParsing(MainActivity.this);

                if(Checkcommonspinner.equalsIgnoreCase(Constant.COUNTRY)) {
                    //getting the values by parsing the response
                    arrayCountryspinner = parsing.getCountry(message);

                    for(int i=0;i<arrayCountryspinner.size();i++){
                        locationIds.add(arrayCountryspinner.get(i).getId());

                    }
                    //method to set the values in spinner
                    setSpinner();

                }else  {
                }
            } else {
                Constant.alertbox(MainActivity.this,
                        getString(R.string.error),
                        getString(R.string.error));
            }
        }
    }

    private void setSpinner() {

        ArrayAdapter<SpinnerHelper> spinnerAdapter = new ArrayAdapter<>(MainActivity.this,
                android.R.layout.simple_list_item_1, arrayCountryspinner);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
        spinCtry.setAdapter(spinnerAdapter);

        /*Spinner_onItemClick*/
        spinCtry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {

                SpinnerHelper locationid = (SpinnerHelper) adapterView.getSelectedItem();
                countryId = locationid.getId();

                countryName=locationid.getName();
                Checkcommonspinner=Constant.COUNTRY;
                 // getLocation();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
}

Step 7. Other classes used here

Constant.java
public class Constant {

    public static final String Webservice_url = "http://www.YOURURL";

    public static final String COUNTRY="Country";
    public static final String TAG_COUNTRYNAME= "CountryName";
    public static final String TAG_COUNTRYID= "CountryId";

    /*Create_Constant_Methods*/

    /*check_for_Internet Connection*/
    public static boolean isConnectingToInternet(MainActivity _context) {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = connectivity.getActiveNetworkInfo();
        if (info == null) {
            return false;
        } else {
            return true;
        }
    }

}

Webservice.java
class Webservice {

    Context context;

    public Webservice(Context con) {
        context = con;
    }

    public String getCountry() {

        try {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);

            SoapObject request = new SoapObject(context.getResources()
                    .getString(R.string.namespace), context.getResources()
                    .getString(R.string.getCountry));

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;
            HttpTransportSE androidHttpTransport = new HttpTransportSE(
                    Constant.Webservice_url);
            androidHttpTransport.call(
                    context.getResources().getString(R.string.namespace)
                            + context.getResources().getString(
                            R.string.getCountry), envelope);

            String result = envelope.getResponse().toString();

            return result;

        } catch (Exception e) {
            // TODO: handle exception
            return e.toString();
        }
    }

}

ApiParsing.java
class ApiParsing {

    Context mContext;

    public ApiParsing(Context context) {
        mContext = context;
    }

    public ArrayList<SpinnerHelper> getCountry(String json) {

        ArrayList<SpinnerHelper> Locationdetails = new ArrayList<>();
        try {
            JSONArray states = new JSONArray(json);
            for (int i = 0; i < states.length(); i++) {
                JSONObject state = states.getJSONObject(i);
                String LocationId = state.optString(Constant.TAG_COUNTRYID);
                String LoccationName = state.optString(Constant.TAG_COUNTRYNAME);
                SpinnerHelper countrydetails = new SpinnerHelper(LocationId, LoccationName);
                Locationdetails.add(countrydetails);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return Locationdetails;
    }

}

SpinnerHelper.java
public class SpinnerHelper {

    private String Id;
    private String Name;

    public SpinnerHelper(String natureProblemId, String natureProblemname) {
        this.Id = natureProblemId;
        this.Name = natureProblemname;

        setName(Name);
        setId(Id);
    }
    public String getId() {
        return Id;
    }

    public void setId(String natureProblemId) {
        Id = natureProblemId;
    }

    public String getName() {
        return Name;
    }

    public void setName(String natureProblemname) {
        Name = natureProblemname;
    }

    //to display object as a string in spinner
    @Override
    public String toString() {
        return Name;
    }

}

webservice.xml (in res-values folder)
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="namespace">http://tempuris.org/</string>
    <string name="getCountry">GetCountry</string>
</resources>


___________________________________________________________
SourceCode for SOAP_webservice.zip

Happy Coding...

Comments

Popular posts from this blog

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ___________________________________________________________

Set Focus on Spinner when select Item on Vertical Scroll - Android Tutorial

We may face an issue on Spinner lies on long vertical scroll, (i.e.) when selected and item from dropdown the focus moves to top of scroll. To avoid this please follow this piece of code spinner.setFocusableInTouchMode( true ); spinner.setOnFocusChangeListener( new View.OnFocusChangeListener() {     @Override     public void onFocusChange(View v, boolean hasFocus) {         if (hasFocus) {             if (spinner.getWindowToken() != null ) {                 spinner.performClick();             }         }     } });   _______________________________________________________________________________ Happy Coding...