<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AsyncTask Archives - Truiton</title>
	<atom:link href="https://www.truiton.com/tag/asynctask/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Technology Reaching Us In Time - Online</description>
	<lastBuildDate>Mon, 25 Nov 2019 12:30:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/11/cropped-truiton_new_logo_half_white.png?fit=32%2C32&#038;ssl=1</url>
	<title>AsyncTask Archives - Truiton</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">54534495</site>	<item>
		<title>Android Volley vs AsyncTask &#124; Better Approach?</title>
		<link>https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/</link>
					<comments>https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Mon, 16 Feb 2015 19:17:01 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[AsyncTask]]></category>
		<category><![CDATA[comparison]]></category>
		<category><![CDATA[difference between Volley and AsyncTask]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=819</guid>

					<description><![CDATA[<p>Recently a new framework was introduced for Android in Google I/O called Android Volley. This new framework was introduced to reduce the complexity involved in fetching data over network. Being Android developers we all know that fetching data over network is one of the most common task that one has to perform in any Android&#8230;&#160;<a href="https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Volley vs AsyncTask &#124; Better Approach?</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/">Android Volley vs AsyncTask | Better Approach?</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><a href="https://www.flickr.com/photos/we-own-the-sky/8635797438" target="_blank" rel="noopener noreferrer"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="640" height="427" data-attachment-id="823" data-permalink="https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/android-volley-vs-asynctask/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/02/Android-Volley-vs-AsyncTask.jpg?fit=640%2C427&amp;ssl=1" data-orig-size="640,427" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Android Volley vs AsyncTask" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/02/Android-Volley-vs-AsyncTask.jpg?fit=300%2C200&amp;ssl=1" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/02/Android-Volley-vs-AsyncTask.jpg?fit=640%2C427&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/02/Android-Volley-vs-AsyncTask.jpg?resize=640%2C427" alt="Photo Credit: Pedro Hespanha via Flickr cc" class="wp-image-823" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/02/Android-Volley-vs-AsyncTask.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/02/Android-Volley-vs-AsyncTask.jpg?resize=300%2C200&amp;ssl=1 300w" sizes="(max-width: 640px) 100vw, 640px" /></a></figure></div>



<p></p>



<p>Recently a new framework was introduced for Android in Google I/O called Android Volley. This new framework was introduced to reduce the complexity involved in fetching data over network. Being Android developers we all know that fetching data over network is one of the most common task that one has to perform in any Android app. Therefore this new Android Volley library could be a game changer in Android app development. This library pitches in a lot of new features, but the question here is, do we need all these features? Here in this sum up, we would discuss the features of Android Volley vs AsyncTask.</p>



<p>Whenever some new component or library is released, being a developer, first thoughts that come into my mind are:</p>



<ol class="wp-block-list"><li>Why should I use it in my current code base?</li><li>Would it ease my development?</li><li>Would it improve my app&#8217;s functionally?</li></ol>



<p>In short, the answer to all these questions would be: <strong>Maybe.</strong> As its not always possible to adapt to something new in your current code base. Unless you are planning to refactor the code completely. Although if you see things from a different perspective, new is always better. Since android volley is just a framework on top of existing android framework. This framework is utilizing the power of android in best possible way. Therefore it may turn out to be very helpful for developers.</p>



<p></p>



<h2 class="wp-block-heading">Android Volley vs AsyncTask</h2>



<p>To start of we will discuss both the approaches individually. First lets begin with AsyncTask as its the older one.</p>



<h3 class="wp-block-heading">AsyncTask</h3>



<p>Usually in android, simply when one need to access a web API, an AsyncTask is used. Its the standard way to do it in android. You may have also observed that AsyncTask is used in many official code samples. Like whenever a new login activity is inserted through the ADT in eclipse, it gives you a stub AsyncTask where you are supposed to write the code for accessing the login API.</p>



<p>The basic code structure used to access data through the AsyncTask is:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class MyAsyncTask extends AsyncTask&lt;Void, Void, Void&gt; {
    @Override
    protected void onPreExecute() {
        //UI Interaction
    }

    @Override
    protected Void doInBackground(Void... params) {
        //Background Task
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        //UI Interaction
    }
}</pre>



<p>Main methods used to access the data from network by AsyncTask are:</p>



<ol class="wp-block-list"><li><code>onPreExecute()</code> &#8211; Usually used to start the loading bar, as this method can interact with UI thread.</li><li><code>doInBackground(Void... params)</code> &#8211; Main method in AsyncTask implementation where all the network access code is written. This method has a limitation that it cannot interact with UI thread.</li><li><code>onPostExecute(Void aVoid)</code> &#8211; This is the method where result from doInBackground is passed as an argument. Since this method can interact with UI thread. It is used to update the screen with results.</li></ol>



<p>A point to note here is that, in the implementation of doInBackground, one would have to write code to access network, and use classes like HttpURLConnection etc. Although if you are trying to access a completely custom implementation of web APIs this may serve your purpose better. Using AsyncTask to fetch data from network is not a bad approach at all, its just that you don&#8217;t get out of the box features like volley has.</p>



<p></p>



<h3 class="wp-block-heading">Android Volley</h3>



<p>Moving forward with this Android Volley vs AsyncTask sum up, let’s have an overview of Android volley.</p>



<p>As mentioned volley is a framework on top of android framework. It simply utilizes the power of android to access the network in best possible way. One of the many advantages of volley is that, you don’t need to write code for accessing network. All of this is managed by volley itself. Whenever a new network request is created, a background thread is spawned for network processing. Whose life-cycle is maintained by volley itself. In default implementation of volley, at a time 4 network threads can do processing simultaneously. To learn in detail about volley, please have a look at this <a title="Android Volley Example" href="http://www.truiton.com/2015/02/android-volley-example/" target="_blank" rel="noopener noreferrer">Android Volley example</a>.</p>



<p>With Volley you also get many more out of the box features like:</p>



<ol class="wp-block-list"><li>Retry Mechanism</li><li>Caching</li><li>Multiple Request Types
<ol>
<li>JsonObjectRequest</li>
<li>JsonArrayRequest</li>
<li>StringRequest</li>
<li>ImageRequest</li>
</ol>
</li></ol>



<h3 class="wp-block-heading">Difference between Android Volley and AsyncTask</h3>



<p>Like I have been saying new is always better. Using AsyncTask has been a good approach, but consider Android Volley as a 2.0 version of it. It has many improvements over AsyncTask, as volley is designed for the purpose of network access. A major advantage of Android Volley over AsyncTask is that you can do multiple requests simultaneously without the overhead of thread management. Also I believe retry mechanism is a great feature of volley which gives it an edge over AsynTask. Another advantage of volley over AsyncTask is that it provides you with multiple request types, through which complex requests can be made easily. On the other hand while using AsyncTasks one would have to create this type of request manually.</p>



<p></p>



<p>Although best approach differs from application to application. Like if you have less no of requests to make, you can use AsyncTask. As for volley, one has to <a title="Android Studio | How To Add A Library Project?" href="http://www.truiton.com/2015/02/android-studio-add-library-project/" target="_blank" rel="noopener noreferrer">import a library project</a> which increases your project size. Hence pick wisely between volley and AsyncTask. Hope this&nbsp;<a title="Android Volley vs AsyncTask | Better Approach?" href="http://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/">Android Volley vs AsyncTask</a> sum up helped you choose. Please like our Facebook and Google+ page for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/">Android Volley vs AsyncTask | Better Approach?</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/02/android-volley-vs-asynctask-better-approach/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">819</post-id>	</item>
		<item>
		<title>Consuming WCF SVC XML Web Service with Attributes in Android</title>
		<link>https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/</link>
					<comments>https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Fri, 19 Apr 2013 13:59:28 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[AsyncTask]]></category>
		<category><![CDATA[document builder]]></category>
		<category><![CDATA[DocumentBuilderFactory]]></category>
		<category><![CDATA[http post]]></category>
		<category><![CDATA[sax parser]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://blog.truiton.com/?p=215</guid>

					<description><![CDATA[<p>In today&#8217;s&#160;ingeniously connected world, no Android app is complete without internet access. Being a mobile app consultant at Truiton, sometimes I feel, I keep doing stuff that no one else has done ever before, for e.g. take topic of this tutorial Consuming WCF SVC XML Web Service with Attributes in Android. I searched internet for&#8230;&#160;<a href="https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Consuming WCF SVC XML Web Service with Attributes in Android</span></a></p>
<p>The post <a href="https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/">Consuming WCF SVC XML Web Service with Attributes in Android</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="640" height="423" data-attachment-id="221" data-permalink="https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/the-roadside-beauty-salon/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/3640379412_b69f766d8a_z.jpg?fit=640%2C423&amp;ssl=1" data-orig-size="640,423" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="The Roadside Beauty Salon" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/3640379412_b69f766d8a_z.jpg?fit=300%2C198&amp;ssl=1" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/3640379412_b69f766d8a_z.jpg?fit=640%2C423&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/3640379412_b69f766d8a_z.jpg?resize=640%2C423" alt="The Roadside Beauty Salon" class="wp-image-221" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/3640379412_b69f766d8a_z.jpg?w=640&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/3640379412_b69f766d8a_z.jpg?resize=300%2C198&amp;ssl=1 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure></div>



<p></p>



<p>In today&#8217;s&nbsp;ingeniously connected world, no Android app is complete without internet access. Being a mobile app consultant at <a title="Truiton" href="http://www.truiton.com" target="_blank" rel="noopener noreferrer">Truiton</a>, sometimes I feel, I keep doing stuff that no one else has done ever before, for e.g. take topic of this tutorial <a title="Consuming WCF SVC XML Web Service with Attributes in Android" href="http://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/">Consuming WCF SVC XML Web Service with Attributes in Android</a>. I searched internet for hours, hoping to find some info about how to invoke a DotNet based WCF&nbsp;SOAP web service with <span style="text-decoration: underline;">attributes</span> in XML, but found nothing. Eventually I figured out a way and thought to share it with the community by means of this <a title="Consuming WCF SVC XML Web Service with Attributes in Android" href="http://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/">Consuming WCF SVC XML Web Service with Attributes in Android</a> tutorial.</p>



<p>While searching for ways on how to consume&nbsp;WCF&nbsp;SOAP web service, I found an open source project for Android named <a title="Ksoap2" href="http://code.google.com/p/ksoap2-android/" target="_blank" rel="noopener noreferrer">Ksoap2</a>. This comes in a form of .jar file which can be included in any Android app project, this is a lightweight and efficient SOAP client library, at least this is what it&#8217;s page claims. I found various tutorials explaining on how to consume XML soap web services but none of them explains how to send attributes with input request data. In fact, I looked up the <a href="http://code.google.com/p/ksoap2-android/w/list" target="_blank" rel="noopener noreferrer">wiki</a> for ksoap2, hoping to find a way to add attributes to request XML, but found nothing. While searching for an answer, I started to think why should I include a third party library for such a small task of consuming a WCF SVC XML web service with attributes in Android. Hence I dropped searching in that direction.</p>



<p></p>



<p>Finally I found another way through which I could invoke a WCF SVC XML web service with attributes in Android, i.e. via <em>HttpClient, HttpPost, HttpResponse</em>, and <em>HttpEntity</em> classes of <em>org.apache.http</em> package. This way we can create a simple http request and send it to the desired url. Now since we are not using Ksoap2 library, there is still a question to be answered i.e. how will we parse the response? Answer to that is simple XML SAX parser, with document builder class. The main advantage of this approach is that we can send and parse attributes in request and response respectively. Lets have a look at my request for Soap xml web service:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   &lt;soapenv:Header/>
   &lt;soapenv:Body>
      &lt;tem:Login>
         &lt;!--Optional:-->
         &lt;tem:XInputXML>
            &lt;!--You may enter ANY elements at this point-->
            &lt;CREDENTIALS OF_OFFICEID="TRUITON" USER_PASSWORD="nilnil" EMAIL_ID="email@email.com"/>
         &lt;/tem:XInputXML>
      &lt;/tem:Login>
   &lt;/soapenv:Body>
&lt;/soapenv:Envelope></pre>



<p>Since we are not using any library to consume DotNet WCF soap web service with attributes in request, you need to create this request manually, which is quite simple to do. Have a look at the request above, in this request we are invoking <em>Login</em> method of SVC XML web service on Andorid. Here have a look at the highlighted part, i.e. the CREDENTIALS tag, it has three attributes. One of the main reasons we are using this <em>HttpPost</em> class is because of the attributes.</p>



<p>Lets have a look at the class which is consuming WCF SVC XML web service with attributes in Android:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.wcfconnect;

import java.io.StringReader;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class TruitonMainActivity extends Activity {
 String LOG_TAG = "TruitonMainActivity";
 private UserLoginTask mAuthTask = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_truiton_main);
 mAuthTask = new UserLoginTask();
 mAuthTask.execute((Void) null);
 }

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

 void doWhateverYouWant(){
 // TODO: Write here the code which needs to be executed after AsyncTask.
 }

 public class UserLoginTask extends AsyncTask&lt;Void, Void, Boolean> {
 @Override
 protected Boolean doInBackground(Void... params) {
 // TODO: attempt authentication against a network service.

 String SOAP_ACTION = "http://tempuri.org/MyService/Login";
 String URL = getString(R.string.URL);
 //String URL = "http:// *your URL here*";
 String response = null;
 try {
 HttpClient httpClient = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(URL);
 String bodyOut = "&lt;soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">"
 + "   &lt;soapenv:Header/>"
 + "   &lt;soapenv:Body>"
 + "      &lt;tem:Login>"
 + "         &lt;!--Optional:-->"
 + "         &lt;tem:XInputXML>"
 + "            &lt;!--You may enter ANY elements at this point-->"
 + "            &lt;CREDENTIALS OF_OFFICEID=\"TRUITON\" USER_PASSWORD=\"nilnil\" EMAIL_ID=\"email@email.com\"/>"
 + "         &lt;/tem:XInputXML>"
 + "      &lt;/tem:Login>"
 + "   &lt;/soapenv:Body>" + "&lt;/soapenv:Envelope>";

 StringEntity se = new StringEntity(bodyOut, HTTP.UTF_8);
 se.setContentType("text/xml");
 httpPost.addHeader("SOAPAction", SOAP_ACTION);
 httpPost.setEntity(se);

 HttpResponse httpResponse = httpClient.execute(httpPost);
 HttpEntity resEntity = httpResponse.getEntity();
 response = EntityUtils.toString(resEntity);
 DocumentBuilderFactory factory = DocumentBuilderFactory
 .newInstance();
 DocumentBuilder builder = factory.newDocumentBuilder();
 StringReader sr = new StringReader(response);
 InputSource is = new InputSource(sr);
 Document XMLResponse = builder.parse(is);
 NodeList elements = XMLResponse.getElementsByTagName("ERRORS");
 Boolean error = Boolean.valueOf(elements.item(0)
 .getAttributes().item(0).getNodeValue());
 HashMap&lt;String, String> Data = new HashMap&lt;String, String>();
 if (error) { // case of no error, value of error is returned
 // true in case of no error.
 elements = XMLResponse
 .getElementsByTagName(
 "AUTH_OUTPUT").item(0)
 .getChildNodes();

 for (int index = 0; index &lt; elements.getLength(); index++) {
 String elemName = elements.item(index).getNodeName();
 if (elements.item(index).hasAttributes()) { // if has
 // Attributes
 int attLength = elements.item(index)
 .getAttributes().getLength();
 for (int attIndex = 0; attIndex &lt; attLength; attIndex++) {
 String attName = elements.item(index)
 .getAttributes().item(attIndex)
 .getNodeName();
 String attValue = elements.item(index)
 .getAttributes().item(attIndex)
 .getNodeValue();
 Data.put(elemName + "_" + attName, attValue);
 }
 } else { // in case of no attributes
 Data.put(elemName, elements.item(index)
 .getTextContent());
 }
 }
 elements = XMLResponse.getElementsByTagName("METRO_CITY")
 .item(0).getChildNodes();
 String elemName = "METRO_CITY";
 int childNo = elements.getLength();
 for (int chIndex = 0; chIndex &lt; childNo; chIndex++) {
 Node childNode = elements.item(chIndex);
 String chName = childNode.getNodeName();
 if (childNode.hasAttributes()) { // if has attributes
 int attLength = childNode.getAttributes()
 .getLength();
 for (int attIndex = 0; attIndex &lt; attLength; attIndex++) {
 String attName = childNode.getAttributes()
 .item(attIndex).getNodeName();
 String attValue = childNode.getAttributes()
 .item(attIndex).getNodeValue();
 String val = Data.get(elemName + "_" + chName
 + "_" + attName);
 if (val == null) {
 Data.put(elemName + "_" + chName + "_"
 + attName, attValue);
 } else {
 Data.put(elemName + "_" + chName + "_"
 + attName, val + "," + attValue);
 }
 }
 }
 }
 } else {// In case of error
 String eCode = elements.item(0).getChildNodes().item(0)
 .getAttributes().item(0).getNodeValue();
 String eDesc = elements.item(0).getChildNodes().item(0)
 .getAttributes().item(1).getNodeValue();
 Exception e = new Exception("Server Response: Error Code- "
 + eCode + " -" + eDesc);
 throw e;
 }
 } catch (Exception e) {
 Log.e(LOG_TAG, e.getMessage());
 } finally {
 Log.v(LOG_TAG + " Response", response);
 }
 return true;
 }

 @Override
 protected void onPostExecute(final Boolean success) {
 mAuthTask = null;

 if (success) {
 Log.v(LOG_TAG + " AsyncTask", "Success");
 doWhateverYouWant();
 } else {
 Log.e(LOG_TAG + " AsyncTask", "Fail");
 }
 }

 @Override
 protected void onCancelled() {
 mAuthTask = null;
 }
 }
}</pre>



<p>Since the release of Honeycomb we cannot use network on main thread, therefore I used <em>AsyncTask</em> to call the WCF SVC XML web service with attributes on Android. This tutorial can also be treated as a tutorial for <em>AsyncTask</em>.</p>



<p>As you can see the, the code above has <em>SOAP_ACTION</em> and <em>URL</em> variable, specifying the url and soap action for soap xml web service. After all the the variable instantiations we are creating a HttpPost request, which has soap xml attributes. When the request is sent, response is captured in a string type variable <em>response</em>. Then we use <em>DocumentBuilderFactory</em> methods with&nbsp;SAX parser <em>InputSource</em> class to create a xml document which is used to parse xml response with help from <em>org.w3c.dom.node</em> class. The response XML is stored iteratively in a <em>HashMap</em> called <em>Data</em>.</p>



<p>Next we can pass on this data to onPostExecute method and call method in class from it. Just to show the concept of <em>AsyncTask</em>, I have created a method <em>doWhateverYouWant</em>().</p>



<p></p>



<p>Have a look at the login method web service response:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   &lt;s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      &lt;LoginResponse xmlns="http://tempuri.org/">
         &lt;LoginResult>
            &lt;AUTH_OUTPUT xmlns="">
               &lt;AGENT TA_ID="TR12" OF_ID="TRI98" USER_ID="TR-UID33" CURR_CODE="USD" TA_CL_AMOUNT="6538453.00" TA_ACCOUNT_FREEZED="0"/>
               &lt;CUSTOMER_ID>TR-UID33&lt;/CUSTOMER_ID>
               &lt;EMAIL_ID>email@email.com&lt;/EMAIL_ID>
               &lt;USER_FIRST_NAME>Truiton&lt;/USER_FIRST_NAME>
               &lt;OF_AIRPORT>0&lt;/OF_AIRPORT>
               &lt;USER_LAST_NAME>&lt;/USER_LAST_NAME>
               &lt;EMPLOYEE_CODE>TR110004&lt;/EMPLOYEE_CODE>
               &lt;OF_OFFICEID>NYCP0034&lt;/OF_OFFICEID>
               &lt;OF_ID>TRI98&lt;/OF_ID>
               &lt;POLICY_APPLY>False&lt;/POLICY_APPLY>
               &lt;FIRST_APPROVER/>
               &lt;FIRST_APPROVER_CODE/>
               &lt;OF_ADDRESS1/>
               &lt;OF_ADDRESS2/>
               &lt;CURR_CODE>USD&lt;/CURR_CODE>
               &lt;APL_TYPE_ID>1&lt;/APL_TYPE_ID>
               &lt;DEPT_ID>84&lt;/DEPT_ID>
               &lt;DEPT_NAME/>
               &lt;POSITION_NAME/>
               &lt;POSITION_ID>51&lt;/POSITION_ID>
               &lt;OF_NAME>Truit Online&lt;/OF_NAME>
               &lt;OF_CITY>NY&lt;/OF_CITY>
               &lt;CITY_NAME>New York&lt;/CITY_NAME>
               &lt;OF_COUNTRY>US&lt;/OF_COUNTRY>
               &lt;CO_NAME>United States&lt;/CO_NAME>
               &lt;USER_DOB>19750505&lt;/USER_DOB>
               &lt;CONTACT_NO>000-0000-000000&lt;/CONTACT_NO>
               &lt;MOBILE_NO>001-0000000000&lt;/MOBILE_NO>
               &lt;ADDRESS>New York&lt;/ADDRESS>
               &lt;STATE_NAME>New York&lt;/STATE_NAME>
               &lt;METRO_CITY>
                  &lt;CITY_DETAILS CITY_CODE="BUF" CITY_NAME="Buffalo Niagara International" CO_CODE="US"/>
                  &lt;CITY_DETAILS CITY_CODE="JFK" CITY_NAME="John F Kennedy International" CO_CODE="US"/>
                  &lt;CITY_DETAILS CITY_CODE="LGA" CITY_NAME="La Guardia" CO_CODE="US"/>
                  &lt;CITY_DETAILS CITY_CODE="EWR" CITY_NAME="Newark Liberty International" CO_CODE="US"/>
               &lt;/METRO_CITY>
               &lt;ERRORS STATUS="TRUE">
                  &lt;ERROR CODE="" DESC=""/>
               &lt;/ERRORS>
            &lt;/AUTH_OUTPUT>
         &lt;/LoginResult>
      &lt;/LoginResponse>
   &lt;/s:Body>
&lt;/s:Envelope></pre>



<p>One more thing don&#8217;t forget to add the internet access permission in the manifest, as while consuming WCF SVC XML web service with attributes on Android we will be interacting with internet.</p>



<p class="lang:xhtml decode:true"><code>&lt;uses-permission android:name="android.permission.INTERNET" /></code></p>



<p></p>



<p>Have a look at the log image:</p>



<ul data-carousel-extra='{&quot;blog_id&quot;:1,&quot;permalink&quot;:&quot;https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/&quot;}'  class="wp-block-gallery columns-3 is-cropped wp-block-gallery-1 is-layout-flex wp-block-gallery-is-layout-flex"><li class="blocks-gallery-item"><figure><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="560" height="20" data-attachment-id="218" data-permalink="https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/wcfparsing1/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?fit=560%2C20&amp;ssl=1" data-orig-size="560,20" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="" data-image-description="" data-image-caption="&lt;p&gt;Log&lt;/p&gt;
" data-medium-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?fit=300%2C10&amp;ssl=1" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?fit=560%2C20&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?resize=560%2C20&#038;ssl=1" alt="Consuming WCF SVC XML Web Service with Attributes in Android" data-id="218" class="wp-image-218" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?w=560&amp;ssl=1 560w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing1.png?resize=300%2C10&amp;ssl=1 300w" sizes="auto, (max-width: 560px) 100vw, 560px" /></a></figure></li><li class="blocks-gallery-item"><figure><a href="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?ssl=1"><img data-recalc-dims="1" loading="lazy" decoding="async" width="332" height="590" data-attachment-id="219" data-permalink="https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/wcfparsing2/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?fit=332%2C590&amp;ssl=1" data-orig-size="332,590" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="" data-image-description="" data-image-caption="&lt;p&gt;Consuming WCF SVC XML Web Service with Attributes in Android&lt;/p&gt;
" data-medium-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?fit=168%2C300&amp;ssl=1" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?fit=332%2C590&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?resize=332%2C590&#038;ssl=1" alt="Consuming WCF SVC XML Web Service with Attributes in Android" data-id="219" class="wp-image-219" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?w=332&amp;ssl=1 332w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2013/04/WCFParsing2.png?resize=168%2C300&amp;ssl=1 168w" sizes="auto, (max-width: 332px) 100vw, 332px" /></a></figure></li></ul>



<p></p>



<p>With this I can conclude my tutorial on consuming WCF SVC XML web service with attributes on Android. Here we sent out a soap request with attributes in tags, which was not looking feasible by use of Ksoap2 library. Therefore we used <em>HttpClient, HttpPost, HttpResponse</em>, and <em>HttpEntity</em> classes of <em>org.apache.http</em> package to create and send the request to&nbsp;WCF SVC XML web service. Next we used <em>DocumentBuilderFactory, DocumentBuilder, StringReader, InputSource</em>, and <em>NodeList</em> classes to parse the data in XML format. Also this approach promotes the use of inbuilt functionality of Android and Java since we did not use any third party library. Hope this tutorial helps you, If it did please +1, like and share on Google+ and Facebook.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/">Consuming WCF SVC XML Web Service with Attributes in Android</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2013/04/consuming-wcf-svc-xml-web-service-with-attributes-in-android/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">215</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: www.truiton.com @ 2026-04-17 02:02:45 by W3 Total Cache
-->