<?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>Mobile Orchard &#187; Android</title>
	<atom:link href="http://mobileorchard.com/category/tutorials/android/feed/" rel="self" type="application/rss+xml" />
	<link>http://mobileorchard.com</link>
	<description>The iPhone App Developers&#039; Blog: iPhone Programming, Developer News, Interviews And Tutorials</description>
	<lastBuildDate>Mon, 20 May 2013 13:11:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Android App Development: Implementing Search activities</title>
		<link>http://mobileorchard.com/android-app-development-implementing-search-activities/</link>
		<comments>http://mobileorchard.com/android-app-development-implementing-search-activities/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 17:00:17 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7999</guid>
		<description><![CDATA[Most Android phones have a search button. this button is used to search contacts,applications or anything on the phone. We can make use of the search functionality in our apps. In this post we&#8217;re going to see how to implement search functionality to search for entries stored in a databaseand display them in a ListView. [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>Most Android phones have a<strong> search</strong> button. this button is used to search contacts,applications or anything on the phone. We can make use of the search functionality in our apps.</p>
<p>In this post we&#8217;re going to see how to implement search functionality to search for entries stored in a databaseand display them in a ListView.</p>
<h2>Creating database:</h2>
<p>our database has two tables: <strong>Countries</strong> and <strong>Names:</strong></p>
<pre>public class DBHelper extends SQLiteOpenHelper {

	public DBHelper(Context context) {
		super(context, "DemoDB", null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		StringBuilder builder=new StringBuilder();
		// countries table
		builder.append("CREATE TABLE Countries ");
		builder.append("(_id INTEGER PRIMARY KEY AUTOINCREMENT,");
		builder.append("NAME TEXT) ");
		db.execSQL(builder.toString());
		// Names table
		// Virtual table for full text search
		builder.setLength(0);
		builder.append("CREATE VIRTUAL TABLE NAMES USING FTS3");
		builder.append("(");
		builder.append("name TEXT) ");		
		db.execSQL(builder.toString());
		builder=new StringBuilder();

		//dummy  data
		InsertData(db);

	}

	 void InsertData(SQLiteDatabase db)
	 {
		 ContentValues cv=new ContentValues();
			cv.put("NAME","USA");
			db.insert("Countries", "NAME", cv);
			cv.put("NAME","UK");
			db.insert("Countries", "NAME", cv);
			cv.put("NAME","Spain");
			db.insert("Countries", "NAME", cv);
			cv.put("NAME","ITALY");
			db.insert("Countries", "NAME", cv);
			cv.put("NAME","Germany");
			db.insert("Countries", "NAME", cv);

			 cv=new ContentValues();
				cv.put("name","John");
				db.insert("NAMES", "name", cv);
				cv.put("name","Jack");
				db.insert("NAMES", "name", cv);
				cv.put("name","Ann");
				db.insert("NAMES", "name", cv);
				cv.put("name","Adam");
				db.insert("NAMES", "name", cv);
				cv.put("name","Sarah");
				db.insert("NAMES", "name", cv);

	 }

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}
}</pre>
<p>notice that the <strong>Names </strong>table is a <strong>VIRTUAL </strong>table. we created it as virtual to make use of <strong>Full Text Search (FTS3)</strong> feature in SQLite. this feature makes queries faster than that in regular tables.</p>
<p>then we add two functions to retrieve all rows from both tables:</p>
<pre>/**
	 * Return all countries
	 * @return
	 */
	public ArrayListgetCountries(){
		ArrayList countries=new ArrayList();
		SQLiteDatabase db=this.getReadableDatabase();
		Cursor c=db.rawQuery("select * from Countries", null);
		while(c.moveToNext()){
			String country=c.getString(1);
			countries.add(country);
		}
		c.close();
		return countries;
	}
/**
	 * Return all names
	 * @return
	 */

	public ArrayListgetNames(){
		ArrayList names=new ArrayList();
		Cursor c=this.getReadableDatabase().rawQuery("select * FROM Names", null);
		while(c.moveToNext()){
			String name=c.getString(0);
			names.add(name);
		}
		c.close();
		return names;
	}</pre>
<p>and another two functions to retrieve data based on a <strong>search string</strong>:</p>
<pre>/**
	 * Return all countries based on a search string
	 * @return
	 */
	public ArrayListgetCountriesSearch(String query){
		ArrayList countries=new ArrayList();
		SQLiteDatabase db=this.getReadableDatabase();
		Cursor c=db.rawQuery("select * from Countries where NAME LIKE '%"+query+"%'", null);
		while(c.moveToNext()){
			String country=c.getString(1);
			countries.add(country);
		}
		c.close();
		return countries;
	}
/**
	 * Return all names based on a search string
	 * we use the MATCH keyword to make use of the full text search
	 * @return
	 */
	public ArrayListgetNamesSearch(String query){
		ArrayList names=new ArrayList();
		Cursor c=this.getReadableDatabase().rawQuery("select * FROM Names WHERE name MATCH '"+query+"'", null);
		while(c.moveToNext()){
			String name=c.getString(0);
			names.add(name);
		}
		c.close();
		return names;
	}</pre>
<h2>Implementing The activity:</h2>
<p>then we will create our activity that has a list view like this:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
&lt;ListView
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/list"/&gt;
&lt;/LinearLayout&gt;</pre>
<p><a href="http://mobileorchard.com/android-app-development-implementing-search-activities/search/" rel="attachment wp-att-8000"><img class="aligncenter size-medium wp-image-8000" src="http://mobileorchard.com/wp-content/uploads/2011/07/search-200x300.png" alt="" width="200" height="300" /></a><br />
we load data from database like this:</p>
<pre>public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list=(ListView)findViewById(R.id.list);

            DBHelper helper=new DBHelper(this);
            ArrayList items=helper.getNames();
            ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,items);
            list.setAdapter(adapter);
}</pre>
<pre></pre>
<p>&nbsp;</p>
<h2>Handling the search dialog:</h2>
<p>In order to handle the search dialog ourselves we need to create a xml file with search configurations such as the search dialog title, voice search capabilities, content provider for auto complete and so on. we create a file with the name <strong>searchable.xml</strong> in <strong>res/xml</strong>directory:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/hint"  &gt;
&lt;/searchable&gt;</pre>
<p>the <strong>android:hint</strong> attribute denotes a string that acts as a water mark on the search text box.<br />
then we need to add an <strong>Intent Filter</strong> in out app&#8217;s <strong>AndroidManifest.xml</strong> file to our activity to handle the search dialog:</p>
<pre>&lt;activity android:name=".MainActivty"
                  android:label="@string/app_name"&gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;
                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;
             &lt;intent-filter&gt;
            &lt;action android:name="android.intent.action.SEARCH" /&gt;
        &lt;/intent-filter&gt;
        &lt;meta-data android:name="android.app.searchable"
                   android:resource="@xml/searchable"/&gt;
        &lt;/activity&gt;</pre>
<h2>Understanding the Search process:</h2>
<p>when you press the search button, type some text and click on search the activit&#8217;s <strong>onSearchRequested()</strong> function is called, then an Intent with the action <strong>Intent.ACTION_SEARCH</strong> is created and you activity is re-created with this intent.<br />
the search intent has you search string as a string extra with the name <strong>SearchManager.QUERY</strong>. also it can carry a <strong>bundle </strong>of other extras with the name <strong>SearchManager.APP_DATA</strong>.</p>
<h3>what if the device doesn&#8217;t have a Search button:</h3>
<p>not all Android devices have a search button, so we can start the search dialog manually by calling the activity&#8217;s <strong>onSearchRequested()</strong> from a button or a menu item:</p>
<pre>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add("Search").setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
                                //launch the search dialog
				onSearchRequested();
				return true;
			}
		});
    	return true;
    }</pre>
<h2>adding extras to the search dialog:</h2>
<p>we can pass some extra data as a bundle with our search dialog or an initial search string by overriding the activity&#8217;s <strong>onSearchRequested()</strong>:</p>
<pre>@Override
    public boolean onSearchRequested() {
    	Bundle bundle=new Bundle();
		bundle.putString("extra", "exttra info");
		// search initial query
		startSearch("Country", false, bundle, false);
		return true;
    }</pre>
<h2>Handling the search query:</h2>
<p>we said before that the search query is passed as a <strong>String extra</strong> when our activity is re-created. so we can handle the searcgh string in our <strong>onCreate()</strong> like this:</p>
<pre>@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list=(ListView)findViewById(R.id.list);

        DBHelper helper=new DBHelper(this);
        Intent intent=getIntent();
        // if the activity is created from search
        	if(intent.getAction().equals(Intent.ACTION_SEARCH)){
        		// get search query
        		String query=intent.getStringExtra(SearchManager.QUERY);
        		ArrayList items=helper.getNamesSearch(query);
        		//get extras, just for demonstration
        		Bundle bundle=intent.getBundleExtra(SearchManager.APP_DATA);
        	    String info=bundle.getString("extra");
        		Log.v("extra", info);
        		//bind the list
                ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,items);
                list.setAdapter(adapter);
        	}
        //activity created normally
        else{
        	ArrayList items=helper.getNames();
            ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,items);
            list.setAdapter(adapter);
        }
        helper.close();
    }</pre>
<p><a href="http://mobileorchard.com/android-app-development-implementing-search-activities/search2/" rel="attachment wp-att-8001"><img class="aligncenter size-medium wp-image-8001" src="http://mobileorchard.com/wp-content/uploads/2011/07/search2-200x300.png" alt="" width="200" height="300" /></a></p>
<p>we just extract the search string and any other extras and perform our search logic based on the search string.<br />
and that&#8217;s was all about implementing search, stay tuned for another Android tutorial</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-development-implementing-search-activities/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Optimizing Your Tutorial – How to Introduce Currency in a Virtual Economy</title>
		<link>http://mobileorchard.com/optimizing-your-tutorial-%e2%80%93-how-to-introduce-currency-in-a-virtual-economy/</link>
		<comments>http://mobileorchard.com/optimizing-your-tutorial-%e2%80%93-how-to-introduce-currency-in-a-virtual-economy/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 13:00:44 +0000</pubDate>
		<dc:creator>Matt Tubergen</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7965</guid>
		<description><![CDATA[You can have 20 million users download you freemium application, but if only 2 of them spend more than 30 seconds in your app you have a problem! This week we will look at the ways currency can be introduced and the best way to introduce users to your games virtual economy. Dad to son: [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>You can have 20 million users download you freemium application, but if only 2 of them spend more than 30 seconds in your app you have a problem! This week we will look at the ways currency can be introduced and the best way to introduce users to your games virtual economy.</p>
<p><strong>Dad to son: “Don’t spend it all in one place”</strong></p>
<p>I remember as a child, although infrequently, receiving money from my parents for a number of reasons. Monetary reward would come from performing chores, good grades and birthday events. Receiving this fine coinage would always be accompanied with the phrase “Don’t spend it all in one place!”…. and while my father’s intentions really weren’t for me to spread my cash across multiple places, he did attempt to warn me against spending my money foolishly. Growing up my father was always delivering sound bites on money management regardless of how much they were ignored, but the point was eventually digested and I soon better understood how to spend my money. In the way that my father educated me, we as game developers need to educate our users on how to operate or “spend” money in the virtual game economies that we create.</p>
<p><strong>Currency introduced through gameplay</strong></p>
<p>The best way to teach is through action. Encourage your user to take action that requires spending virtual currency. Always reinforce the spending with a positive experience so that a user knows spending money is valuable. All successful simulation games on the mobile market today introduce currency as unique steps in their tutorial… or at least require it be used within the first few sessions of gameplay.</p>
<p><a href="http://mobileorchard.com/optimizing-your-tutorial-%e2%80%93-how-to-introduce-currency-in-a-virtual-economy/spend-wising/" rel="attachment wp-att-7966"><img class="aligncenter size-full wp-image-7966" src="http://mobileorchard.com/wp-content/uploads/2011/07/spend-wising.jpg" alt="" width="375" height="250" /></a></p>
<p><strong>Quarters, Nickels and Dimes</strong></p>
<p>Many games these days have multiple currency types know as premium (primary) currency and secondary currency. Primary currency typically is defined as being rare and tightly tied to real dollar value while secondary currency can be easy to earn and readily accessible. Depending on the game, you can choose to charge real dollars for both premium and secondary currencies or simply just premium. Make sure to introduce both currencies during game but do so separately. Be careful to introduce users to your currency all in one step or action. Spread out the introduction over a series of steps so that they can fully grasp how the decisions they make regarding their purchases affect gameplay.</p>
<p>&nbsp;</p>
<p><strong>Missions vs. Tutorial</strong></p>
<p>Next week we will talk about the differences of missions vs. tutorials and the value each play in a mobile gaming environment.</p>
<p>Do you have a question about freemium gaming or a topic you’d like us to explore? Let us know in the comments or catch us on twitter <a href="http://twitter.com/#%21/rechargestudios" target="_blank">@rechargestudios</a> or <a href="http://twitter.com/#%21/w3i" target="_blank">@w3i</a>.</p>
<p><em>Freemium Game Blogs are published in partnership with the series on <a href="http://blog.w3i.com/category/freemium-game-mechanics/?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Blog" target="_blank">W3i’s corporate blog</a>. </em></p>
<p><em>Matt Tubergen heads <a href="http://www.rechargestudios.com/?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Mobile%20Orchard" target="_blank">Recharge Studios</a>, a wholly owned subsidiary of <a href="http://www.w3i.com/mobile-apps.aspx?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Mobile%20Orchard" target="_blank">W3i</a> that invests in the development and marketing/distribution of freemium mobile games.  W3i is a market leader in distributing and monetizing apps with over 500 million apps distributed for W3i clients. Recharge Studios is actively seeking new investment opportunities, if you have a great idea for a game <a href="http://www.rechargestudios.com/contact/?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Mobile%20Orchard" target="_blank">contact us</a>.</em></p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/optimizing-your-tutorial-%e2%80%93-how-to-introduce-currency-in-a-virtual-economy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Android App Development: Implementing remote Android Services with AIDL</title>
		<link>http://mobileorchard.com/android-app-development-implementing-remote-android-services-with-aidl/</link>
		<comments>http://mobileorchard.com/android-app-development-implementing-remote-android-services-with-aidl/#comments</comments>
		<pubDate>Wed, 13 Jul 2011 17:00:21 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7955</guid>
		<description><![CDATA[In the last post we saw how to use Android services to do time consuming operations in the background. in this post we will see how can a client application call the methods of a service defined in another application. this is achieved through Android Interface Definition Language (AIDL). AIDL is a java like language [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>In the last post we saw how to use Android services to do time consuming operations in the background. in this post we will see how can a client application call the methods of a service defined in another application. this is achieved through <strong>Android Interface Definition Language (AIDL). </strong></p>
<p><strong></strong>AIDL is a java like language that enables you to define an interface that both the application defining the service and the client application implement it.</p>
<p>the interface defines the functions that are needed to be called in the client application.</p>
<h2>Defining the AIDL file:</h2>
<p>AIDL syntax is similar to that of Java, we can use the following data types in AIDL:</p>
<ol>
<li>primitive data types: int, long, char, boolean,&#8230;.</li>
<li>String.</li>
<li>CharSequence.</li>
<li>List (ArrayList,Vector,&#8230;).</li>
</ol>
<p>&nbsp;</p>
<ol>
<li>the AIDL file is defined as follows:<br />
open a notepad file and paste the following code in it:</p>
<pre>package com.mina.servicedemo;

// service interface
interface IRemoteService {
    //sample method
    String sayHello(String message);
}</pre>
<p>take care of the package name <strong>com.mina.servicedemo</strong>.<br />
we defined a methods <strong>sayHello(String message)</strong> that returns a string.</p>
<p>&nbsp;</li>
<li>save the file with the name<strong> IRemoteService</strong> and change it&#8217;s extension to <strong>.aidl</strong>.</li>
<li>copy the file to the <strong>src</strong> folder of your project.</li>
<li>once you save and build the file, Android generates an interface java file with the name <strong>IRemoteService.java</strong> in the <strong>gen</strong> folder if the project.</li>
</ol>
<h2>Defining the Service:</h2>
<p>now we want our service to expose this interface to client applications, so we return an implementation of the service in the <strong>onBind()</strong> method of our service:</p>
<pre>package com.mina.servicedemo;

import com.mina.servicedemo.IRemoteService.Stub;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Toast;

public class DemoService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}

	// implementation of the aidl interface
	private final IRemoteService.Stub mBinder=new Stub() {

		@Override
		public String sayHello(String message) throws RemoteException {
			return "Hello "+message;

		}
	};

	}
}</pre>
<p>the last thing to do in the service is to make its <strong>exported</strong> attribute in the <strong>AndroidManifest.xml</strong> file set to true like this:</p>
<pre>&lt;service android:name="DemoService" android:exported="true"&gt;&lt;/service&gt;</pre>
<p>our app structure can be like this:</p>
<p><a href="http://mobileorchard.com/android-app-development-implementing-remote-android-services-with-aidl/service-demo/" rel="attachment wp-att-7957"><img class="aligncenter size-medium wp-image-7957" src="http://mobileorchard.com/wp-content/uploads/2011/07/Service-Demo-263x300.png" alt="" width="263" height="300" /></a></p>
<p>&nbsp;</p>
<h2>Consuming the service at the client application:</h2>
<p>now to our client application where we want to invoke methods from our service. the client application is a separate application with a different package name than that where the service is defined.</p>
<p>the client application needs a reference to the AIDL interface defined in the original applcation, this is done through the following steps:</p>
<ol>
<li>in the client applicatio create a package with the same package name of that the service is defined in: <strong>com.mina.servicedemo.</strong></li>
<li>copy the AIDL file in this package.</li>
<li>save and build and a new file called IRemoteService.java is generated. your app structure should be like this:<a href="http://mobileorchard.com/android-app-development-implementing-remote-android-services-with-aidl/service-client/" rel="attachment wp-att-7956"><img class="aligncenter size-medium wp-image-7956" src="http://mobileorchard.com/wp-content/uploads/2011/07/Service-Client-263x300.png" alt="" width="263" height="300" /></a></li>
</ol>
<p>and we invoke the servcice methods in our activity like this:</p>
<pre>package com.mina.serviceclient;

import com.mina.servicedemo.IRemoteService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class MainActivity extends Activity {

	IRemoteService mRemoteService;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent serviceIntent=new Intent();
        serviceIntent.setClassName("com.mina.servicedemo", "com.mina.servicedemo.DemoService");
        boolean ok=bindService(serviceIntent, mServiceConnection,Context.BIND_AUTO_CREATE);
        Log.v("ok", String.valueOf(ok));
    }

    private ServiceConnection mServiceConnection=new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// get instance of the aidl binder
			mRemoteService = IRemoteService.Stub.asInterface(service);
			try {
				String message=mRemoteService.sayHello("Mina");
				Log.v("message", message);
			} catch (RemoteException e) {
				Log.e("RemoteException", e.toString());
			}

		}
	};
}</pre>
<p>and that&#8217;s was all about calling remote services with AIDL, stay tuned for another Android tutorial</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-development-implementing-remote-android-services-with-aidl/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Android App Development: Android Services</title>
		<link>http://mobileorchard.com/android-app-development-android-services/</link>
		<comments>http://mobileorchard.com/android-app-development-android-services/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 13:00:22 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7737</guid>
		<description><![CDATA[Android Service is used for long-running processes that do not require user interaction, such as calling a web service and parsing response. Or processes that need to be running even if the application that started the service is not on the foreground such as playing mp3 files in a music player. we need to distinguish [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p><strong>Android Service </strong>is used for long-running processes that do not require user interaction, such as calling a web service and parsing response. Or processes that need to be running even if the application that started the service is not on the foreground such as playing mp3 files in a music player.</p>
<p>we need to distinguish between A <strong>Service</strong> and a<strong> Thread</strong> or an <strong>AsyncTask: </strong>Threads or Async task perform their tasks in a background thread thus they do not block the main thread, while a service performs it&#8217;s work in the main thread. so if a service is performing an intensive task such as calling a web service, it may block the main thread until it finishes. So for intensive tasks a service should run it&#8217;s work in a background thread.</p>
<p>A service runs in the same process of the application and keeps running until stopped by itself, stopped by the user or killed by the system if it needs memory.</p>
<h2>Creating a service:</h2>
<p>to create a service we create a class that extends <strong>android.app.Service </strong>and it would be like this:</p>
<pre>public class DemoService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}</pre>
<p>next we need to define our service in our <strong>AndroidManifest.xml</strong> file:</p>
<pre>&lt;service android:name="DemoService"&gt;&lt;/service&gt;</pre>
<p>The service life cycle has the following events</p>
<ul>
<li><strong>onCreate():</strong> called when the service is created.</li>
<li><strong>onStart():</strong> Called when the service starts by a call to <strong>startService(Intent intent)</strong>.</li>
<li><strong>onDestroy():</strong> Called as the service is terminates.</li>
</ul>
<h2><strong>Calling a service:</strong></h2>
<p>A service can be called from an activity in two ways:</p>
<ol>
<li>By calling <strong>startService(Intent intent).</strong></li>
<li>By binding to the service through an <strong>Binder</strong> object.</li>
</ol>
<h3>calling startService(Intent intent):</h3>
<p>to start a service from an activity using this method, we create an intent and start the service like this:</p>
<pre>Intent intent=new Intent(this,DemoService.class);
startService(intent);</pre>
<p>the <strong>startService(intent)</strong> method causes the onStart() method of the service to be called, so the service can execute it&#8217;s work like this:</p>
<pre>public class DemoService extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		doSomething();
	}

	public void doSomething(){
		// do some work
	}

}</pre>
<p>the service will keep running until it stops itself via stop <strong>stopSelf()</strong> after finishing work:</p>
<pre>@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		doSomething();
		stopSelf();
	}</pre>
<p>or it can be stopped from the activity via <strong>stopService(Intent intent)</strong>.</p>
<h3>Binding to a service through an Binder object:</h3>
<p>As the service runs in the same process of the application the service has only one instance (singleton) instance running. you may want to keep reference to this instance to perform periodical tasks or to call the service methods themselves.</p>
<p>to make the service bind-able we extends <strong>Binder</strong> class and return an instance of it in the service&#8217;s <strong>onBind(Intent intent)</strong> method:</p>
<pre>public class DemoService extends Service {

	private final IBinder binder = new LocalBinder();
	@Override
	public IBinder onBind(Intent arg0) {
		return binder;
	}

	public class LocalBinder extends Binder {
		DemoService getService() {
            return DemoService.this;
        }
    }

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		doSomething();
		stopSelf();
	}

	public void doSomething(){
		// do something
	}

}</pre>
<p>then we bind the service from our activity by first creating a ServiceConnection object to handle the service connection/disconnection then binding to the service by an intent like this:</p>
<pre>public class MainActivity extends Activity {

	DemoService mService;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    ServiceConnection serviceConn=new ServiceConnection() {

                /**
                * service unbound, release from memory
                **/
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService=null;
		}

                /**
                * service is bound, start it's work
                **/
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService=((LocalBinder)service).getService();
			mService.doSomething();

		}
	};

    @Override
    protected void onResume() {
    	super.onResume();
        // bind to the service by an intent
    	Intent intent=new Intent(this,DemoService.class);
        // AUTO CREATE: creates the service and gives it an importance so that it won't be killed
        // unless any process bound to it (our activity in this case) is killed to
    	bindService(intent, serviceConn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
    	super.onDestroy();
        / unbind the service whena ctivity is destroyed
    	unbindService(serviceConn);
    }
}</pre>
<p>notice that we <strong>unbind</strong> the service in the activity&#8217;s <strong>onDestroy()</strong> method to disconnect from the service and stop it from executing any further</p>
<p>and that&#8217;s was all about Android services, stay tuned for another Android tutorial.</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-development-android-services/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Android App Development: Parsing Web Service Response part 1</title>
		<link>http://mobileorchard.com/android-app-development-parsing-web-service-response-part-1/</link>
		<comments>http://mobileorchard.com/android-app-development-parsing-web-service-response-part-1/#comments</comments>
		<pubDate>Wed, 15 Jun 2011 17:00:40 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7656</guid>
		<description><![CDATA[In a previous last post we saw how to call REST and SOAP web services. The web service reponse can be one of the following: XML. SOAP. JSON. Parsing XML Android offers three types of XML parsers: DOM Parser. Pull Parser. SAX Parser. we&#8217;ll demonstrate each using the following xml example: &#60;?xml version="1.0"?&#62; &#60;person&#62; &#60;firstname&#62;Jack&#60;/firstname&#62; [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>In a previous last <a href="http://mobileorchard.com/android-app-development-calling-web-services/">post</a> we saw how to call REST and SOAP web services. The web service reponse can be one of the following:</p>
<ol>
<li><strong>XML.</strong></li>
<li><strong>SOAP.</strong></li>
<li><strong>JSON.</strong></li>
</ol>
<h2>Parsing XML</h2>
<p>Android offers three types of XML parsers:</p>
<ol>
<li>DOM Parser.</li>
<li>Pull Parser.</li>
<li>SAX Parser.</li>
</ol>
<p>we&#8217;ll demonstrate each using the following xml example:</p>
<pre>&lt;?xml version="1.0"?&gt;
&lt;person&gt;
    &lt;firstname&gt;Jack&lt;/firstname&gt;
    &lt;lastname&gt;smith&lt;/lastname&gt;
    &lt;age&gt;28&lt;/age&gt;
&lt;/person&gt;</pre>
<p>which we need to parse to create an object from <strong>Person</strong> class:</p>
<pre>public class Person{
    	public String firstName;
    	public String lastName;
    	public int age;
    }</pre>
<h2>Parsing the response with DOM Parser:</h2>
<p>Android provides org.w3c.dom library that contains classes used to parse xml by constructing a document and<br />
matching each node to parse the info.<br />
to parse our example response with DOM parser, we implement a function like this</p>
<pre>void parseByDOM(String response) throws ParserConfigurationException, SAXException, IOException{
    	Person person=new Person();
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    	DocumentBuilder db = dbf.newDocumentBuilder();
    	Document doc = db.parse(new InputSource(new StringReader(response)));
    	// normalize the document
    	doc.getDocumentElement().normalize();
    	// get the root node
    	NodeList nodeList = doc.getElementsByTagName("person");
    	Node node=nodeList.item(0);
    	// the  node has three child nodes
    	for (int i = 0; i &lt; node.getChildNodes().getLength(); i++) {
    	Node temp=node.getChildNodes().item(i);
    	if(temp.getNodeName().equalsIgnoreCase("firstname")){
    		person.firstName=temp.getTextContent();
    	}
    	else if(temp.getNodeName().equalsIgnoreCase("lastname")){
    		person.lastName=temp.getTextContent();
    	}
    	else if(temp.getNodeName().equalsIgnoreCase("age")){
    		person.age=Integer.parseInt(temp.getTextContent());
    	}

    	}

    	Log.e("person", person.firstName+ " "+person.lastName+" "+String.valueOf(person.age));
    }</pre>
<p>The previous method is good, it retrieves the info correctly, but it requires that you are familiar with the xml structure so that you know the order of each xml node.<br />
luckily Android provides a better approach of parsing using <strong>SAX</strong> parser.</p>
<h2>Parsing the response with SAX Parser:</h2>
<p>Android provides <strong>org.xml.sax</strong> package that has that provides the event-driven SAX parser.<br />
to parse the previous response with SAX parser, we have to create a class extending <strong>DefaultHandler</strong> and override the following methods:</p>
<ol>
<li><strong>startDocument():</strong> invoked when the xml document is open, there we can initialize any member variables.</li>
<li><strong>startElement(String uri, String localName, String qName,				Attributes attributes):</strong> invoked when the parser encounters a xml node, here we can initialize specific instances of our person object.</li>
<li><strong>endElement(String uri, String localName, String Name):</strong> invoked when the parser reaches the closing of a xml tag. here the element value would have been completely read.</li>
<li><strong>characters(char[] ch, int start, int length):</strong> this method is called when the parser reads characters of a node value.</li>
</ol>
<p>so our parsing class will be like this:</p>
<pre>/*
	 * SAX parser to parse persons response
	 */
	public class PersonParser extends DefaultHandler
	{

		// arraylist to store person objects
		ArrayList persons;
		// temporary person object
		Person tempPerson;
		// string builder acts as a buffer
		StringBuilder builder;

		/**
		 * Initialize the arraylist
		 * @throws SAXException
		 */
		@Override
		public void startDocument() throws SAXException {
			pesons=new ArrayList();

		}

		/**
		 * Initialize the temp person object which will hold the parsed info
		 * and the string builder that will store the read characters
		 * @param uri
		 * @param localName
		 * @param qName
		 * @param attributes
		 * @throws SAXException
		 */
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {

			if(localName.equalsIgnoreCase.equals("person")){
				tempPerson=new Person();
				builder=new StringBuilder();
			}

		}
		/**
		 * Finished reading the person tag, add it to arraylist
		 * @param uri
		 * @param localName
		 * @param qName
		 * @throws SAXException
		 */
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			// finished reading a person, add it to the arraylist
			if(localName.toLowerCase().equals("person"))
			{
				this.persons.add(tempPerson);
			}
			// finished reading "firstname" tag assign it to the temp person
			else if(localName.toLowerCase().equals("firstname")){
				tempPerson.firstName=builder.toString();
			}
			// finished reading "lastname" tag assign it to the temp person
			else if(localName.toLowerCase().equals("lastname")){
				tempPerson.lastName=builder.toString();
			}
			// finished reading "age" tag assign it to the temp person
			else if(localName.toLowerCase().equals("age")){
				tempPerson.age=Integer.parseInt(builder.toString());
			}
		}

		/**
		 * Read the value of each tag
		 * @param ch
		 * @param start
		 * @param length
		 * @throws SAXException
		 */
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			// read the characters and append them to the buffer
			String tempString=new String(ch, start, length);
			 builder.append(tempString);
		}
	}</pre>
<p>the code is pretty easy, the parser iterates over each node, you check the current node name and take an action.</p>
<p>then we call the parser like this:</p>
<pre> public ArrayList getPersons(final String response) throws ParserConfigurationException, SAXException, IOException
	{
		BufferedReader br=new BufferedReader(new StringReader(response));
		InputSource is=new InputSource(br);
		PersonParser parser=new PersonParser();
		SAXParserFactory factory=SAXParserFactory.newInstance();
   		SAXParser sp=factory.newSAXParser();
   		XMLReader reader=sp.getXMLReader();
   		reader.setContentHandler(parser);
   		reader.parse(is);
   		ArrayList persons=parser.persons;

		return persons;

	}</pre>
<h2>Parsing JSON respone:</h2>
<p>what if our repspone was <strong>JSON</strong> instead of xml. it would be something like this:</p>
<pre>"persons"
[
{
"person"{
"firstName": "John",
     "lastName": "Smith",
     "age": 25
}
}
{
"person"{
"firstName": "Catherine",
     "lastName": "Jones",
     "age": 35
}
}
]</pre>
<p>this response is a <strong>JSON Array</strong> with the name &#8220;persons&#8221;, this array consists of &#8220;person&#8221; <strong>JSON Object</strong>s.<br />
to parse such a reponse:</p>
<pre>public ArrayList&lt;Person&gt; getMessage(String response){
		JSONObject jsonResponse;
		ArrayList&lt;Person&gt; arrPersons=new ArrayList&lt;Person&gt;;
		try {
			// obtain the reponse
			jsonResponse = new JSONObject(response);
			// get the array
			JSONArray persons=jsonResponse.optJSONArray("persons");
			// iterate over the array and retrieve single person instances
			for(int i=0;i&lt;persons.length();i++){
				// get person object
				JSONObject person=persons.getJSONObject(i);
				// get first name
				String firstname=person.optString("firstname");
				// get last name
				String lastname=person.optString("lastname");
				// get the age
				int age=person.optInt("age");

				// construct the object and add it to the arraylist
				Person p=new Person();
				p.firstName=firstname;
				p.lastName=lastname;
				p.age=age;
				arrPersons.add(p);
			}

		} catch (JSONException e) {

			e.printStackTrace();
		}

		return arrPersons;
	}</pre>
<p>much easier than the previous methods.<br />
notice that we used the methods <strong>optJSONArray,optString,optInt</strong> instead of using <strong>getString,getInt</strong> because the opt methods return empty strings or zero integers if no elements are found. while the get methods throw an exception if the element is not found.</p>
<p>and that was all about parsing web service reponses, stay tuned next week for another tutorial</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-development-parsing-web-service-response-part-1/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Android vs iOS:  A Freemium Game Comparison</title>
		<link>http://mobileorchard.com/android-vs-ios-a-freemium-game-comparison/</link>
		<comments>http://mobileorchard.com/android-vs-ios-a-freemium-game-comparison/#comments</comments>
		<pubDate>Thu, 26 May 2011 17:00:44 +0000</pubDate>
		<dc:creator>Matt Tubergen</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Freemium]]></category>
		<category><![CDATA[iOS vs Android app development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7530</guid>
		<description><![CDATA[Matt Tubergen heads Recharge Studios, a wholly owned subsidiary of W3i that invests in the development and marketing/distribution of freemium mobile games.  W3i is a market leader in distributing and monetizing apps with over 500 million apps distributed for W3i clients. Recharge Studios is actively seeking new investment opportunities, if you have a great idea [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p><em>Matt Tubergen heads <a href="http://www.rechargestudios.com/?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Mobile%20Orchard" target="_blank">Recharge Studios</a>, a wholly owned subsidiary of <a href="http://www.w3i.com/mobile-apps.aspx?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Mobile%20Orchard" target="_blank">W3i</a> that invests in the development and marketing/distribution of freemium mobile games.  W3i is a market leader in distributing and monetizing apps with over 500 million apps distributed for W3i clients. Recharge Studios is actively seeking new investment opportunities, if you have a great idea for a game <a href="http://www.rechargestudios.com/contact/?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Mobile%20Orchard" target="_blank">contact us</a>.</em></p>
<p>Everywhere we go we read about the battle between Android and iOS. It’s simply impossible to get away from the conversation of which platform is better, where’s the money, which monetizes better, what the cost of porting is and even which OS is sexier…  Setting all the noise aside I wanted to do a simple comparison to see what the actual popularity is for freemium on each platform.</p>
<p>In my search I choose to do a simple count of the top grossing free apps. I also segregated the counts out by relative deck placement (i.e. top 10 apps vs. top 200).</p>
<p>iOS has twice the amount of freemium apps in the top 200 grossing yet both have similar ratios in the top 10 grossing. What does this tell me? Freemium opportunities on Android exist, but the market has yet to meet the demand. See below for full details.</p>
<div id="attachment_7531" class="wp-caption aligncenter" style="width: 587px"><a rel="attachment wp-att-7531" href="http://mobileorchard.com/android-vs-ios-a-freemium-game-comparison/android-v-ios-freemium/"><img class="size-full wp-image-7531" src="http://mobileorchard.com/wp-content/uploads/2011/05/android-v-ios-freemium.png" alt="Android versus iOS market share for freemium game apps" width="577" height="496" /></a><p class="wp-caption-text">Android versus iOS market share for freemium game apps</p></div>
<p><strong>Why go freemium on Android?</strong></p>
<p>Beyond the fact that freemium has exploded on iOS, there are many other reasons to go freemium on Android. The first and foremost reason to move your business model to Android is due to the ramped increase in piracy. I have heard multiple horror stories from AAA premium developers that for every 1 paid install they are seeing 100 pirated installs…. Ouch!</p>
<p>Other reasons for going freemium on Android include cost of user acquisition. Predictable user acquisition and discoverability is far worse in the Androids market comparable to iOS. Going free allows for a greater opportunity to increase distribution without risking cash for means of unknown distribution sources.</p>
<p>Do you have a question about freemium gaming or a topic you’d like us to explore? Let us know in the comments or catch us on twitter <a href="http://twitter.com/#%21/rechargestudios" target="_blank">@rechargestudios</a> or <a href="http://twitter.com/#%21/w3i" target="_blank">@w3i</a>.</p>
<p><em>Freemium Game Blogs are published in partnership with the series on <a href="http://blog.w3i.com/category/freemium-game-mechanics/?utm_source=Twitter&amp;utm_medium=Social&amp;utm_campaign=Blog" target="_blank">W3i’s corporate blog</a>. </em></p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-vs-ios-a-freemium-game-comparison/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Android App Development: Calling Web Services</title>
		<link>http://mobileorchard.com/android-app-development-calling-web-services/</link>
		<comments>http://mobileorchard.com/android-app-development-calling-web-services/#comments</comments>
		<pubDate>Wed, 25 May 2011 17:00:49 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7512</guid>
		<description><![CDATA[One of the most common functionalities required in mobile applications is to call a web service to retrieve data. This process involves requesting the web service with parameters, receiving the response and parsing it to obtain data. Today the most common web services types are SOAP and REST. Android does not provide a built in SOAP client, [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>One of the most common functionalities required in mobile applications is to call a web service to retrieve data. This process involves requesting the web service with parameters, receiving the response and parsing it to obtain data.<br />
Today the most common web services types are <strong>SOAP</strong> and <strong>REST</strong>. Android does not provide a built in SOAP client, there are many third party libraries that can be used, but we&#8217;ll see how to call a SOAP web service with native android APIs.</p>
<h2>Requesting SOAP web service:</h2>
<p>Before proceeding to the code, let&#8217;s take a look at the SOAP structure:</p>
<p><a rel="attachment wp-att-7513" href="http://mobileorchard.com/android-app-development-calling-web-services/soap_structure/"><img class="aligncenter size-full wp-image-7513" src="http://mobileorchard.com/wp-content/uploads/2011/05/soap_structure.png" alt="" width="220" height="235" /></a></p>
<p>A soap request can be something like this:</p>
<pre>POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.w3schools.com/GetItems"

&lt;?xml version="1.0"?&gt;
&lt;soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"&gt;
&lt;soap:Header&gt;
  &lt;m:Trans xmlns:m="http://www.w3schools.com/transaction/"
  soap:mustUnderstand="1"&gt;234
  &lt;/m:Trans&gt;
&lt;/soap:Header&gt;
&lt;soap:Body&gt;
  &lt;m:GetPrice xmlns:m="http://www.w3schools.com/prices"&gt;
    &lt;m:Item&gt;Apples&lt;/m:Item&gt;
  &lt;/m:GetPrice&gt;
&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;</pre>
<p>The SOAP request/response is sent as a <strong>SOAP Envelope</strong> which consists of a <strong>SOAP Header</strong> and a <strong>SOAP Body</strong>.</p>
<ol style="text-align: left;">
<li><strong>SOAP Header:</strong> optional component of the envelop, contains application specific information, such as authentication.</li>
<li><strong>SOAP Body:</strong> the actual message sent to/received from the service.</li>
<li>The header can contain a <strong>SOAP Action</strong> which identifies the desired function to be called by the service.</li>
</ol>
<h3>Calling the service:</h3>
<p>To call the  SOAP web service you have to do the following:<br />
<strong>First:</strong> construct the SOAP envelope manually like this:</p>
<pre>String envelope="&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;"+
"&lt;soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"</pre>
<pre>xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"</pre>
<pre>xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&gt;"+
  "&lt;soap:Body&gt;"+
    "&lt;GetItems xmlns=\"http://tempuri.org/\"&gt;"+
      "&lt;startDate&gt;%s&lt;/ startDate&gt;"+
      "&lt;getAll&gt;%s&lt;/getAll&gt;"+
    "&lt;/Items&gt;"+
  "&lt;/soap:Body&gt;"+
"&lt;/soap:Envelope&gt;";</pre>
<p>where <strong>%s</strong> are place holders where you substitute request parameters in like this</p>
<pre>String requestEnvelope=String.format(envelope, "10-5-2011","true");</pre>
<p><strong>Second:</strong> call the web service like this:<br />
<strong>Second:</strong> call the web service like this:</p>
<pre>String CallWebService(String url,
    String soapAction,
   String envelope)  {
  final DefaultHttpClient httpClient=new DefaultHttpClient();
  // request parameters
  HttpParams params = httpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, 10000);
     HttpConnectionParams.setSoTimeout(params, 15000);
     // set parameter
  HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

  // POST the envelope
  HttpPost httppost = new HttpPost(url);
  // add headers
     httppost.setHeader("soapaction", soapAction);
     httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

     String responseString="";
     try {

      // the entity holds the request
   HttpEntity entity = new StringEntity(envelope);
   httppost.setEntity(entity);

   // Response handler
   ResponseHandler&lt;string&gt; rh=new ResponseHandler&lt;string&gt;() {
    // invoked when client receives response
    public String handleResponse(HttpResponse response)
      throws ClientProtocolException, IOException {

     // get response entity
     HttpEntity entity = response.getEntity();

     // read the response as byte array
           StringBuffer out = new StringBuffer();
           byte[] b = EntityUtils.toByteArray(entity);

           // write the response byte array to a string buffer
           out.append(new String(b, 0, b.length));
           return out.toString();
    }
   };

   responseString=httpClient.execute(httppost, rh); 

  }
     catch (Exception e) {
      Log.v("exception", e.toString());
  }

     // close the connection
  httpClient.getConnectionManager().shutdown();
  return responseString;
 }</pre>
<p>After calling this function, you will have the response as a String, something like this:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"</pre>
<pre>xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt;
  &lt;soap:Body&gt;
    &lt;GetItemsResponse xmlns="http://tempuri.org/"&gt;
      &lt;GetItemsResult&gt;

        &lt;Items&gt;
          &lt;Item&gt;
            &lt;name&gt;string&lt;/name&gt;
            &lt;description&gt;string&lt;/ description &gt;
          &lt;/iPhoneCategory&gt;
          &lt;iPhoneCategory&gt;
            &lt;name&gt;string&lt;/name&gt;
            &lt;description&gt;string&lt;/ description &gt;
          &lt;/ Item &gt;
        &lt;/Items&gt;
      &lt;/GetItemsResult&gt;
    &lt;/ GetItemsResponse &gt;
  &lt;/soap:Body&gt;
&lt;/soap:Envelope&gt;</pre>
<p>This response needs to be parsed to extract the data.</p>
<h2>Requesting REST web service:</h2>
<p>REST web services are much simpler, you request the service by calling a URL with the parameters. like this</p>
<pre>http://example.com/resources/getitems</pre>
<p>an example of calling a REST web service:</p>
<pre>String callWebErvice(String serviceURL){
		// http get client
        	HttpClient client=new DefaultHttpClient();
        	HttpGet getRequest=new HttpGet();

        	try {
        		// construct a URI object
				getRequest.setURI(new URI(serviceURL));
			} catch (URISyntaxException e) {
				Log.e("URISyntaxException", e.toString());
			}

			// buffer reader to read the response
        	BufferedReader in=null;
        	// the service response
        	HttpResponse response=null;
			try {
				// execute the request
				response = client.execute(getRequest);
			} catch (ClientProtocolException e) {
				Log.e("ClientProtocolException", e.toString());
			} catch (IOException e) {
				Log.e("IO exception", e.toString());
			}
        	try {
				in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			} catch (IllegalStateException e) {
				Log.e("IllegalStateException", e.toString());
			} catch (IOException e) {
				Log.e("IO exception", e.toString());
			}
        	StringBuffer buff=new StringBuffer("");
        	String line="";
        	try {
				while((line=in.readLine())!=null)
				{
					buff.append(line);
				}
			} catch (IOException e) {
				Log.e("IO exception", e.toString());
				return e.getMessage();
			}

        	try {
				in.close();
			} catch (IOException e) {
				Log.e("IO exception", e.toString());
			}
        	// response, need to be parsed
        	return buff.toString();
	}</pre>
<p>&nbsp;</p>
<h2>Connecting to a web service over a Secure Sockets Layer (SSL): protocol:</h2>
<p>Android default <strong>HttpClinet</strong> does not support SSL connections, so if you have a secured web service, you need to connect to it via <strong>javax.net.ssl.HttpsURLConnection</strong>.<br />
if you want to call a SSL SOAP web service:</p>
<pre>String CallWebService(String url,
			 String soapAction,
			String envelope) throws IOException  {
		URL address=new URL(url);
		URLConnection connection=address.openConnection();
		HttpsURLConnection post=(HttpsURLConnection)connection;
		post.setDoInput(true);
		post.setDoOutput(true);
		post.setRequestMethod("POST");
		post.setRequestProperty("SOAPAction", soapAction);
		post.setRequestProperty( "Content-type", "text/xml; charset=utf-8" );
		post.setRequestProperty( "Content-Length", String.valueOf(envelope.length()));
		post.setReadTimeout(4000);

		OutputStream outStream=post.getOutputStream();
		Writer out=new OutputStreamWriter(outStream);
		out.write(envelope);
		out.flush();
		out.close();

		InputStream inStream = post.getInputStream();
		BufferedInputStream in = new BufferedInputStream(inStream,4);
		StringBuffer buffer=new StringBuffer();
		// read 4 bytes a time
		byte[] buffArray=new byte[4];
		int c=0;
			while((c=in.read(buffArray))!=-1){
				for(int i=0;i&lt;c;i++)
					buffer.append((char)buffArray[i]);
			}

			return buffer.toString();
	}</pre>
<p>In this post we saw how to request a web service, in the next post we&#8217;re going to see how to parser the different (SOAP, XML, JSon) types of responses.</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-development-calling-web-services/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Android App Development:Using Preferences</title>
		<link>http://mobileorchard.com/android-app-developmentusing-preferences/</link>
		<comments>http://mobileorchard.com/android-app-developmentusing-preferences/#comments</comments>
		<pubDate>Thu, 19 May 2011 17:00:26 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7497</guid>
		<description><![CDATA[We saw before that we can persist an application&#8217;s data using SQLite database. Android offers another way to store user&#8217;s data through using preferences. Android preferences is a key/value entries that store data that can be specific to a certain activity or shared among all activities within the application. the data are stored in a [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>We saw before that we can persist an application&#8217;s data using SQLite database. Android offers another way to store user&#8217;s data through using preferences.</p>
<p>Android preferences is a key/value entries that store data that can be specific to a certain activity or shared among all activities within the application.<br />
the data are stored in a xml file within the application folders.</p>
<h2>Saving Preferences</h2>
<p>We can save preferences in three ways:</p>
<ol style="text-align: left;">
<li>Preferences can be retrieved only by a single activity.</li>
<li>Preferences can be shared and retrieved among all activities within the application.</li>
<li>Preferences can be shared and retrieved through all applications on the device.</li>
</ol>
<h3>Saving Activity-level preferences:</h3>
<p>To save preferences that are accessed only from a single activity, we do it like this:</p>
<pre>SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=prefs.edit();
        editor.putString("pref 1", "some text");

        editor.commit();</pre>
<p>We get a <strong>SharedPreferences</strong> object by calling <strong>getPreferences(int mode)</strong> method which takes an integer value as a parameter, the mode value can be one of the following:</p>
<ol>
<li><strong>Context.MODE_PRIVATE (0)</strong>: a file creating mode that makes the created file only accessible by applications with the same user ID (access the file from the same application context, will desctribe later).</li>
<li><strong>Context.MODE_WORLD_READABLE (1)</strong>: file mode makes the file readable from other applications.</li>
<li><strong>Context.MODE_WORLD_WRITEABLE (2)</strong>: file mode allows other applications to write to the file.</li>
</ol>
<p>Then we get an instance of <strong>SharedPreferences.Editor </strong>and write the preference value with <strong>editor.putString(String key, String value)</strong> method.<br />
shared preferences allows you to insert preferences using the following methods:</p>
<ol>
<li><strong>editor.putBoolean(String key, boolean value).</strong></li>
<li><strong>editor.putFloat(String key,float value).</strong></li>
<li><strong>editor.putInt(String key, int value).</strong></li>
<li><strong>editor.putLong(String key, long value)</strong></li>
<li><strong>editor.putString(String key, String value)</strong></li>
</ol>
<p>Then we call <strong>edit.commit() </strong>to save the preferences to the file. commit returns a boolean indicating the result of saving, true if successful and false if failed.</p>
<h3>Reading preferences values:</h3>
<p>To read preferences values:</p>
<pre>SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
String val=prefs.getString("pref 1", "some text");</pre>
<p>We use sharedpreferences.getString(String key, String defaultValue) (or get boolean/float/int) to return the value stored with a specific key or defaultValue if not found.</p>
<h2>Saving Application-level preferences:</h2>
<p>To save preferences that can be retrieved from all activities in the application we do it like this:</p>
<pre>SharedPreferences prefs= getSharedPreferences("demopref", Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor=prefs.edit();
        editor.putString("demostring", "hello");
        editor.commit();</pre>
<p>Same as the code above, but the difference is that we give our preferences file a name (demopref in this case) so that other activities can reference that preferences file.</p>
<h2>Sharing preferences across applications:</h2>
<p>We can store preferences in one application and read them in another application, this is done reading the preferences file by loading them through the first application&#8217;s context.</p>
<p>Let&#8217;s assume we have two applications:</p>
<ol>
<li>Application 1 with package name &#8220;com.mina.prefdemo&#8221;.</li>
<li>Application2 with package name &#8220;com.mina.demoapp&#8221;.</li>
</ol>
<p>If application1 creates a preferences file with the name &#8220;demopref&#8221; and inserts a String preference with the key/value &#8220;demostring/hello&#8221;.<br />
now we access this file and value from application 2 like this:</p>
<pre>Context con;
  try {
   con = createPackageContext("com.minasamy.prefdemo", 0);
   SharedPreferences pref=con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
   String x=pref.getString("demostring", "not found");
   txt.setText(x);
  } catch (NameNotFoundException e) {
   Log.e(Tag, e.toString());
  }</pre>
<h3>Creating Preferences Activities:</h3>
<p>Android provides another nice way of presenting and saving preferences. you can create Activities that extend <strong>PreferenceActivity</strong>.<br />
PreferenceActivity is an activity that displays a set of built-in preferences related widgets that are defined in xml file.</p>
<p>The preference activity can be divided to several <strong>PreferenceCategory</strong> each containing a set of related preferences.<br />
The preferences widgets that Android provide are:</p>
<ol>
<li><strong>CheckBoxPreference:</strong> displays a check box widget.</li>
<li><strong>EditTextPreference:</strong> displays an EditText widget to save user prefs.</li>
<li><strong>RingtonePreference:</strong> displays a list with the  ringtones on the device.</li>
<li><strong>ListPreference:</strong> displays a list of key/value items.</li>
</ol>
<p>Each one of these preferences widgets is associated with a preference key. it&#8217;s value is persisted instantly as the widget selection changes.<br />
we can construct our preferences screen xml (saved in res/xml directory) layout like this:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;PreferenceCategory
    android:title="Catogory one"
    android:summary="sample summary"&gt;
        &lt;CheckBoxPreference
         android:title="Enable"
         android:key="pref_enable"
         android:summary="enables a preference"/&gt;
        &lt;EditTextPreference
        android:summary="Edit text prefrence"
        android:title="Edit"
        android:key="pref_edit"/&gt;

    &lt;/PreferenceCategory&gt;
    &lt;PreferenceCategory
    android:title="Category2"
    android:summary="sample summary"&gt;
        &lt;RingtonePreference
        android:key="pref_ring"
        android:title="Ringtones preference"/&gt;

        &lt;ListPreference
        android:key="pref_list"
        android:title="List Preference"
        android:dialogTitle="List Pref Dialog"
        android:entries="@array/pref_items"
        android:entryValues="@array/pref_items_values"/&gt;
    &lt;/PreferenceCategory&gt;</pre>
<p>Then from our activity:</p>
<pre>public class PrefActivity extends PreferenceActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.prefs);

	}
}</pre>
<p>The activity will look like this:</p>

<a href='http://mobileorchard.com/android-app-developmentusing-preferences/prefs1/' title='prefs1'><img width="150" height="150" src="http://mobileorchard.com/wp-content/uploads/2011/05/prefs1-150x150.png" class="attachment-thumbnail" alt="prefs1" /></a>
<a href='http://mobileorchard.com/android-app-developmentusing-preferences/prefs2/' title='prefs2'><img width="150" height="150" src="http://mobileorchard.com/wp-content/uploads/2011/05/prefs2-150x150.png" class="attachment-thumbnail" alt="prefs2" /></a>
<a href='http://mobileorchard.com/android-app-developmentusing-preferences/prefs3/' title='prefs3'><img width="150" height="150" src="http://mobileorchard.com/wp-content/uploads/2011/05/prefs3-150x150.png" class="attachment-thumbnail" alt="prefs3" /></a>
<a href='http://mobileorchard.com/android-app-developmentusing-preferences/prefs4/' title='prefs4'><img width="150" height="150" src="http://mobileorchard.com/wp-content/uploads/2011/05/prefs4-150x150.png" class="attachment-thumbnail" alt="prefs4" /></a>

<p>The <strong>ListPreference</strong> can be associated with String array resources as it&#8217;s key/value entries</p>
<pre>&lt;string-array name="pref_items"&gt;
    &lt;item&gt;Item1&lt;/item&gt;
    &lt;item&gt;Item2&lt;/item&gt;
    &lt;item&gt;Item3&lt;/item&gt;
    &lt;item&gt;Item4&lt;/item&gt;
    &lt;item&gt;Item5&lt;/item&gt;
    &lt;/string-array&gt;

    &lt;string-array name="pref_items_values"&gt;
    &lt;item&gt;1&lt;/item&gt;
    &lt;item&gt;2&lt;/item&gt;
    &lt;item&gt;3&lt;/item&gt;
    &lt;item&gt;4&lt;/item&gt;
    &lt;item&gt;5&lt;/item&gt;
    &lt;/string-array&gt;</pre>
<p>To reference the preference widgets programmatically:</p>
<pre>EditTextPreference pref_edit=(EditTextPreference)findPreference("pref_edit");</pre>
<p>And that&#8217;s was all about Android preferences. stay tuned for another tutorial next week</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-developmentusing-preferences/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Android App Development:Threading part 2: Async Tasks</title>
		<link>http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/</link>
		<comments>http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/#comments</comments>
		<pubDate>Wed, 11 May 2011 17:00:48 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7443</guid>
		<description><![CDATA[In the previous post we saw one way to deal with threads in Android, which is by using Handlers. In this post we&#8217;ll see how to use another technique which is using AsyncTask class. AsyncTask is an abstract class that provides several methods managing the interaction between the UI thread and the background thread. it&#8217;s [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>In the <a href="http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/">previous post</a> we saw one way to deal with threads in Android, which is by using <strong>Handlers</strong>. In this post we&#8217;ll see how to use another technique which is using <strong>AsyncTask</strong> class.</p>
<p><strong>AsyncTask </strong>is an abstract class that provides several methods managing the interaction between the UI thread and the background thread. it&#8217;s implementation is by creating a sub class that extends <strong>AsyncTask</strong> and implementing the different protected methods it provides.</p>
<p>Let&#8217;s demonstrate how to user <strong>AsyncTask</strong> by creating a simple activity that has two buttons and a progress bar:</p>
<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  &gt;
  &lt;Button
  android:id="@+id/btn"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Show Progress"
  &gt;&lt;/Button&gt;
  &lt;ProgressBar
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/progress"
  style="?android:attr/progressBarStyleHorizontal"
  &gt;&lt;/ProgressBar&gt;
  &lt;Button
  android:id="@+id/btnCancel"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Cancel"
  &gt;&lt;/Button&gt;
&lt;/LinearLayout&gt;</pre>
<p><a rel="attachment wp-att-7444" href="http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/asynctask/"><img class="aligncenter size-medium wp-image-7444" src="http://mobileorchard.com/wp-content/uploads/2011/05/asynctask-210x300.png" alt="" width="210" height="300" /></a></p>
<p>Here we have two buttons: one to start progress and the other to stop it.</p>
<h2>Creating the AsyncTask sub class:</h2>
<p>The first step in implementing AsyncTask is to create a sub class like this:</p>
<pre>class ProgressTask extends AsyncTask&lt;Params, Progress, Result&gt;{
}</pre>
<p>The AsyncTask declaration has three <a href="http://download.oracle.com/javase/1,5.0/docs/guide/language/varargs.html">Varargs</a> parameters which are:</p>
<ol>
<li>Params: parameter info passed to be used by the AsyncTask.</li>
<li>Progress: the type of progress that the task accomplishes.</li>
<li>The result returned after the AsyncTask finishes.</li>
</ol>
<p>These parameters are of type <strong>Varargs </strong>which provide the flexibility to pass dynamic sized arrays as parameters.</p>
<p>In our example our class will be like this:</p>
<pre>class ProgressTask extends AsyncTask&lt;Integer, Integer, Void&gt;{
}</pre>
<p>The parameter and the progress are of type Integer and the result is Void as our tasks does not return anthing (returns null).</p>
<p>The second step is overriding the protected methods defined by the <strong>AsyncTask </strong>class that handle the execution life cycle of the AsyncTask.</p>
<p>We have five methods to implement which are:</p>
<ol>
<li><strong>onPreExecute:</strong> the first method called in the AsyncTask, called on the UI thread.</li>
<li><strong>doInBackground</strong>: the method that executes the time consuming tasks and publish the task progress, executed in background thread.</li>
<li><strong>onProgressUpdate:</strong> method that updates the progress of the AsyncTask, run on the UI thread.</li>
<li><strong>onPostExecute:</strong> the final method that gets called after <strong>doInBackground</strong> finishes, here we can update the UI with the results of the AsyncTask.</li>
<li><strong>onCancelled:</strong> gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask.</li>
</ol>
<h3>Starting the AsyncTask:</h3>
<p>To start the AsyncTask we create an instance of it, then call the <strong>execute()</strong> method passing the initial parameters like this:</p>
<pre>ProgressTask task=new ProgressTask();
// start progress bar with initial progress 10
task.execute(10);</pre>
<h3>Implementing the AsyncTask:</h3>
<pre>class ProgressTask extends AsyncTask&lt;Integer, Integer, Void&gt;{

		@Override
		protected void onPreExecute() {
			// initialize the progress bar
			// set maximum progress to 100.
			progress.setMax(100);

		}

		@Override
		protected void onCancelled() {
			// stop the progress
			progress.setMax(0);

		}

		@Override
		protected Void doInBackground(Integer... params) {
			// get the initial starting value
			int start=params[0];
			// increment the progress
			for(int i=start;i&lt;=100;i+=5){
				try {
					boolean cancelled=isCancelled();
					//if async task is not cancelled, update the progress
					if(!cancelled){
						publishProgress(i);
						SystemClock.sleep(1000);

					}

				} catch (Exception e) {
					Log.e("Error", e.toString());
				}

			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// increment progress bar by progress value
			progress.setProgress(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// async task finished
			Log.v("Progress", "Finished");
		}

	}</pre>
<p>Here are the steps:</p>
<ol>
<li><strong>onPreExecute()</strong> method first gets called initializing the maximum value of the progress bar.</li>
<li><strong>doInBackground</strong>(Integer&#8230; params) methods gets called by obtaining the initial start value of the progress bar then incrementing the value of the progress bar every second and publishing the progress as long as the <strong>async task is not cancelled</strong>.</li>
<li><strong>onProgressUpdate(Integer&#8230; values)</strong> method is called each time progress is published from <strong>doInBackground</strong>, thus incrementing the progress bar.</li>
<li><strong>onPostExecute(Void result)</strong> is called after <strong>doInBackground </strong>finished execution.</li>
<li>void <strong>onCancelled()</strong> is called if <strong>task.cancel(true) </strong>is called from the UI thread. it may interrupt the execution preventing <strong>onPostExecute </strong>from being executed.</li>
</ol>
<p>The onClick handler of our buttons is like this:</p>
<pre>@Override
	public void onClick(View v) {
		ProgressTask task=new ProgressTask();
		switch(v.getId()){
		case R.id.btn:
			task.execute(10);
			break;
		case R.id.btnCancel:
			task.cancel(true);		
			break;
		}

	}</pre>
<h3><a rel="attachment wp-att-7445" href="http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/asynctask2/"><img class="aligncenter size-medium wp-image-7445" src="http://mobileorchard.com/wp-content/uploads/2011/05/asynctask2-209x300.png" alt="" width="209" height="300" /></a></h3>
<h3>The Difference between Handler and AsyncTask:</h3>
<p>After we saw both Handlers and AsyncTasks a question may evolve: what&#8217;s the difference between the two and when to use one of them over the other ?</p>
<p>The Handler is associated with the application&#8217;s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.</p>
<p>AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.</p>
<p>The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the <strong>MessageQueue</strong> in a specific order.</p>
<p>You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.</p>
<p>We hope you fund this tutorial on Android AsyncTask helpful, stay tuned for another tutorial next week.</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Android App Development:Threading part 1: Handlers</title>
		<link>http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/</link>
		<comments>http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/#comments</comments>
		<pubDate>Wed, 04 May 2011 17:00:08 +0000</pubDate>
		<dc:creator>Mina Samy</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Android App Development]]></category>

		<guid isPermaLink="false">http://mobileorchard.com/?p=7376</guid>
		<description><![CDATA[Multi-Threading concept is essential in most platforms. it provides maximum utilization of the processor. threading is used when the program executes time consuming processes (such as calling a web service) and to give a good user experience by unblocking the UI. Android provides threading techniques to perform time consuming tasks in a background thread with coordination with the [...]<p></p>
]]></description>
				<content:encoded><![CDATA[<p>Multi-Threading concept is essential in most platforms. it provides maximum utilization of the processor. threading is used when the program executes time consuming processes (such as calling a web service) and to give a good user experience by unblocking the UI.</p>
<p>Android provides threading techniques to perform time consuming tasks in a background thread with coordination with the UI thread to update the UI.</p>
<p>Android provides the following methods of threading:</p>
<ol style="text-align: left;">
<li><strong>Handlers.</strong></li>
<li><strong>Async. Tasks.</strong></li>
</ol>
<h2>Handlers:</h2>
<p>When you create an object from the <strong>Handler</strong> class, it processes</p>
<p><strong>Messages</strong> and <strong>Runnable</strong> objects associated with the current thread <strong>MessageQueue</strong>. the message queue holds the tasks to be executed in FIFO (First In First Out) mannser. you will need only ine <strong>Handler</strong> per activity where the background thread will communicate with to update the UI.</p>
<p>The Handler is associated with the thread from which it&#8217;s been created</p>
<p>We can communicate with the Handler by two methods:</p>
<ol>
<li><strong>Messages</strong>.</li>
<li><strong>Runnable</strong> objects.</li>
</ol>
<p>In this post we will demonstrate how to use both using a simple example which is updating the text of a TextView using multiple threads.</p>
<h3>Using Messages:</h3>
<p>The steps of using a Handler are as follows:</p>
<ol>
<li>You create a <strong>Handler</strong> object with an asscociated callbackmethod to handle the received messages (it is the method where the UI updatewill be done).</li>
<li>From the background thread you will need to send messages to thehandler.</li>
</ol>
<p>Here&#8217;s the code of our activity:</p>
<pre>public class MainActivity extends Activity {
TextView txt;
// our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {</pre>
<pre>//display each item in a single line
  txt.setText(txt.getText()+"Item "+System.getProperty("line.separator"));
     }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt=(TextView)findViewById(R.id.txt);
 }

 @Override
 protected void onStart() {
  super.onStart();
              // create a new thread
  Thread background=new Thread(new Runnable() {

   @Override
   public void run() {
    for(int i=0;i&lt;10;i++)
    {
     try {
      Thread.sleep(1000);        b.putString("My Key", "My Value: 

"+String.valueOf(i));
// send message to the handler with the current message handler          

handler.sendMessage(handler.obtainMessage());
     } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });

  background.start();
 }
}</pre>
<p>After running the following code the TextView will display the following,</p>
<p>Each second a new line is written:</p>
<p><a rel="attachment wp-att-7377" href="http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/threading/"><img class="aligncenter size-medium wp-image-7377" src="http://mobileorchard.com/wp-content/uploads/2011/05/Threading-213x300.png" alt="" width="213" height="300" /></a><br />
This example is pretty basic, it just sends the same message for a number of times.</p>
<p>What if we want the message sent to hold data that&#8217;s changed each time the message is sent, the answer is to use <strong>Message.setData(Bundle bundle)</strong> method by creating a <strong>Bundle</strong> object and adding the data to it like this:</p>
<pre>public class MainActivity extends Activity {
 TextView txt;
 // our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   // get the bundle and extract data by key
   Bundle b = msg.getData();
   String key = b.getString("My Key");
   txt.setText(txt.getText() + "Item " + key
   +System.getProperty("line.separator"));
  }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt = (TextView) findViewById(R.id.txt);
 }

 @Override
 protected void onStart() {
  super.onStart();
  // create a new thread
  Thread background = new Thread(new Runnable() {

   @Override
   public void run() {
    for (int i = 0; i &lt; 10; i++) {
     try {
      Thread.sleep(1000);
                                        Message msg = new Message();
      Bundle b = new Bundle();
      b.putString("My Key", "My Value: " + String.valueOf(i));
      msg.setData(b);
      // send message to the handler with the current message handler
      handler.sendMessage(msg);
           } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });

  background.start();
 }
}</pre>
<p>We put a string to the bundle and send a message with that bundle. in the handler method we receive the bundle and get the value with the predefined key.</p>
<p>After executing that code the text view would look like this:</p>
<h3><a rel="attachment wp-att-7378" href="http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/threading2/"><img class="aligncenter size-medium wp-image-7378" src="http://mobileorchard.com/wp-content/uploads/2011/05/Threading2-212x300.png" alt="" width="212" height="300" /></a><br />
Using Runnables:</h3>
<p>another way to use Handlers is to pass them a <strong>Runnable</strong> by using the</p>
<p><strong>Handler.post()</strong> method like this:</p>
<pre>Runnable r=new Runnable() {

   @Override
   public void run() {
    txt.setText("Runnable");

   }
  };

  handler.post(r);</pre>
<p>This will add the <strong>Runanble</strong> object to the message queue to be executed by the handler.</p>
<h3>Sending Messages in a timely manner:</h3>
<p>we can use handlers to send messages or post runnables at time intervals using</p>
<p>The following methods:</p>
<ol>
<li><strong>handler.sendEmptyMessageAtTime(int what,long uptimeMillis):</strong>sends an<br />
empty message at a specific time in milli-seconds, can be defined by using the<br />
<strong>SystemClock.uptimeMillis()</strong> method to get the time since the device boot<br />
in milli-seconds and concatinating to it.</li>
<li><strong>handler.sendEmptyMessageDelayed(int what,long delayMillis):</strong>sends an<br />
empty message after a certain amount of time in milli-seconds.</li>
<li><strong>handler.sendMessageAtTime(Message msg,long uptimeMillis).</strong></li>
<li><strong>handler.sendMessageDelayed(Message msg,long delayMillis).</strong></li>
<li><strong>handler.postAtTime(Runnable r,long uptimeMillis).</strong></li>
<li><strong>handler.postAtTime(Runnable r,Object token,long uptimeMillis):</strong>posts a<br />
runnable with an object as a distinguishing token.</li>
<li><strong>handler.postDelayed(Runnable r,long delayMillis).</strong></li>
</ol>
<p>All the above messages return a boolean indicating whether the message or the runnable has been placed successfully in the message queue.</p>
<h3>Removing Call backs:</h3>
<p>If you want to remove a runnable or a message from the message queue, you can use the following methods:</p>
<ol style="text-align: left;">
<li><strong>handler.removeCallbacks(Runnable r).</strong></li>
<li><strong>handler.removeCallbacks(Runnable r,Object token).</strong></li>
<li><strong>handler.removeCallbacksAndMessages(Object token).</strong></li>
<li><strong>handler.removeMessages(int what).</strong></li>
<li><strong>handler.removeMessages(int what,Object object)</strong></li>
</ol>
<p>That&#8217;s was all about handlers, stay tuned for another tutorial next week.</p>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
