<?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>devahead BLOG</title>
	<atom:link href="http://www.devahead.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.devahead.com/blog</link>
	<description>Adobe Flex, Flash Platform and everything else about software development from a developer&#039;s point of view</description>
	<lastBuildDate>Thu, 26 Jan 2012 23:27:11 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Saving the Android WebView cache on the SD card</title>
		<link>http://www.devahead.com/blog/2012/01/saving-the-android-webview-cache-on-the-sd-card/</link>
		<comments>http://www.devahead.com/blog/2012/01/saving-the-android-webview-cache-on-the-sd-card/#comments</comments>
		<pubDate>Thu, 26 Jan 2012 23:27:11 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[external memory]]></category>
		<category><![CDATA[SD card]]></category>
		<category><![CDATA[WebView]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=79</guid>
		<description><![CDATA[It could be useful to save the cache of an Android WebView on the SD card (or integrated external memory) especially for devices with a limited amount of internal memory, but how can you do that? Well, it&#8217;s simple. You know that some Android browsers already do it and here I&#8217;m going to tell you [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/AndroidWebViewCacheOnSD/AndroidWebViewCacheOnSD.zip">Source code</a></span></div>
<p style="padding-top:10px;">It could be useful to save the cache of an Android <em><a href="http://developer.android.com/reference/android/webkit/WebView.html">WebView</a></em> on the SD card (or integrated external memory) especially for devices with a limited amount of internal memory, but how can you do that? Well, it&#8217;s simple. You know that some Android browsers already do it and here I&#8217;m going to tell you a way to do it in your own app as well. This solution is made to work with Android 2.1 and higher, so I&#8217;m not going to use the API that was introduced only in a later version of the OS.</p>
<p><strong>The key is the <em><a href="http://developer.android.com/reference/android/content/ContextWrapper.html#getCacheDir()">getCacheDir</a></em> method of the <em><a href="http://developer.android.com/reference/android/content/ContextWrapper.html">ContextWrapper</a> class</em></strong>. This is what is used by the cache manager to decide where to store the cache files. <strong>The behavior is slightly different for Android 2.1 and Android 2.2 and higher</strong>, so we&#8217;ll also keep this in mind.</p>
<p>I&#8217;ll explain everything going through the source code of the example application that you can download through the link on top of this post. Let&#8217;s start with the mainfest file:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	package=&quot;com.devahead.androidwebviewcacheonsd&quot;
	android:versionCode=&quot;1&quot;
	android:versionName=&quot;1.0&quot;&gt;

	&lt;uses-sdk android:minSdkVersion=&quot;7&quot;/&gt;

	&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;/&gt;
	&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
	&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;

	&lt;application
		android:icon=&quot;@drawable/ic_launcher&quot;
		android:label=&quot;@string/app_name&quot;
		android:name=&quot;com.devahead.androidwebviewcacheonsd.ApplicationExt&quot;&gt;
		&lt;activity
			android:name=&quot;.MainActivity&quot;
			android:label=&quot;@string/app_name&quot;&gt;
			&lt;intent-filter&gt;
				&lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt;
				&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt;
			&lt;/intent-filter&gt;
		&lt;/activity&gt;
		&lt;activity
			android:name=&quot;.SecondActivity&quot;
			android:label=&quot;Second activity&quot;/&gt;
	&lt;/application&gt;

&lt;/manifest&gt;
</pre>
</div>
<p>Here we have the permissions to write to the SD (the external storage) and access the web. We also have a custom <em><a href="http://developer.android.com/reference/android/app/Application.html">Application</a></em> class extension called <em>ApplicationExt</em> and a couple of activities, <em>MainActivity</em> and <em>SecondActivity</em>.</p>
<p>The <em>ApplicationExt</em> class is where most of the things are done to have the cache on the SD:</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.androidwebviewcacheonsd;

import java.io.File;

import android.app.Application;
import android.os.Environment;

public class ApplicationExt extends Application
{
	// NOTE: the content of this path will be deleted
	//       when the application is uninstalled (Android 2.2 and higher)
	protected File extStorageAppBasePath;

	protected File extStorageAppCachePath;

	@Override
	public void onCreate()
	{
		super.onCreate();

		// Check if the external storage is writeable
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
		{
			// Retrieve the base path for the application in the external storage
			File externalStorageDir = Environment.getExternalStorageDirectory();

			if (externalStorageDir != null)
			{
				// {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd
				extStorageAppBasePath = new File(externalStorageDir.getAbsolutePath() +
					File.separator + &quot;Android&quot; + File.separator + &quot;data&quot; +
					File.separator + getPackageName());
			}

			if (extStorageAppBasePath != null)
			{
				// {SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd/cache
				extStorageAppCachePath = new File(extStorageAppBasePath.getAbsolutePath() +
					File.separator + &quot;cache&quot;);

				boolean isCachePathAvailable = true;

				if (!extStorageAppCachePath.exists())
				{
					// Create the cache path on the external storage
					isCachePathAvailable = extStorageAppCachePath.mkdirs();
				}

				if (!isCachePathAvailable)
				{
					// Unable to create the cache path
					extStorageAppCachePath = null;
				}
			}
		}
	}

	@Override
	public File getCacheDir()
	{
		// NOTE: this method is used in Android 2.2 and higher

		if (extStorageAppCachePath != null)
		{
			// Use the external storage for the cache
			return extStorageAppCachePath;
		}
		else
		{
			// /data/data/com.devahead.androidwebviewcacheonsd/cache
			return super.getCacheDir();
		}
	}
}
</pre>
</div>
<p>In the <em>onCreate</em> method we start by checking if the external storage is actually mounted and we can write on it, then we build the <strong>base path of the app</strong> on the external storage. This path is <em>{SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd</em> because <em>com.devahead.androidwebviewcacheonsd</em> is the package declared in the manifest file and using this path structure makes sure that the entire path and all its content will be automatically deleted by Android 2.2 and higher in case the app is uninstalled avoiding to have garbage files on the SD. Note that this works only in Android 2.2 and higher, while in Android 2.1 the path will not be deleted by the OS so you&#8217;ll have to deal with it on your own. The full path for the cache files will be <em>{SD_PATH}/Android/data/com.devahead.androidwebviewcacheonsd/cache</em>, so the base path plus the <em>cache</em> directory. We must also make sure that the path is actually available before using it, so we create all the directories with the <em><a href="http://developer.android.com/reference/java/io/File.html#mkdirs()">mkdirs</a></em> method in case they don&#8217;t already exist.</p>
<p>Now that we have the cache path on the SD, we&#8217;re ready to use it and all we have to do is override the <em>getCacheDir</em> method inside our <em>ApplicationExt</em> class. This method is invoked by the cache manager when the application is started so basically we&#8217;re saying that the cache will be stored on the SD if it&#8217;s available and writeable, while we use the default path in case we&#8217;re allowed to use only the internal memory. Android stores all the cache data for our app in the <em>/data/data/com.devahead.androidwebviewcacheonsd/cache</em> directory by default on the internal memory.</p>
<p>We&#8217;re done with the implementation for Android 2.2 and higher, but what about Android 2.1? For that version of the OS the cache manager doesn&#8217;t use the <em>getCacheDir</em> method of the <em>Application</em> context, but it uses the one of the <em>Activity</em> context instead. So <strong>to make our solution work also with Android 2.1, we must override the <em>getCacheDir</em> method inside our activities</strong>.</p>
<p>To immediately understand how it works with Android 2.1, let&#8217;s take a look at the activities of the example application. We start with the <em>MainActivity</em>: <span id="more-79"></span></p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;
	android:orientation=&quot;vertical&quot;&gt;

  &lt;Button android:id=&quot;@+id/startSecondActivityBtn&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_gravity=&quot;center_horizontal&quot;
    android:text=&quot;Start second activity&quot;/&gt;

	&lt;WebView android:id=&quot;@+id/webView&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;fill_parent&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>There&#8217;s simply a button to start the <em>SecondActivity</em> and a <em>WebView</em> to test our solution. The code for <em>MainActivity</em> looks like this:</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.androidwebviewcacheonsd;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener
{
	protected WebView webView;
	protected Button startSecondActivityBtn;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		webView = ((WebView)findViewById(R.id.webView));
		startSecondActivityBtn = ((Button)findViewById(R.id.startSecondActivityBtn));

		// Set the listener
		startSecondActivityBtn.setOnClickListener(this);

		// Initialize the WebView
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setScrollbarFadingEnabled(true);
		webView.getSettings().setLoadsImagesAutomatically(true);

		// Load the URLs inside the WebView, not in the external web browser
		webView.setWebViewClient(new WebViewClient());

		webView.loadUrl(&quot;http://www.google.com&quot;);
	}

	@Override
	protected void onDestroy()
	{
		// Clear the cache (this clears the WebViews cache for the entire application)
		webView.clearCache(true);

		super.onDestroy();
	}

	@Override
	public File getCacheDir()
	{
		// NOTE: this method is used in Android 2.1

		return getApplicationContext().getCacheDir();
	}

	@Override
	public void onClick(View v)
	{
		if (v == startSecondActivityBtn)
		{
			Intent intent = new Intent(this, SecondActivity.class);
			startActivity(intent);
		}
	}
}
</pre>
</div>
<p>As you can see, the <em>getCacheDir</em> method inside the activity simply calls the same method in the <em>Application</em> context, that means that the <em>ApplicationExt</em> method is called. We&#8217;ll have to do this for every activity in the app to make sure the cache path is redirected correctly in Android 2.1, but actually in my tests I found that it looks like the cache manager calls the <em>getCacheDir</em> method inside the first activity that initializes a <em>WebView</em> (if <em>MainActivity</em> doesn&#8217;t use a <em>WebView</em>, but only <em>SecondActivity</em> does, then the <em>getCacheDir</em> method of <em>SecondActivity</em> will be called by the cache manager and not the one of <em>MainActivity</em>), anyway I think it&#8217;s a good idea to make sure the cache directory is consistent across all the activities of the application.</p>
<p>In <em>MainActivity</em> there&#8217;s a button that starts <em>SecondActivity</em>. This is just another activity with a <em>WebView</em> that I used to test the calls to the <em>getCacheDir</em> method in Android 2.1 and see what happens if there&#8217;s a <em>WebView</em> also in <em>MainActivity</em> or not. This is the layout of <em>SecondActivity</em>:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;
	android:orientation=&quot;vertical&quot;&gt;

	&lt;WebView android:id=&quot;@+id/webView&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;fill_parent&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>And this is its source code:</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.androidwebviewcacheonsd;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SecondActivity extends Activity
{
	protected WebView webView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.second);

		webView = ((WebView)findViewById(R.id.webView));

		// Initialize the WebView
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setScrollbarFadingEnabled(true);
		webView.getSettings().setLoadsImagesAutomatically(true);

		// Load the URLs inside the WebView, not in the external web browser
		webView.setWebViewClient(new WebViewClient());

		webView.loadUrl(&quot;http://www.google.com&quot;);
	}

	@Override
	public File getCacheDir()
	{
		// NOTE: this method is used in Android 2.1

		return getApplicationContext().getCacheDir();
	}
}
</pre>
</div>

<p>It looks similar to the one of <em>MainActivity</em> and we override the <em>getCacheDir</em> method here as well. The main difference is that in <em>MainActivity</em> the cache of the <em>WebViews</em> is cleared inside the <em>onDestroy</em> method. Remember that whenever you call the <em><a href="http://developer.android.com/reference/android/webkit/WebView.html#clearCache(boolean)">clearCache</a></em> method you&#8217;re actually clearing the cache for all the <em>WebViews</em> of your application, not only the one that you used to invoke the method, so you must implement your own logic to clear the cache depending on the structure of your app.</p>
<p>This is all you have to do to write the cache of an Android <em>WebView</em> to the external memory. Remember that you&#8217;ll probably have to manage also the case when the external storage is unmounted during your app extecution by detecting the event and maybe giving a warning to the user. I hope you found this post useful and in case you&#8217;ve got more suggestions about this topic, feel free to write a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2012/01/saving-the-android-webview-cache-on-the-sd-card/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Preserving the state of an Android WebView on screen orientation change</title>
		<link>http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/</link>
		<comments>http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 14:58:41 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[orientation]]></category>
		<category><![CDATA[screen]]></category>
		<category><![CDATA[screen orientation change]]></category>
		<category><![CDATA[state]]></category>
		<category><![CDATA[WebView]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=75</guid>
		<description><![CDATA[If you&#8217;ve tried to use a WebView inside your app, you know that the standard behavior on screen orientation change is not satisfactory in most cases because the full state of the WebView is not preserved. Here I&#8217;m going to show you a possible implementation to keep the full state of the WebView every time [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/AndroidWebViewScreenOrientationChange/AndroidWebViewScreenOrientationChange.zip">Source code</a></span></div>
<p style="padding-top:10px;">If you&#8217;ve tried to use a <em><a href="http://developer.android.com/reference/android/webkit/WebView.html">WebView</a></em> inside your app, you know that the standard behavior on screen orientation change is not satisfactory in most cases because the full state of the <em>WebView</em> is not preserved. Here I&#8217;m going to show you a possible implementation to <strong>keep the full state of the <em>WebView</em> every time you rotate the screen</strong>. This is the same implementation I used in my own app (<strong><a href="http://market.android.com/details?id=com.devahead.fweblauncher.free">FWebLauncher</a></strong>) for the internal web browser.</p>
<h3>Standard implementation (the state is not completely preserved)</h3>
<p>Let&#8217;s start by taking a look at what a standard implementation would look like. This is how you would usually implement the state saving for a <em>WebView</em> according to the Android documentation:</p>
<div class="post-source-code">
<pre class="brush: java;">
public class StandardImplActivity extends Activity
{
	protected WebView webView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.standard_impl);

		// Retrieve UI elements
		webView = ((WebView)findViewById(R.id.webView));

		// Initialize the WebView
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setScrollbarFadingEnabled(true);
		webView.getSettings().setLoadsImagesAutomatically(true);

		// Load the URLs inside the WebView, not in the external web browser
		webView.setWebViewClient(new WebViewClient());

		if (savedInstanceState == null)
		{
			// Load a page
			webView.loadUrl(&quot;http://www.google.com&quot;);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);

		// Save the state of the WebView
		webView.saveState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);

		// Restore the state of the WebView
		webView.restoreState(savedInstanceState);
	}
}
</pre>
</div>
<p>So we call the <em><a href="http://developer.android.com/reference/android/webkit/WebView.html#saveState(android.os.Bundle)">saveState</a></em> and the <em><a href="http://developer.android.com/reference/android/webkit/WebView.html#restoreState(android.os.Bundle)">restoreState</a></em> methods in the <em><a href="http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState</a></em> and the <em><a href="http://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)">onRestoreInstanceState</a></em> methods of the <em><a href="http://developer.android.com/reference/android/app/Activity.html">Activity</a></em>.</p>
<p>The <em>WebView</em> is declared directly in the layout file for the activity:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;

	&lt;WebView android:id=&quot;@+id/webView&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;fill_parent&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>The main problem with this implementation is that, whenever you rotate the screen, the <em>WebView</em> is created again because the activity is destroyed and its <em>saveState</em> method doesn&#8217;t save the full state, but only a part of it like the URL of the page that was loaded and the browsing history. So it happens that for example the zoom and the scroll position are not preserved after the screen orientation change and sometimes the page is reloaded from the web.</p>
<h3>State preserving implementation (a possible solution)</h3>
<p>I tried many different solutions to preserve the full state of the <em>WebView</em> on screen rotation and the following one proved to be a reliable one that solves our problem. The main point is that <strong>the activity must not be destroyed and we must handle the screen orientation change by ourselves</strong>. Let&#8217;s start by taking a look at the layout file:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;

	&lt;FrameLayout android:id=&quot;@+id/webViewPlaceholder&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;fill_parent&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>You immediately notice the difference with the standard implementation. Here we don&#8217;t declare the <em>WebView</em> inside the layout file, but we declare a <strong>placeholder</strong> instead. It is the position where our <em>WebView</em> will be placed inside the activity.</p>
<p>Also the code inside the activity will be different of course and here it is: <span id="more-75"></span></p>
<div class="post-source-code">
<pre class="brush: java;">
public class StatePreservingImplActivity extends Activity
{
	protected FrameLayout webViewPlaceholder;
	protected WebView webView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.state_preserving_impl);

		// Initialize the UI
		initUI();
	}

	protected void initUI()
	{
		// Retrieve UI elements
		webViewPlaceholder = ((FrameLayout)findViewById(R.id.webViewPlaceholder));

		// Initialize the WebView if necessary
		if (webView == null)
		{
			// Create the webview
			webView = new WebView(this);
			webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			webView.getSettings().setSupportZoom(true);
			webView.getSettings().setBuiltInZoomControls(true);
			webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
			webView.setScrollbarFadingEnabled(true);
			webView.getSettings().setLoadsImagesAutomatically(true);

			// Load the URLs inside the WebView, not in the external web browser
			webView.setWebViewClient(new WebViewClient());

			// Load a page
			webView.loadUrl(&quot;http://www.google.com&quot;);
		}

		// Attach the WebView to its placeholder
		webViewPlaceholder.addView(webView);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		if (webView != null)
		{
			// Remove the WebView from the old placeholder
			webViewPlaceholder.removeView(webView);
		}

		super.onConfigurationChanged(newConfig);

		// Load the layout resource for the new configuration
		setContentView(R.layout.state_preserving_impl);

		// Reinitialize the UI
		initUI();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);

		// Save the state of the WebView
		webView.saveState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);

		// Restore the state of the WebView
		webView.restoreState(savedInstanceState);
	}
}
</pre>
</div>
<p>We need to change also the <em>AndroidManifest.xml</em> file to intercept the configuration changes inside the activity:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;activity
	android:name=&quot;.StatePreservingImplActivity&quot;
	android:configChanges=&quot;keyboard|keyboardHidden|orientation&quot;
	android:label=&quot;State preserving implementation&quot;/&gt;
</pre>
</div>
<p>In the <em>android:configChanges</em> attribute we are telling the system that we don&#8217;t want the activity to be restarted when the declared configuration changes happen, but we want to handle the configuration changes by ourselves through the <em><a href="http://developer.android.com/reference/android/app/Activity.html#onConfigurationChanged(android.content.res.Configuration)">onConfigurationChanged</a></em> method that will be called every time there is a change.</p>
<p>When the activity is created we initialize its content with the current layout and we initialize the user interface with the <em>initUI</em> method. That&#8217;s where the <em>WebView</em> is created, stored in the <em>webView</em> class field and then attached to the <em>webViewPlaceholder</em> element filling its space completely. Every time the screen is rotated, the <em>onConfigurationChanged</em> method is called so we remove the <em>WebView</em> from its current placeholder first, then we load the new activity layout (we can define a different layout for the portrait and the landscape configuration) and reinitialize the UI. After a configuration change, the activity instance is still the same because it has not been destroyed. The <em>initUI</em> method retrieves the new placeholder instance while the <em>WebView</em> instance is still the same because the <em>webView</em> class field is not changed, so the <em>WebView</em> is not created again and all we have to do is attach the old <em>WebView</em> to the new <em>webViewPlaceholder</em> instance.</p>
<p>This implementation is very useful in case you defined a different layout depending on the screen orientation. For example, you could have a <em>my_activity_layout.xml</em> file in the <em>res/layout</em> folder of your Android project for the portrait orientation and another <em>my_activity_layout.xml</em> file in the <em>res/layout-land</em> folder with a different content for the landscape orientation. When <em>onConfigurationChanged</em> is called, the system already has the appropriate resources for the new configuration and when you call the <em><a href="http://developer.android.com/reference/android/app/Activity.html#setContentView(int)">setContentView</a></em> method passing it a layout resource id, the system uses the correct layout file for the current screen orientation, you just have to make sure that the ids of the UI elements are the same in both files and that the <em>webViewPlaceholder</em> element is present in both the layout configurations. This is what I have also in the internal web browser of my <a href="http://market.android.com/details?id=com.devahead.fweblauncher.free">FWebLauncher</a> app and that allows me to have a different position and layout of the buttons bar depending on the screen orientation while keeping the same <em>WebView</em> instance.</p>

<p>I&#8217;m sure you noticed that the <em>onSaveInstanceState</em> and <em>onRestoreInstanceState</em> methods are still there, but why since the activity is not destroyed anymore? Well, they are there in case the activity is destroyed for a reason that is not a configuration change (e.g. the system needs to destroy the activity because it is not in foreground and there&#8217;s a need to free some memory). In that case we can still restore the original state of the <em>WebView</em>, just without preserving the complete state because we&#8217;re going to lose the zoom and the scroll position for example, anyway it&#8217;s still better than totally losing the <em>WebView</em> state.</p>
<p>If you want to read more about the configuration change handling in Android, you can check the <a href="http://developer.android.com/guide/topics/resources/runtime-changes.html">specific page</a> of the Android documentation. You can also download an example application through the link on top of this post to take a look at the source code that shows what I described in the post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recycling objects in Android with an Object Pool to avoid garbage collection</title>
		<link>http://www.devahead.com/blog/2011/12/recycling-objects-in-android-with-an-object-pool-to-avoid-garbage-collection/</link>
		<comments>http://www.devahead.com/blog/2011/12/recycling-objects-in-android-with-an-object-pool-to-avoid-garbage-collection/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 17:28:14 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[garbage collection]]></category>
		<category><![CDATA[garbage collector]]></category>
		<category><![CDATA[Object Pool]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=68</guid>
		<description><![CDATA[If you need to reduce the work of the garbage collector in Android, like in games development for example, all you can do is reduce the amount of objects you create and recycle those you’ve already created. One of the ways to do this is the implementation of the Object Pool design pattern.
An Object Pool [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/AndroidObjectPool/AndroidObjectPool.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p style="padding-top:10px;">If you need to reduce the work of the garbage collector in Android, like in games development for example, all you can do is reduce the amount of objects you create and recycle those you’ve already created. One of the ways to do this is the implementation of the <a href="http://en.wikipedia.org/wiki/Object_pool_pattern">Object Pool design pattern</a>.</p>
<p style="padding-bottom:0px;">An <em>Object Pool</em> could be implemented in many different ways depending on the needed features. What I’m going to show here is an implementation that respects the following requirements:</p>
<ul>
<li>during its execution, <strong>the <em>Object Pool</em> doesn’t allocate new objects</strong> other than those contained in the pool itself (we prefer plain arrays instead of Java collections);</li>
<li><strong>the <em>Object Pool</em> must be efficient</strong> in terms of execution speed;</li>
<li><strong>the <em>Object Pool</em> is responsible for initializing and finalizing the objects it contains</strong> (the objects must be ready to use when retrieved from the pool and they must free any unneeded resource when they are put back in the pool);</li>
<li><strong>if there’s no more room for new objects in the pool, then new objects must be created anyway if requested</strong>, but they’ll not be stored in the pool when freed;</li>
<li><strong>the <em>Object Pool</em> must be able to handle every type of Object</strong> (we only ask the objects to implement an interface to make them ready for the pool);</li>
<li><strong>sharing the pool between multiple threads</strong> doesn’t have to be a problem.</li>
</ul>
<p>And now, straight to the source code. We start with the definition of the <em>PoolObject</em> interface:</p>
<div class="post-source-code">
<pre class="brush: java;">
/**
 * Interface that has to be implemented by an object that can be
 * stored in an object pool through the ObjectPool class.
 */
public interface PoolObject
{
	/**
	 * Initialization method. Called when an object is retrieved
	 * from the object pool or has just been created.
	 */
	public void initializePoolObject();

	/**
	 * Finalization method. Called when an object is stored in
	 * the object pool to mark it as free.
	 */
	public void finalizePoolObject();
}
</pre>
</div>
<p>This is the interface that an object must implement to let the pool perform two operations: the initialization and the finalization. We use an interface so we can easily extend every other class and make the pool able to handle different objects.</p>
<p>The <em>Object Pool</em> creates the needed objects through a factory class that implements the <em>PoolObjectFactory</em> interface:</p>
<div class="post-source-code">
<pre class="brush: java;">
/**
 * Interface that has to be implemented by every class that allows
 * the creation of objectes for an object pool through the
 * ObjectPool class.
 */
public interface PoolObjectFactory
{
	/**
	 * Creates a new object for the object pool.
	 *
	 * @return new object instance for the object pool
	 */
	public PoolObject createPoolObject();
}
</pre>
</div>
<p>The factory class must decide how to create a new <em>PoolObject</em> instance whenever the pool needs it.</p>
<p>All we need to see now is the <em>ObjectPool</em> class, so let’s take a look at it:</p>
<div class="post-source-code">
<pre class="brush: java;">
/**
 * Object pool implementation.
 */
public class ObjectPool
{
	protected final int MAX_FREE_OBJECT_INDEX;

	protected PoolObjectFactory factory;
	protected PoolObject[] freeObjects;
	protected int freeObjectIndex = -1;

	/**
	 * Constructor.
	 *
	 * @param factory the object pool factory instance
	 * @param maxSize the maximun number of instances stored in the pool
	 */
	public ObjectPool(PoolObjectFactory factory, int maxSize)
	{
		this.factory = factory;
		this.freeObjects = new PoolObject[maxSize];
		MAX_FREE_OBJECT_INDEX = maxSize - 1;
	}

	/**
	 * Creates a new object or returns a free object from the pool.
	 *
	 * @return a PoolObject instance already initialized
	 */
	public synchronized PoolObject newObject()
	{
		PoolObject obj = null;

		if (freeObjectIndex == -1)
		{
			// There are no free objects so I just
			// create a new object that is not in the pool.
			obj = factory.createPoolObject();
		}
		else
		{
			// Get an object from the pool
			obj = freeObjects[freeObjectIndex];

			freeObjectIndex--;
		}

		// Initialize the object
		obj.initializePoolObject();

		return obj;
	}

	/**
	 * Stores an object instance in the pool to make it available for a subsequent
	 * call to newObject() (the object is considered free).
	 *
	 * @param obj the object to store in the pool and that will be finalized
	 */
	public synchronized void freeObject(PoolObject obj)
	{
		if (obj != null)
		{
			// Finalize the object
			obj.finalizePoolObject();

			// I can put an object in the pool only if there is still room for it
			if (freeObjectIndex &lt; MAX_FREE_OBJECT_INDEX)
			{
				freeObjectIndex++;

				// Put the object in the pool
				freeObjects[freeObjectIndex] = obj;
			}
		}
	}
}
</pre>
</div>
<p>The structure of this class is very simple. There are only three methods, the constructor and two other methods to create and free the object instances.</p>
<p>The <strong>constructor</strong> accepts two parameters, the factory instance and the maximum number of objects that can be stored in the pool.</p>
<p>The <strong><em>newObject</em></strong> method retrieves an object from the pool and returns it to the caller after initializing it. If there are free objects in the pool, then one of those is returned, otherwise a new one is created through the factory. In this way we put a limit on the maximum number of instances in the pool, but only the needed amount is actually created.</p>
<p>The <strong><em>freeObject</em></strong> method puts an object instance back in the pool making it available for subsequent calls to <em>newObject</em>. Before storing the object in the free objects array, its finalization method is called to let it free any unneeded resource if necessary. If there’s no room in the pool for the object, then only its finalization method is called.</p>
<p>Both the <em>newObject</em> and the <em>freeObject</em> methods are <strong>synchronized</strong> so the interaction between the pool and different threads is managed correctly.</p>
<p>We have all we need, so let’s take a look at an example to see how our new tool can be used and what is its benefit. Let’s say that we need to work with <em>Point</em> instances for a graphic application. We need to have many points, but we want to avoid to keep on creating them and try to reuse the instances if possible. We need to define a <em>PoolObject</em> first: <span id="more-68"></span></p>
<div class="post-source-code">
<pre class="brush: java;">
import android.graphics.Point;

import com.devahead.util.objectpool.PoolObject;

public class PointPoolObject extends Point implements PoolObject
{
	@Override
	public void initializePoolObject()
	{
		x = 0;
		y = 0;
	}

	@Override
	public void finalizePoolObject()
	{
		// No finalization needed
	}
}
</pre>
</div>
<p>Our <em>PointPoolObject</em> extends the <em>Point</em> class, so it’s a point in fact, but also implements the <em>PoolObject</em> interface. Whenever a point needs to be initialized, it must make sure that its <em>x</em> and <em>y</em> coordinates are both set to zero. There’s no need for a finalization since there are no resources to free.</p>
<p>A <em>PointPoolObject</em> instance is created through the <em>PointPoolObjectFactory</em> class:</p>
<div class="post-source-code">
<pre class="brush: java;">
import com.devahead.util.objectpool.PoolObject;
import com.devahead.util.objectpool.PoolObjectFactory;

public class PointPoolObjectFactory implements PoolObjectFactory
{
	@Override
	public PoolObject createPoolObject()
	{
		return new PointPoolObject();
	}
}
</pre>
</div>
<p>This simple factory doesn’t need to do anything particular, but just create a new instance of the <em>PointPoolObject</em> class. If additional steps are needed to create a new instance, you can perform them here in the <em>createPoolObject</em> method.</p>
<p>The following code is our example application to test the <em>Object Pool</em>:</p>
<div class="post-source-code">
<pre class="brush: java;">
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Debug;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.devahead.androidobjectpool.poolobjects.PointPoolObject;
import com.devahead.androidobjectpool.poolobjects.PointPoolObjectFactory;
import com.devahead.util.objectpool.ObjectPool;

public class MainActivity extends Activity implements OnClickListener
{
	private Button testNoPoolBtn;
	private TextView testNoPoolText;
	private Button testHalfPoolBtn;
	private TextView testHalfPoolText;
	private Button testFullPoolBtn;
	private TextView testFullPoolText;
	private Button testExceedPoolBtn;
	private TextView testExceedPoolText;

	private ObjectPool pointObjectPool1;
	private ObjectPool pointObjectPool2;
	private ObjectPool pointObjectPool3;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		testNoPoolBtn = (Button)findViewById(R.id.testNoPoolBtn);
		testNoPoolText = (TextView)findViewById(R.id.testNoPoolText);
		testHalfPoolBtn = (Button)findViewById(R.id.testHalfPoolBtn);
		testHalfPoolText = (TextView)findViewById(R.id.testHalfPoolText);
		testFullPoolBtn = (Button)findViewById(R.id.testFullPoolBtn);
		testFullPoolText = (TextView)findViewById(R.id.testFullPoolText);
		testExceedPoolBtn = (Button)findViewById(R.id.testExceedPoolBtn);
		testExceedPoolText = (TextView)findViewById(R.id.testExceedPoolText);

		testNoPoolBtn.setOnClickListener(this);
		testHalfPoolBtn.setOnClickListener(this);
		testFullPoolBtn.setOnClickListener(this);
		testExceedPoolBtn.setOnClickListener(this);

		// Create object pools with a maximum of 100 PointPoolObject
		pointObjectPool1 = new ObjectPool(new PointPoolObjectFactory(), 100);
		pointObjectPool2 = new ObjectPool(new PointPoolObjectFactory(), 100);
		pointObjectPool3 = new ObjectPool(new PointPoolObjectFactory(), 100);
	}

	@Override
	public void onClick(View v)
	{
		if (v == testNoPoolBtn)
		{
			testNoPool(100, testNoPoolText);
		}
		else if (v == testHalfPoolBtn)
		{
			testPool(pointObjectPool1, 50, testHalfPoolText);
		}
		else if (v == testFullPoolBtn)
		{
			testPool(pointObjectPool2, 100, testFullPoolText);
		}
		else if (v == testExceedPoolBtn)
		{
			testPool(pointObjectPool3, 120, testExceedPoolText);
		}
	}

	private void testNoPool(final int POINTS_COUNT, TextView textView)
	{
		Point point;

		Point[] points = new Point[POINTS_COUNT];

		Debug.startAllocCounting();

		for (int i = 0; i &lt; POINTS_COUNT; i++)
		{
			point = new Point();

			points[i] = point;
		}

		for (int i = 0; i &lt; POINTS_COUNT; i++)
		{
			point = new Point();

			points[i] = point;
		}

		Debug.stopAllocCounting();

		int ac = Debug.getThreadAllocCount();

		textView.setText(ac + &quot; ac&quot;);
	}

	private void testPool(ObjectPool objectPool, final int POINTS_COUNT, TextView textView)
	{
		PointPoolObject point;

		PointPoolObject[] points = new PointPoolObject[POINTS_COUNT];

		Debug.startAllocCounting();

		for (int i = 0; i &lt; POINTS_COUNT; i++)
		{
			point = (PointPoolObject)objectPool.newObject();

			points[i] = point;
		}

		for (int i = 0; i &lt; POINTS_COUNT; i++)
		{
			point = points[i];

			objectPool.freeObject(point);
		}

		for (int i = 0; i &lt; POINTS_COUNT; i++)
		{
			point = (PointPoolObject)objectPool.newObject();

			points[i] = point;
		}

		Debug.stopAllocCounting();

		int ac = Debug.getThreadAllocCount();

		textView.setText(ac + &quot; ac&quot;);
	}
}
</pre>
</div>
<p>As you can see, there are four buttons. We test how many instances are created in different situations, but the problem to solve is always the same: we need a certain amount of Point instances that have to be ready to use at the same time and we need to do this twice. We want to see what happens with or without the <em>Object Pool</em> and what happens with the pool if the total amount of needed instances at the same time is 50, 100 or 120 while having set the maximum size of the pool to be 100.</p>

<p><img src="http://www.devahead.com/blog/images/AndroidObjectPool/sample-app.jpg"/></p>
<p>
<p style="padding-bottom:0px;">In the image above you can see the test results. What does this mean?</p>
<ul>
<li><strong>no Object Pool:</strong> 200 instances are created because we need 100 instances for two times and we cannot reuse them;</li>
<li><strong>Object Pool and 50 instances needed:</strong> only 50 instances are created because the second time we need them we can just reuse those that have previously been created and are still in the pool (the pool maximum limit is never reached);</li>
<li><strong>Object Pool and 100 instances needed:</strong> 100 instances are created filling the pool and the second time we need them we can use those inside the pool previously marked as free;</li>
<li><strong>Object Pool and 120 instances needed:</strong> in this case 140 instances are created because the pool maximum limit is 100 and the other 20 instances are created anyway by <em>ObjectPool</em>, but there’s no room in the pool to store them when they’re not needed anymore; since we need the 120 instances twice, the second time 20 more instances are created so a total amount of 40 instances is created outside of the pool.</li>
</ul>

<p>We tested that the <em>Object Pool</em> lets us recycle object instances and creates only the objects that are needed at the same time avoiding to create more useless instances. If you keep on calling the same methods you can understand that without an <em>Object Pool</em> the total amount of instances that the garbage collector needs to collect is potentially endless and this means a lot of CPU time wasted in collecting instances, while the <em>Object Pool</em> keeps the objects creation under control and the garbage collector may not need to be executed at all.</p>
<p>This is just a way to implement the <em>Object Pool</em> design pattern and it’s made to be simple and avoid the creation of any object other than those stored inside the pool while it is used. If you need different features you can modify the proposed architecture to suit your needs.</p>
<p>If you want to take a look at another performance test of this <em>Object Pool</em> implementation and many other tests on the Android platform, you can check my other post titled &#8220;<a href="http://www.devahead.com/blog/2011/12/coding-for-performance-and-avoiding-garbage-collection-in-android/">Coding for performance and avoiding garbage collection in Android</a>&#8220;.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2011/12/recycling-objects-in-android-with-an-object-pool-to-avoid-garbage-collection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Coding for performance and avoiding garbage collection in Android</title>
		<link>http://www.devahead.com/blog/2011/12/coding-for-performance-and-avoiding-garbage-collection-in-android/</link>
		<comments>http://www.devahead.com/blog/2011/12/coding-for-performance-and-avoiding-garbage-collection-in-android/#comments</comments>
		<pubDate>Sun, 11 Dec 2011 22:49:20 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[garbage collection]]></category>
		<category><![CDATA[garbage collector]]></category>
		<category><![CDATA[Object Pool]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[speed]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=65</guid>
		<description><![CDATA[
Post updates:

[December 18th, 2011] added TEST 10: OBJECT POOL


You know how much important it is to always keep in mind the performance of your application when developing for mobile devices with limited resources. This is important especially for game developers that need to reach two goals:

write high performance code
avoid having the garbage collector work too [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/CodingForPerformanceAvoidingGC/CodingForPerformanceAvoidingGC.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<div class="post-updates-box">
<p class="post-updates-title">Post updates:</p>
<ul>
<li>[December 18th, 2011] added <em>TEST 10: OBJECT POOL</em></li>
</ul>
</div>
<p style="padding-top:10px;padding-bottom:0">You know how much important it is to always keep in mind the performance of your application when developing for mobile devices with limited resources. This is important especially for game developers that need to reach two goals:</p>
<ul>
<li>write <strong>high performance code</strong></li>
<li><strong>avoid having the garbage collector work too much</strong> because it might have a negative impact on the user experience (you don’t want the users to see small pauses while playing a game)</li>
</ul>
<p>In this post I’m going to show some tests I made for the Android platform. You can repeat the same tests on your own downloading the test app source code through the link on top of this post.</p>
<p style="padding-bottom:0">Here is my test environment:</p>
<ul>
<li>Samsung Galaxy S II</li>
<li>Android 2.3.3 (Gingerbread)</li>
<li>Airplane mode on (to avoid network connections that could affect the test results)</li>
</ul>
<p style="padding-bottom:0"><strong>NOTES:</strong></p>
<ul>
<li>these tests are not meant to be a 100% exact measure of performance differences between different solutions, they are made to show and verify what could be the best implementation choice depending on the context and they give only a rough measure of the difference in performance (specific to the test cases); the final conclusion is still true for similar implementation cases so a faster implementation is always faster, maybe not as much faster as shown in a test case, but still faster;</li>
<li>these tests are made for the Android platform, so a common good practice for a <a href="http://en.wikipedia.org/wiki/Java_Virtual_Machine">Java virtual machine</a> might not be valid for the <a href="http://en.wikipedia.org/wiki/Dalvik_(software)">Dalvik virtual machine</a>.</li>
</ul>
<p>The structure of this post is simple. A series of tests will be described giving information about what is the best choice for a software developer and why. Are you ready? Let’s go!</p>
<p><br/></p>
<h3>TEST 1: FOR LOOP OVER ARRAY</h3>
<p>When writing a for loop over arrays, the common way of implementing it is use the <em>length</em> property of the array in the termination condition. But instead of asking the array its length on every single iteration of the loop, we could just read it before entering the loop and cache it in a local variable.</p>
<p><strong>What we test:</strong> is there a difference between using a local variable to cache the length of an array instead of using the <em>length</em> property in a termination condition of a for loop?</p>
<p><br/></p>
<p><strong>Standard implementation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an int[] array

for (int i = 0; i &lt; arr.length; i++)
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Optimized implementation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an int[] array

int arrLength = arr.length;

for (int i = 0; i &lt; arrLength; i++)
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to loop over an array with length = 3000000. The loop is repeated 100 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Standard</strong></td>
<td align="middle">58 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Optimized</strong></td>
<td align="middle" bgcolor="#9bbb59">43 ms</td>
<td align="middle">26% faster than standard</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>Caching the array length in a local variable is faster than reading the value for every single loop iteration. If you know that the length of an array will never change during the loop execution, then caching its value is a good idea to improve the execution speed.</p>
<p><br/></p>
<h3>TEST 2: FOR LOOP OVER ARRAYLIST</h3>
<p>Like <em>TEST 1</em>, when writing a for loop over ArrayList, the common way of implementing it is use the <em>size</em> method of the ArrayList in the termination condition. But instead of asking the ArrayList its size on every single iteration of the loop, we could just read it before entering the loop and cache it in a local variable.</p>
<p><strong>What we test:</strong> is there a difference between using a local variable to cache the size of an ArrayList instead of using the size method in a termination condition of a for loop?</p>
<p><br/></p>
<p><strong>Standard implementation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an ArrayList&lt;Object&gt;

for (int i = 0; i &lt; arr.size(); i++)
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Optimized implementation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an ArrayList&lt;Object&gt;

int arrLength = arr.size();

for (int i = 0; i &lt; arrLength; i++)
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to loop over an ArrayList with size = 3000000. The loop is repeated 100 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Standard</strong></td>
<td align="middle">262 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Optimized</strong></td>
<td align="middle" bgcolor="#9bbb59">233 ms</td>
<td align="middle">11% faster than standard</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>Caching the ArrayList size in a local variable is faster than reading the value for every single loop iteration. If you know that the size of an ArrayList will never change during the loop execution, then caching its value is a good idea to improve the execution speed. An ArrayList is generally slower than a simple array because of the method invocations involved in reading and writing values from and to the collection. Different collections have different performances (think about the access time to the elements of a HashMap), so different tests are necessary to test them. <span id="more-65"></span></p>
<p><br/></p>
<h3>TEST 3: VARIABLE FIELD ACCESS</h3>
<p>If you add a variable field to a class, you can choose to make it <em>public</em> so other classes can read and write its value directly, or you can choose to implement <em>getter</em> and <em>setter</em> accessor methods and make the field <em>private</em> or <em>protected</em>.</p>
<p><strong>What we test:</strong> is there a difference between accessing a variable field through getter and setter methods instead of accessing it directly?</p>
<p><br/></p>
<p><strong>Getter and setter methods</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
private long var;

public long getVar()
{
	return var;
}

public void setVar(long value)
{
	var = value;
}
</pre>
</div>
<p><br/></p>
<p><strong>Direct access</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public long var;
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to read and write the value of <em>var</em> in a loop executed 3000000 times. The loop is repeated 100 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Getter and setter</strong></td>
<td align="middle">96 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Direct access</strong></td>
<td align="middle" bgcolor="#9bbb59">60 ms</td>
<td align="middle">37% faster than getter and setter</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>Accessing directly a field of a class instance is always faster than getting and setting its value through accessor methods. If the performance is very important and you don’t need to perform any check while reading or writing the value of the field, then making it public and accessing it directly highly increases the speed (methods invocations are slow).</p>
<p><br/></p>
<h3>TEST 4: VARIABLE VS CONSTANT</h3>
<p>A value can be stored in a variable field or in a constant field. If a value is expected to never change, storing it in a constant field is not only a good practice, but it also improves the speed of the implementation. Here we are going to verify this and we are going to test whether the use of a <em>static</em> field makes a difference in terms of performance.</p>
<p><strong>What we test:</strong> is there a difference between reading a value of a variable field compared to the one of a constant field and does declaring it as <em>static</em> make a difference in terms of performance?</p>
<p><br/></p>
<p><strong>Variable field</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public int var;
</pre>
</div>
<p><br/></p>
<p><strong>Static variable field</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public static int var;
</pre>
</div>
<p><br/></p>
<p><strong>Constant field</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public final int CONST;
</pre>
</div>
<p><br/></p>
<p><strong>Static constant field</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public static final int CONST;
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to read the value of <em>var</em> or <em>CONST</em> in a loop executed 5000000 times. The loop is repeated 500 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Variable field</strong></td>
<td align="middle">63 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Static variable field</strong></td>
<td align="middle">67 ms</td>
<td align="middle">slightly slower than variable</td>
</tr>
<tr>
<td><strong>Constant field</strong></td>
<td align="middle" bgcolor="#9bbb59">55 ms</td>
<td align="middle">faster than variable or static variable;<br/>no difference between constant and static constant</td>
</tr>
<tr>
<td><strong>Static constant field</strong></td>
<td align="middle" bgcolor="#9bbb59">55 ms</td>
<td align="middle">faster than variable or static variable;<br/>no difference between constant and static constant</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>If you know that a value will never change, then you should declare it as constant through the <em>final</em> keyword. Using constants instead of variables is always faster because the compiler can replace their value in the compiled code to avoid the variable field lookup time. In this test we also see that a static variable is slightly slower than an instance variable probably due to the different lookup procedure used by the virtual machine at runtime.</p>
<p><br/></p>
<h3>TEST 5: METHOD INVOCATIONS</h3>
<p>To have a better structure of a software implementation that helps reuse and maintainability, it’s good to create a modular architecture with multiple classes and methods that solve specific tasks instead of writing very long methods with repeated pieces of code that solve exactly the same problem. This leads anyway to more method invocations instead of having all the necessary code in a single method to complete the task. We want to see what’s the impact of multiple method invocations instead of a single invocation.</p>
<p><strong>What we test:</strong> how is the performance affected by multiple method invocations instead of a single invocation to complete the same task?</p>
<p><br/></p>
<p><strong>Multiple method invocations</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
private void execMethod()
{
	execMethod1();
}

private void execMethod1()
{
	execMethod2();
}

private void execMethod2()
{
	execMethod3();
}

private void execMethod3()
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Single method invocation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
private void execMethod()
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to execute <em>execMethod</em> inside a loop repeated 3000000 times. The test is repeated 100 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Multiple method invocations</strong></td>
<td align="middle">656 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Single method invocation</strong></td>
<td align="middle" bgcolor="#9bbb59">175 ms</td>
<td align="middle">73% faster than multiple method invocations</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>Multiple method invocations can really slow down the execution speed, so if you need to write high performance code, you should keep in mind that sometimes it’s more important to put all the necessary code in a single method instead of having the same code spread all over different methods or classes. The code structure will not be optimal, but the performance benefit is notable.</p>
<p><br/></p>
<h3>TEST 6: POLYMORPHIC METHODS</h3>
<p>Like we already said in <em>TEST 5</em>, to have a better structure of a software implementation that helps reuse and maintainability, it’s good to create a modular architecture with multiple classes so we can have the ability to implement polymorphic methods that execute a task in a different way depending on the specific class implementation. This is obtained through class inheritance and methods overriding. In this test we want to see what’s the impact of methods overriding on performance.</p>
<p><strong>What we test:</strong> how is the performance affected by methods overriding?</p>
<p><br/></p>
<p><strong>Classes inheritance and methods overriding</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public class PolyClass1
{
	public void execMethod()
	{
		// Do something
	}
}

public class PolyClass2 extends PolyClass1
{
	@Override
	public void execMethod()
	{
		super.execMethod();
	}
}

public class PolyClass3 extends PolyClass2
{
	@Override
	public void execMethod()
	{
		super.execMethod();
	}
}

public class PolyClass4 extends PolyClass3
{
	@Override
	public void execMethod()
	{
		super.execMethod();
	}
}

PolyClass4 polyClass = new PolyClass4();
polyClass.execMethod();
</pre>
</div>
<p><br/></p>
<p><strong>Direct method invocation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public class PolyClass1
{
	public void execMethod()
	{
		// Do something
	}
}

PolyClass1 polyClass = new PolyClass1();
polyClass.execMethod();
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to execute <em>execMethod</em> inside a loop repeated 3000000 times. The test is repeated 100 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Classes inheritance and methods overriding</strong></td>
<td align="middle">674 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Direct method invocation</strong></td>
<td align="middle" bgcolor="#9bbb59">195 ms</td>
<td align="middle">71% faster than methods overriding</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>Classes inheritance and polymorphism are good to improve the source code structure, but the cost is the reduced performance compared to direct methods invocations. This is basically the same thing we saw in <em>TEST 5</em> so we didn’t expect something different because each method in a subclass calls the corresponding one in the superclass (a method invocation). Since overriding a method is done to create a different version (with a different behavior) of the same method in a specific class, if you absolutely need high performance you could implement different methods that do something in a different way and call them directly instead of creating inherited classes with overridden methods to have the same result (of course some code will be repeated in this case).</p>
<p><br/></p>
<h3>TEST 7: VIRTUAL VS STATIC METHODS</h3>
<p>If you declare a method in Java, it is <em>virtual</em> by default. In case it doesn’t need to access other instance methods or fields, it should be declared as <em>static</em> not only as a good programming practice (you clearly say that the method will not modify anything in a class instance), but also to improve performance.</p>
<p><strong>What we test:</strong> is there a difference between <em>virtual</em> and <em>static</em> methods in terms of performance?</p>
<p><br/></p>
<p><strong>Virtual method</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public void virtualMethod()
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Static method</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
public static void staticMethod()
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to execute <em>virtualMethod</em> or <em>staticMethod</em> inside a loop repeated 3000000 times. The test is repeated 100 times to check the average time taken for each complete loop.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Virtual method</strong></td>
<td align="middle">152 ms</td>
<td align="middle">&nbsp;</td>
</tr>
<tr>
<td><strong>Static method</strong></td>
<td align="middle" bgcolor="#9bbb59">137 ms</td>
<td align="middle">10% faster than virtual method</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p><em>Static</em> methods are faster than <em>virtual</em> methods and since there are no drawbacks in declaring a method as <em>static</em> if it doesn’t use fields or methods specific to a class instance, you should always do that when you can.</p>
<p><br/></p>
<h3>TEST 8: ITERATION OVER ARRAY</h3>
<p>Starting with Java 1.5, there’s an easy syntax to implement an iteration over arrays or collections instead of hand-writing the usual for loop. This gives performance improvements compared to some hand-written versions of the iteration, while it is indistinguishable from others.</p>
<p><strong>What we test:</strong> what&#8217;s the difference between using an iterator over an array instead of a hand-written loop in terms of performance and objects allocation?</p>
<p><br/></p>
<p><strong>Iterator</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an Object[] array declared as a class field

for (Object obj : arr)
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Manual iteration</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an Object[] array declared as a class field

int arrLength = arr.length;

for (int i = 0; i &lt; arrLength; i++)
{
	// Do something with arr
}
</pre>
</div>
<p><br/></p>
<p><strong>Manual iteration with local array</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an Object[] array declared as a class field

// We declare a variable localArr that is local to the
// method that implements the iteration (we avoid
// accessing the arr class field inside the loop).
Object[] localArr = arr;

int arrLength = localArr.length;

for (int i = 0; i &lt; arrLength; i++)
{
	// Do something with localArr
}
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to loop over an array with length = 5000000. The test is repeated 500 times to check the average time taken for each complete loop. It is also shown the number of objects allocated in the different loop implementations.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Objects allocation count</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Iterator</strong></td>
<td align="middle" bgcolor="#9bbb59">90 ms</td>
<td align="middle" bgcolor="#9bbb59">0</td>
<td align="middle">the same as manual iteration with local array</td>
</tr>
<tr>
<td><strong>Manual iteration</strong></td>
<td align="middle">102 ms</td>
<td align="middle" bgcolor="#9bbb59">0</td>
<td align="middle">13% slower than iterator or manual iteration with local array</td>
</tr>
<tr>
<td><strong>Manual iteration with local array</strong></td>
<td align="middle" bgcolor="#9bbb59">90 ms</td>
<td align="middle" bgcolor="#9bbb59">0</td>
<td align="middle">the same as iterator</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>To understand this, you should take a look at the <a href="http://developer.android.com/guide/practices/design/performance.html">&#8220;Designing for Performance&#8221;</a> document in the Android developers guide (look at &#8220;Use Enhanced For Loop Syntax&#8221;). The <em>Iterator</em> case is translated by the compiler in a way identical to the <em>Manual iteration with local array</em> case, that’s why the performance is the same. With simple arrays there is no difference between a hand-written optimized loop and the iteration syntax, so you should always prefer the latter to improve the code readability. In every case there are no objects allocations so we have no problems with the garbage collector. In this test we also see a performance improvement if we store a reference to the array locally in the method that executes the loop instead of accessing directly the array as a class instance field. This is another thing to keep in mind to improve performance (the lookup time for the array variable is reduced).</p>
<p><br/></p>
<h3>TEST 9: ITERATION OVER ARRAYLIST</h3>
<p>We want to try the same test we did in <em>TEST 8</em>, but with an ArrayList instead of a simple array. When using the iteration syntax introduced in Java 1.5 with collections (like ArrayList) instead of simple arrays, there’s a difference in the compiled code. In this case an <em><a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a></em> object is used to implement the iteration so we must also consider the extra objects allocation compared to a hand-written loop without the iteration syntax.</p>
<p><strong>What we test:</strong> what’s the difference between using an iterator over an ArrayList instead of a hand-written loop in terms of performance and objects allocation?</p>
<p><br/></p>
<p><strong>Iterator</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an ArrayList&lt;Object&gt; collection declared as a class field

for (Object obj : arr)
{
	// Do something
}
</pre>
</div>
<p><br/></p>
<p><strong>Manual iteration</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an ArrayList&lt;Object&gt; collection declared as a class field

int arrLength = arr.size();

for (int i = 0; i &lt; arrLength; i++)
{
	// Do something with arr
}
</pre>
</div>
<p><br/></p>
<p><strong>Manual iteration with local ArrayList</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// arr is an ArrayList&lt;Object&gt; collection declared as a class field

// We declare a variable localArr that is local to the
// method that implements the iteration (we avoid
// accessing the arr class field inside the loop).
ArrayList&lt;Object&gt; localArr = arr;

int arrLength = localArr.size();

for (int i = 0; i &lt; arrLength; i++)
{
	// Do something with localArr
}
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to loop over an ArrayList with size = 3000000. The test is repeated 100 times to check the average time taken for each complete loop. It is also shown the number of objects allocated in the different loop implementations.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Objects allocation count</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Iterator</strong></td>
<td align="middle">481 ms</td>
<td align="middle" bgcolor="#c0504d">100</td>
<td align="middle">slower than both manual iterations and 100 objects allocated (an <em>Iterator</em> instance for each test repetition)</td>
</tr>
<tr>
<td><strong>Manual iteration</strong></td>
<td align="middle">246 ms</td>
<td align="middle" bgcolor="#9bbb59">0</td>
<td align="middle">49% faster than iterator and 5% slower than manual iteration with local ArrayList</td>
</tr>
<tr>
<td><strong>Manual iteration with local ArrayList</strong></td>
<td align="middle" bgcolor="#9bbb59">235 ms</td>
<td align="middle" bgcolor="#9bbb59">0</td>
<td align="middle">51% faster than iterator and 5% faster than manual iteration</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>You might be surprised to see that the <em>Iterator</em> performance is much slower than a hand-written iteration loop, but the reason is simple: to implement the <em>Iterator</em> syntax, the compiler uses an <em><a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a></em> object, so the loop is made invoking its <em>hasNext</em> and <em>next</em> methods and you know from our previous tests that method invocations are slow. A hand-written loop just uses a standard <em>for</em> syntax to implement the loop and doesn’t need to invoke any method resulting in a much faster execution. There’s another problem with the <em>Iterator</em> syntax: a new <em><a href="http://developer.android.com/reference/java/util/Iterator.html">Iterator</a></em> object is allocated for each complete loop execution and this means more objects to collect for the garbage collector. This can lead to a poor performance in games for example, because there could be many small pauses every time the garbage collector executes while the user is playing, making the overall experience not really great. You should choose the <em>Iterator</em> syntax only for applications that don’t need high performance code or continuous rendering (like games) because it helps to keep the source code cleaner and easier to read, but you should always prefer hand-written iterations when developing games or other similar applications. This test has been made with an ArrayList collection and might give different results with other collections, but it shows that even though the <em>Iterator</em> syntax is the same as the one for a standard array (like we saw in <em>TEST 8</em>), the compiled code is much different and we must consider the drawbacks of this syntax while dealing with collections.</p>
<p><br/></p>
<h3>TEST 10: OBJECT POOL</h3>
<p>In order to reduce the work of the garbage collector, all you can do is reduce the amount of objects you create and recycle the instances you’ve already created. You can do this with the implementation of the <a href="http://en.wikipedia.org/wiki/Object_pool_pattern">Object Pool design pattern</a>. There are different ways to implement an <em>Object Pool</em>, depending on the features you need, and a possible implementation is the one you can find in my other post titled &#8220;<a href="http://www.devahead.com/blog/2011/12/recycling-objects-in-android-with-an-object-pool-to-avoid-garbage-collection/">Recycling objects in Android with an Object Pool to avoid garbage collection</a>&#8220;. That will be the implementation used in this test.</p>
<p><strong>What we test:</strong> what&#8217;s the impact of an <em>Object Pool</em> in terms of performance and objects allocation compared to the standard object creation without recycling the instances?</p>
<p><br/></p>
<p><strong>Standard object creation</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// Example of a standard object creation of an android.graphics.Point instance

Point point = new Point(x, y);
</pre>
</div>
<p><br/></p>
<p><strong>Object Pool</strong></p>
<div class="post-source-code">
<pre class="brush: java;">
// Example of a creation of an android.graphics.Point instance through an Object Pool

// Object Pool initialization with a maximum capacity or NEEDED_POINTS_COUNT instances.
// The PointPoolObjectFactory is a factory class that creates PointPoolObject
// instances.
ObjectPool pointsPool = new ObjectPool(new PointPoolObjectFactory(), NEEDED_POINTS_COUNT);

// The PointPoolObject class extends android.graphics.Point and implements the
// interface needed to make it work with the Object Pool.
PointPoolObject point = (PointPoolObject)pointsPool.newObject();
point.x = x;
point.y = y;

// When the point instance is not needed anymore, we put it back in the Object Pool
pointsPool.freeObject(point);
</pre>
</div>
<p><br/></p>
<p><strong>Test results</strong></p>
<p>The results show the average time taken to create and initialize 1000 <em>Point</em> instances inside a loop repeated 100 times to simulate a situation where we need 1000 <em>Point</em> instances to be ready to use at the same time and we need all of them 100 times during our application execution (note: with the <em>Object Pool</em> we also need to free the instances and store them back in the pool, while without the pool that’s the job of the garbage collector). The test is repeated 100 times to check the average time taken for each complete loop. It is also shown the number of objects allocated in the different loop implementations.</p>
<table>
<tr>
<th>&nbsp;</th>
<th>Average loop time</th>
<th>Objects allocation count</th>
<th>Result</th>
</tr>
<tr>
<td><strong>Standard object creation</strong></td>
<td align="middle">180 ms</td>
<td align="middle" bgcolor="#c0504d">10000000</td>
<td align="middle">slower than the <em>Object Pool</em> implementation and 10000000 objects allocated (the total time varies depending on the speed of the garbage collector execution)</td>
</tr>
<tr>
<td><strong>Object Pool</strong></td>
<td align="middle" bgcolor="#9bbb59">47 ms</td>
<td align="middle" bgcolor="#9bbb59">1000</td>
<td align="middle">faster than the standard object creation (the garbage collector doesn&#8217;t need to work) and only 1000 objects allocated</td>
</tr>
</table>
<p><br/></p>
<p><strong>Conclusion</strong></p>
<p>As you can see, the <em>Object Pool</em> allows us to allocate only the total amount of <em>Point</em> instances that are needed at the same time (1000) while with a standard object creation we would allocate the objects multiple times without reusing them (1000 points x 100 times x 100 repetitions of the test = 10000000 instances). Of course we could find a strategy to recycle the points even without the <em>Object Pool</em>, but the reason to have an <em>Object Pool</em> is to make this simple and standardized across the source code of our application. As you surely noticed, the test execution takes even less time with the <em>Object Pool</em> and the reason for this is the garbage collector: with the <em>Object Pool</em> and only 1000 instances created, the garbage collector doesn’t need to work at all, while with the standard object creation it needs to collect many instances and it executes a lot of times making everything slower (you can see this if you try to run the test and check in the LogCat view of the DDMS perspective of Eclipse).</p>

<p>That’s it. This is of course only a subset of what could be tested and more tests could be added, but it covers most of the common scenarios that you have to face every time you need to make a decision about the implementation of an application.</p>
<p>When implementing applications (like games) that need to <strong>avoid garbage collection</strong> because of the small pauses it introduces every time the garbage collector executes, all you can do is <strong>avoid to keep on creating objects and try to reuse as much as possible the objects instances you already have</strong>. This can be done in different ways (like through <em><a href="http://www.devahead.com/blog/2011/12/recycling-objects-in-android-with-an-object-pool-to-avoid-garbage-collection/">Object Pools</a></em> as we saw in <em>TEST 10</em>) and depends a lot on the specific implementation and application context, but it’s important to know the cases where you don’t create objects directly and you don’t realize that they are created anyway (like we saw with the <em>Iterator</em> syntax in <em>TEST 9</em>). It can be hard to discover such a hidden source of objects creation when you’ve already completed your source code implementation, so it’s better to know it in advance before any implementation decision.</p>
<p>If you think that something is wrong with these tests or you would like me to implement new ones, feel free to write a comment to this post. Every feedback is appreciated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2011/12/coding-for-performance-and-avoiding-garbage-collection-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a custom Android button with a resizable skin</title>
		<link>http://www.devahead.com/blog/2011/08/creating-a-custom-android-button-with-a-resizable-skin/</link>
		<comments>http://www.devahead.com/blog/2011/08/creating-a-custom-android-button-with-a-resizable-skin/#comments</comments>
		<pubDate>Tue, 02 Aug 2011 02:18:40 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[icon]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[resizable]]></category>
		<category><![CDATA[skin]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=63</guid>
		<description><![CDATA[If you are developing your own Android application, maybe you would like to give it a custom skin with a defined set of colors for all the interface elements. Here I&#8217;m going to show how to customize Android buttons. This is the same kind of customization I made for my own app which is called [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/CustomAndroidButtonWithResizableSkin/CustomAndroidButtonWithResizableSkin.zip">Source code</a></span></div>
<p style="padding-top:10px">If you are developing your own Android application, maybe you would like to give it a custom skin with a defined set of colors for all the interface elements. Here I&#8217;m going to show how to customize Android buttons. This is the same kind of customization I made for my own app which is called <strong><a href="http://www.devahead.com/products/fweblauncher.php">FWebLauncher</a></strong> and you can <a href="http://market.android.com/details?id=com.devahead.fweblauncher.free">download for free from the Android Market</a>. In this post I&#8217;m going to quickly describe the steps that have to be performed to obtain our result, but I recommend you to download the whole example application with all the resource images through the link on top of this post.</p>
<p>First of all, you need to decide how your buttons will look in different states, so you&#8217;ve got to define the corresponding skin images for the <em>Normal</em>, <em>Pressed</em>, <em>Focused</em> and <em>Disabled</em> states. Of course, if you don&#8217;t need all the states, you can just define some of them. In the following image you can see how our buttons will look like:</p>

<p><img src="http://www.devahead.com/blog/images/CustomAndroidButtonWithResizableSkin/button-states.jpg"/></p>
<p>
<p>We want the skin to be resizable, so the button can adapt its size depending on the content (i.e. the text) without making the skin look weird. To do this, we need to define a <strong><a href="http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch">9-patch</a></strong> for each image. There&#8217;s a tool installed with the Android SDK that you can find in <em>${ANDROID_SDK_INSTALL_DIRECTORY}\tools\draw9patch.bat</em>. Execute that batch file and you&#8217;ll have the following application running:</p>

<p><img src="http://www.devahead.com/blog/images/CustomAndroidButtonWithResizableSkin/9-patch-example.jpg"/></p>
<p>
<p>As you can see I&#8217;ve already loaded the PNG file for the <em>Normal</em> state of our buttons and I&#8217;ve defined the 9-patch with the black lines that you can see on every side of the image. As written in the <a href="http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch">Android developer&#8217;s documentation</a>, the top and left lines define the stretchable area used to resize the image, while the bottom and right lines define the area where the content must be placed. With the 9-patch tool, I created a new file for each image of the button skin, so for example, if the skin image for the <em>Normal</em> state of the button is called <em>button_normal.png</em>, then the corresponding 9-patch file will be <em>button_normal.9.png</em> and we need only this inside the resources folders of our application.</p>
<p>The next thing to do is creating a <em>selector</em> that tells Android how it should deal with the skin images depending on the button state. The <em>selector</em> is just an XML file that looks like this:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
	&lt;item android:drawable=&quot;@drawable/button_disabled&quot; android:state_enabled=&quot;false&quot;/&gt;
	&lt;item android:drawable=&quot;@drawable/button_pressed&quot; android:state_pressed=&quot;true&quot;/&gt;
	&lt;item android:drawable=&quot;@drawable/button_focused&quot; android:state_focused=&quot;true&quot;/&gt;
	&lt;item android:drawable=&quot;@drawable/button_normal&quot;/&gt;
&lt;/selector&gt;
</pre>
</div>
<p>In the <em>selector</em> you define which skin image should be used to render each button state. So if the <em>selector</em> XML file is called <em>button.xml</em>, you can just write something like this to have your button skin working:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;Button android:id=&quot;@+id/textBtn&quot;
	android:layout_width=&quot;wrap_content&quot;
	android:layout_height=&quot;wrap_content&quot;
	android:text=&quot;Text in the button&quot;
	android:background=&quot;@drawable/button&quot;
	android:textColor=&quot;#ffffffff&quot;/&gt;
</pre>
</div>
<p>This is just a simple button with some text in it. In case you need a button with an image, like an icon, and you want it to resize proportionally, then you don&#8217;t need to define a 9-patch and you need to use something different like an <em>ImageButton</em>: <span id="more-63"></span></p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;ImageButton android:id=&quot;@+id/iconBtn&quot;
	android:layout_width=&quot;64dip&quot;
	android:layout_height=&quot;64dip&quot;
	android:src=&quot;@drawable/icon_button&quot;
	android:scaleType=&quot;fitCenter&quot;
	android:background=&quot;#00000000&quot;/&gt;
</pre>
</div>
<p>These are the possible states for <em>iconBtn</em>:</p>

<p><img src="http://www.devahead.com/blog/images/CustomAndroidButtonWithResizableSkin/icon-button-states.jpg"/></p>
<p>
<p>I set the <em>scaleType</em> attribute to make the image resize correctly and I set the <em>background</em> to <em>#00000000</em> because I want to make it completely transparent (remember that the format for that attribute is <em>ARGB</em> where <em>A</em> is the alpha value). I don&#8217;t need the background because I already have an image for each state of the button with its own trasparency correctly set on the borders to have a custom shape for the button if I need it. The <em>src</em> attribute specifies the selector to use for this button:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
	&lt;item android:drawable=&quot;@drawable/icon_button_disabled&quot; android:state_enabled=&quot;false&quot;/&gt;
	&lt;item android:drawable=&quot;@drawable/icon_button_pressed&quot; android:state_pressed=&quot;true&quot;/&gt;
	&lt;item android:drawable=&quot;@drawable/icon_button_focused&quot; android:state_focused=&quot;true&quot;/&gt;
	&lt;item android:drawable=&quot;@drawable/icon_button_normal&quot;/&gt;
&lt;/selector&gt;
</pre>
</div>

<p>What if you want a button with both an icon and the text? Well, you can do it with something like this:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;Button android:id=&quot;@+id/textAndIconBtn&quot;
	android:layout_width=&quot;wrap_content&quot;
	android:layout_height=&quot;wrap_content&quot;
	android:text=&quot;Text in the button&quot;
	android:background=&quot;@drawable/button&quot;
	android:drawableLeft=&quot;@drawable/star_icon&quot;
	android:drawablePadding=&quot;5dip&quot;
	android:textColor=&quot;#ffffffff&quot;/&gt;
</pre>
</div>
<p>The icon is specified in the <em>drawableLeft</em> attribute and you can set also a padding to use between the icon and the text through the <em>drawablePadding</em> attribute. In this case the <em>button.xml</em> selector makes it possible to change only the background image depending on the button state, but not the icon itself. To do that, you need to act programmatically in the source code.</p>
<p>To see the final result of what I explained, take a look at the example application downloadable from the top of this post:

<p><img src="http://www.devahead.com/blog/images/CustomAndroidButtonWithResizableSkin/sample-app.jpg"/></p>
<p>
<p>For each kind of button, you can try to make it pressed, focused or disabled to see how it changes. The layout of the main activity is defined as follows:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Button with text:&quot;/&gt;

	&lt;LinearLayout
		android:orientation=&quot;horizontal&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:layout_marginTop=&quot;3dip&quot;
		android:layout_marginBottom=&quot;3dip&quot;&gt;

		&lt;Button android:id=&quot;@+id/textBtn&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:text=&quot;Text in the button&quot;
			android:background=&quot;@drawable/button&quot;
			android:textColor=&quot;#ffffffff&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

		&lt;CheckBox android:id=&quot;@+id/textBtnEnabledCheck&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_marginLeft=&quot;10dip&quot;
			android:checked=&quot;true&quot;
			android:text=&quot;Enabled&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

	&lt;/LinearLayout&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Button with icon:&quot;
		android:layout_marginTop=&quot;6dip&quot;/&gt;

	&lt;LinearLayout
		android:orientation=&quot;horizontal&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:layout_marginTop=&quot;3dip&quot;
		android:layout_marginBottom=&quot;3dip&quot;&gt;

		&lt;ImageButton android:id=&quot;@+id/iconBtn&quot;
			android:layout_width=&quot;64dip&quot;
			android:layout_height=&quot;64dip&quot;
			android:src=&quot;@drawable/icon_button&quot;
			android:scaleType=&quot;fitCenter&quot;
			android:background=&quot;#00000000&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

		&lt;CheckBox android:id=&quot;@+id/iconBtnEnabledCheck&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_marginLeft=&quot;10dip&quot;
			android:checked=&quot;true&quot;
			android:text=&quot;Enabled&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

	&lt;/LinearLayout&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Button with text and icon:&quot;
		android:layout_marginTop=&quot;6dip&quot;/&gt;

	&lt;LinearLayout
		android:orientation=&quot;horizontal&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:layout_marginTop=&quot;3dip&quot;
		android:layout_marginBottom=&quot;3dip&quot;&gt;

		&lt;Button android:id=&quot;@+id/textAndIconBtn&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:text=&quot;Text in the button&quot;
			android:background=&quot;@drawable/button&quot;
			android:drawableLeft=&quot;@drawable/star_icon&quot;
			android:drawablePadding=&quot;5dip&quot;
			android:textColor=&quot;#ffffffff&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

		&lt;CheckBox android:id=&quot;@+id/textAndIconBtnEnabledCheck&quot;
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_marginLeft=&quot;10dip&quot;
			android:checked=&quot;true&quot;
			android:text=&quot;Enabled&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

	&lt;/LinearLayout&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>In the <em>MainActivity</em> class we just define the listeners to make the buttons enabled or disabled depending on the checkboxes. Note that you need to set the value also for the <em>clickable</em> property of the <em>ImageButton</em> to make it actually enabled or disabled.</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.customandroidbuttonwithresizableskin;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;

public class MainActivity extends Activity implements OnCheckedChangeListener
{
	// Interface elements
	protected Button textBtn;
	protected CheckBox textBtnEnabledCheck;
	protected ImageButton iconBtn;
	protected CheckBox iconBtnEnabledCheck;
	protected Button textAndIconBtn;
	protected CheckBox textAndIconBtnEnabledCheck;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Retrieve interface elements
		textBtn = (Button)findViewById(R.id.textBtn);
		textBtnEnabledCheck = (CheckBox)findViewById(R.id.textBtnEnabledCheck);
		iconBtn = (ImageButton)findViewById(R.id.iconBtn);
		iconBtnEnabledCheck = (CheckBox)findViewById(R.id.iconBtnEnabledCheck);
		textAndIconBtn = (Button)findViewById(R.id.textAndIconBtn);
		textAndIconBtnEnabledCheck = (CheckBox)findViewById(R.id.textAndIconBtnEnabledCheck);

		// Add listeners
		textBtnEnabledCheck.setOnCheckedChangeListener(this);
		iconBtnEnabledCheck.setOnCheckedChangeListener(this);
		textAndIconBtnEnabledCheck.setOnCheckedChangeListener(this);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
	{
		if (buttonView == textBtnEnabledCheck)
		{
			textBtn.setEnabled(isChecked);
		}
		else if (buttonView == iconBtnEnabledCheck)
		{
			iconBtn.setEnabled(isChecked);
			iconBtn.setClickable(isChecked);
		}
		else if (buttonView == textAndIconBtnEnabledCheck)
		{
			textAndIconBtn.setEnabled(isChecked);
		}
	}
}
</pre>
</div>
<p>That&#8217;s it. I hope you can find something useful in this post and if you want to see some custom buttons in action in a real application, you could give a try to <strong><a href="http://www.devahead.com/products/fweblauncher.php">FWebLauncher</a></strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2011/08/creating-a-custom-android-button-with-a-resizable-skin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the standard Android icons in your own application</title>
		<link>http://www.devahead.com/blog/2011/07/using-the-standard-android-icons-in-your-own-application/</link>
		<comments>http://www.devahead.com/blog/2011/07/using-the-standard-android-icons-in-your-own-application/#comments</comments>
		<pubDate>Sun, 17 Jul 2011 22:54:35 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[icons]]></category>
		<category><![CDATA[standard]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=61</guid>
		<description><![CDATA[When you make your own Android application, you usually put also your own graphic elements in it like custom icons and images, but it&#8217;s still a good idea to keep the standard Android icons for common user interactions. This helps the user to immediately understand the meaning of the options inside your application and it [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/StandardAndroidIcons/StandardAndroidIcons.zip">Source code</a></span></div>
<p style="padding-top:10px">When you make your own Android application, you usually put also your own graphic elements in it like custom icons and images, but it&#8217;s still a good idea to <strong>keep the standard Android icons for common user interactions</strong>. This helps the user to immediately understand the meaning of the options inside your application and it gives a familiar environment that is consistent with the Android platform. So, how do you get the standard Android icons? How do you deal with different Android versions (the style of the icons might change)?</p>
<p style="padding-bottom:0">There are two different options to accomplish this task:</p>
<ol>
<li>reference the icons with <em><a href="http://developer.android.com/reference/android/R.drawable.html">android.R.drawable</a></em>;</li>
<li>copy the standard Android icons from the SDK to your own application&#8217;s resources folder.</li>
</ol>
<p><strong>OPTION 1</strong> &#8211; The good points about this option is that you automatically have the correct resource for the platform version where your application is running and the size of the application package doesn&#8217;t become higher in case you&#8217;re using more standard Android icons. This looks like the perfect solution, so why look for another one? Well, not all the icons are defined in <em><a href="http://developer.android.com/reference/android/R.drawable.html">android.R.drawable</a></em> so you are forced to copy them locally in case you can&#8217;t find them in the class. Another bad point is what is explicitly stated in the guidelines documents for <a href="http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html">the menu icons</a> and <a href="http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html">the status bar icons</a>:</p>
<p class="citation-box">&#8220;<strong>Warning:</strong> Because these resources can change between platform versions, you should not reference these icons using the Android platform resource IDs (i.e. status bar icons under android.R.drawable). If you want to use any icons or other internal drawable resources, you should store a local copy of those icons or drawables in your application resources, then reference the local copy from your application code. In that way, you can maintain control over the appearance of your icons, even if the system&#8217;s copy changes.&#8221;</p>
<p><strong>OPTION 2</strong> &#8211; You can find all the standard Android icons in your SDK local installation following the path <strong><em>${ANDROID_SDK_INSTALL_DIRECTORY}\platforms\android-${PLATFORM_VERSION}\data\res</em></strong>, so let&#8217;s say that you installed the SDK under <em>C:\AndroidSDK</em> and you want the resources for the version 7 of the Android platform (i.e. Android 2.1), you can find everything under <strong><em>C:\AndroidSDK\platforms\android-7\data\res</em></strong>. You can copy for example the hdpi version of the icons from <em>C:\AndroidSDK\platforms\android-7\data\res\drawable-hdpi</em>. Following this approach, you need to copy the icons for different versions of the Android platform in case their style changed between one version and another. This is what happened for example for the menu and status bar icons, since Android 2.3 (platform version 9) the style changed, so you need a copy of the standard icons for Android 2.3 and higher and for Android 2.2 and lower. To do this, in your own application you need two different folders (this example refers to the hdpi icons):</p>
<pre class="citation-box">
/res/drawable-hdpi (for Android 2.2 and lower)
/res/drawable-hdpi-v9 (for Android 2.3 and higher)
</pre>
<p>Now let&#8217;s see a simple example application that uses the standard icons getting them in both ways. Here is the layout of the main activity: <span id="more-61"></span></p>

<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Reference to android.R.drawable in the XML layout file:&quot;/&gt;

	&lt;ImageView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:src=&quot;@android:drawable/ic_menu_add&quot;/&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Reference to android.R.drawable in the source code:&quot;/&gt;

	&lt;ImageView android:id=&quot;@+id/img1&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;/&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Reference to a local copy of the icon in the XML layout file:&quot;/&gt;

	&lt;ImageView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:src=&quot;@drawable/ic_menu_add&quot;/&gt;

	&lt;TextView
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Reference to a local copy of the icon in the source code:&quot;/&gt;

	&lt;ImageView android:id=&quot;@+id/img2&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>And here is the source code for the <em>MainActivity</em> class:</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.standardandroidicons;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Set the image source referencing android.R.drawable
		ImageView img1 = (ImageView)findViewById(R.id.img1);
		img1.setImageResource(android.R.drawable.ic_menu_add);

		// Set the image source referencing a local copy of the icon
		ImageView img2 = (ImageView)findViewById(R.id.img2);
		img2.setImageResource(R.drawable.ic_menu_add);
	}
}
</pre>
</div>
<p>In this application I used the <em>ic_menu_add</em> standard Android icon. For this example to work, we need to put a copy of the original icon <em>ic_menu_add.png</em> from <em>C:\AndroidSDK\platforms\android-8\data\res\drawable-hdpi</em> to our local <em>/res/drawable-hdpi</em> and another copy from <em>C:\AndroidSDK\platforms\android-9\data\res\drawable-hdpi</em> to our local <em>/res/drawable-hdpi-v9</em>. In this way, the application will load the correct version of the local icon depending on the platform version, so for Android 2.3 and higher, the copy under <em>/res/drawable-hdpi-v9</em> will be automatically chosen.</p>
<p>In the following images you can see the final result. If you run the application on Android 2.1, you see that there&#8217;s a glow around the icon while on Android 2.3 there is no outer glow. That&#8217;s because the style changed starting from Android 2.3 as it is written in the <a href="http://developer.android.com/guide/practices/ui_guidelines/icon_design_menu.html">menu icons design guidelines</a>, so our example application loads the correct icon depending on the platform version.</p>
<p>Example application running on Android 2.1:</p>

<p><img src="http://www.devahead.com/blog/images/StandardAndroidIcons/app-running-on-android-2-1.jpg"/></p>
<p>
<p>Example application running on Android 2.3:</p>

<p><img src="http://www.devahead.com/blog/images/StandardAndroidIcons/app-running-on-android-2-3.jpg"/></p>
<p>
<p>The option you choose to load the standard Android icons is up to you. With this post I just wanted to show the different possibilites, but they all have some good and bad points that must be evaluated to choose what&#8217;s right for you.</p>
<p>You can find the source code of the example application following the link on top of the post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2011/07/using-the-standard-android-icons-in-your-own-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an Android dialog and maintaining its state on screen orientation change</title>
		<link>http://www.devahead.com/blog/2011/07/creating-an-android-dialog-and-maintaining-its-state-on-screen-orientation-change/</link>
		<comments>http://www.devahead.com/blog/2011/07/creating-an-android-dialog-and-maintaining-its-state-on-screen-orientation-change/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 22:17:49 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[dialog]]></category>
		<category><![CDATA[orientation]]></category>
		<category><![CDATA[screen]]></category>
		<category><![CDATA[screen orientation change]]></category>
		<category><![CDATA[state]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=56</guid>
		<description><![CDATA[You want to create a custom dialog in Android, but you also want to maintain its state on screen orientation change when it&#8217;s already open and the Android device is rotated. How do you do that? If you use the standard methods that Android provides inside activities, it&#8217;s straightforward. Here I&#8217;m going to show how [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/CustomAndroidDialog/CustomAndroidDialog.zip">Source code</a></span></div>
<p style="padding-top:10px">You want to <strong>create a <a href="http://developer.android.com/guide/topics/ui/dialogs.html">custom dialog in Android</a></strong>, but you also want to <strong>maintain its state on screen orientation change</strong> when it&#8217;s already open and the Android device is rotated. How do you do that? If you use the standard methods that Android provides inside activities, it&#8217;s straightforward. Here I&#8217;m going to show how to create a completely <strong>custom dialog</strong> with its own custom layout and interface elements.</p>
<p style="padding-bottom:0">Let&#8217;s start with the basics. What do you need inside your Android activity?</p>
<ul>
<li>implement the <em>onCreateDialog</em> method;</li>
<li>implement the <em>onPrepareDialog</em> method;</li>
<li>keep a constant with the custom dialog ID;</li>
<li>call the <em>showDialog</em> method to display the dialog;</li>
<li>call the <em>removeDialog</em> or <em>dismissDialog</em> methods to remove the dialog from the screen.</li>
</ul>
<p>And now straight to the source code with an example application. The layout of our custom dialog will look like this (<em>custom_dialog.xml</em> resource file):</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  android:layout_width=&quot;fill_parent&quot;
  android:layout_height=&quot;wrap_content&quot;
  android:orientation=&quot;vertical&quot;&gt;

	&lt;ScrollView
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;wrap_content&quot;&gt;

		&lt;LinearLayout
		  android:layout_width=&quot;fill_parent&quot;
		  android:layout_height=&quot;wrap_content&quot;
		  android:orientation=&quot;vertical&quot;
		  android:paddingLeft=&quot;3dip&quot;
		  android:paddingRight=&quot;3dip&quot;&gt;

			&lt;TextView
				android:layout_width=&quot;wrap_content&quot;
				android:layout_height=&quot;wrap_content&quot;
				android:text=&quot;Field 1:&quot;
				android:layout_gravity=&quot;left&quot;
				android:textColor=&quot;@android:color/primary_text_dark&quot;/&gt;

			&lt;EditText android:id=&quot;@+id/cdField1Edit&quot;
				android:layout_width=&quot;fill_parent&quot;
				android:layout_height=&quot;wrap_content&quot;
				android:gravity=&quot;left&quot;/&gt;

			&lt;TextView
				android:layout_width=&quot;wrap_content&quot;
				android:layout_height=&quot;wrap_content&quot;
				android:text=&quot;Field 2:&quot;
				android:layout_gravity=&quot;left&quot;
				android:layout_marginTop=&quot;10dip&quot;
				android:textColor=&quot;@android:color/primary_text_dark&quot;/&gt;

			&lt;EditText android:id=&quot;@+id/cdField2Edit&quot;
				android:layout_width=&quot;fill_parent&quot;
				android:layout_height=&quot;wrap_content&quot;
				android:gravity=&quot;left&quot;/&gt;

		&lt;/LinearLayout&gt;

	&lt;/ScrollView&gt;

	&lt;LinearLayout
	  android:layout_width=&quot;fill_parent&quot;
	  android:layout_height=&quot;wrap_content&quot;
	  android:orientation=&quot;horizontal&quot;
	  android:layout_gravity=&quot;center_horizontal&quot;&gt;

		&lt;Button android:id=&quot;@+id/cdOKBtn&quot;
			android:layout_width=&quot;fill_parent&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_weight=&quot;1&quot;
			android:text=&quot;OK&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

		&lt;Button android:id=&quot;@+id/cdCancelBtn&quot;
			android:layout_width=&quot;fill_parent&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_weight=&quot;1&quot;
			android:text=&quot;Cancel&quot;
			android:layout_gravity=&quot;center_vertical&quot;/&gt;

	&lt;/LinearLayout&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>We simply have two text fields (<em>cdField1Edit</em> and <em>cdField2Edit</em>) and two buttons to confirm our input (<em>cdOKBtn</em>) or to cancel the dialog (<em>cdCancelBtn</em>).</p>
<p>Inside the main activity we can set a default value for <em>cdField2Edit</em> in the dialog (through <em>cdField2DefValEdit</em>) and we have a button to display the dialog (<em>showCDBtn</em>):</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot;
	android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;

	&lt;LinearLayout
	  android:layout_width=&quot;fill_parent&quot;
	  android:layout_height=&quot;wrap_content&quot;
	  android:orientation=&quot;horizontal&quot;
	  android:paddingLeft=&quot;3dip&quot;
	  android:paddingRight=&quot;3dip&quot;&gt;

		&lt;TextView
			android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:text=&quot;Field 2 default value:&quot;/&gt;

		&lt;EditText android:id=&quot;@+id/cdField2DefValEdit&quot;
			android:layout_width=&quot;fill_parent&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_marginLeft=&quot;10dip&quot;/&gt;

	&lt;/LinearLayout&gt;

	&lt;Button android:id=&quot;@+id/showCDBtn&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot;
		android:text=&quot;Show Custom Dialog 1&quot;
		android:layout_marginTop=&quot;20dip&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
</div>
<p>The <em>MainActivity</em> class is the place where we&#8217;re going to implement the logic to manage the creation and intialization of our custom dialog: <span id="more-56"></span></p>

<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.customandroiddialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener
{
	protected static final int DIALOG_1 = 0; // Dialog 1 ID

	// Dialog 1 default values (static variables to maintain the values on screen orientation change)
	protected static String cdField2DefaultValue;

	// Interface elements
	protected EditText cdField2DefValEdit;
	protected Button showCDBtn;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Retrieve interface elements
		cdField2DefValEdit = (EditText)findViewById(R.id.cdField2DefValEdit);
		showCDBtn = (Button)findViewById(R.id.showCDBtn);

		// Add listeners
		showCDBtn.setOnClickListener(this);
	}

	public void onClick(View v)
	{
		if (v == showCDBtn)
		{
			showDialog1(cdField2DefValEdit.getText().toString());
		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch (id)
		{
			case DIALOG_1:
			{
				final Dialog dialog = new Dialog(this);

				// Setup the custom dialog interface elements
				dialog.setContentView(R.layout.custom_dialog);
				dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

				Button cdOKBtn = (Button)dialog.findViewById(R.id.cdOKBtn);
				Button cdCancelBtn = (Button)dialog.findViewById(R.id.cdCancelBtn);

				cdOKBtn.setOnClickListener(new OnClickListener()
				{
					// Called when the OK button is pressed
					@Override
					public void onClick(View v)
					{
						EditText cdField1Edit = (EditText)dialog.findViewById(R.id.cdField1Edit);
						EditText cdField2Edit = (EditText)dialog.findViewById(R.id.cdField2Edit);

						String field1Value = cdField1Edit.getText().toString();
						String field2Value = cdField2Edit.getText().toString();

						// Call a method to process the dialog result
						MainActivity.this.processDialog1Result(field1Value, field2Value);

						// If we call removeDialog, then onCreateDialog will be called every time
						// the dialog needs to be displayed, otherwise if we call dismissDialog,
						// only onPrepareDialog will be called after the first dialog creation
						// (the first showDialog).
						removeDialog(DIALOG_1);
						//dismissDialog(DIALOG_1);
					}
				});

				cdCancelBtn.setOnClickListener(new OnClickListener()
				{
					// Called when the Cancel button is pressed
					@Override
					public void onClick(View v)
					{
						removeDialog(DIALOG_1);
						//dismissDialog(DIALOG_1);
					}
				});

				dialog.setOnCancelListener(new OnCancelListener()
				{
					// Called when the Back button is pressed
					@Override
					public void onCancel(DialogInterface dialog)
					{
						removeDialog(DIALOG_1);
						//dismissDialog(DIALOG_1);
					}
				});

				return dialog;
			}
			default:
				return null;
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog)
	{
		switch (id)
		{
			case DIALOG_1:
			{
				dialog.setTitle(&quot;Custom dialog 1&quot;);

				EditText cdField1Edit = (EditText)dialog.findViewById(R.id.cdField1Edit);
				EditText cdField2Edit = (EditText)dialog.findViewById(R.id.cdField2Edit);

				// Set the default values for Field 1 and 2
				cdField1Edit.setText(&quot;&quot;);
				cdField2Edit.setText(cdField2DefaultValue != null ? cdField2DefaultValue : &quot;&quot;);
			}
			break;
		}
	}

	protected void showDialog1(String field2DefaultValue)
	{
		// Set the default value for Field 2 (used in onPrepareDialog)
		cdField2DefaultValue = field2DefaultValue;

		showDialog(DIALOG_1);
	}

	protected void processDialog1Result(String field1Value, String field2Value)
	{
		Toast.makeText(this, &quot;CD1 - field1Value: &quot; + field1Value + &quot; - field2Value: &quot; + field2Value,
			Toast.LENGTH_LONG).show();
	}
}
</pre>
</div>
<p>All the methods useful to manage dialogs need an ID to keep track of all the operations to perform on a specific dialog, so i created a constant named <em>DIALOG_1</em> that represents the ID of our custom dialog. I could create as many ids as I want, the important thing is to identify every dialog with a specific ID. When you start the example application, you can set a default value to initialize <em>Field 2</em> inside the dialog and then you can press the button to display it.</p>
<p>When you call <em>showDialog</em> with the <em>DIALOG_1</em> ID, Android calls <em>onCreateDialog</em> to let you create the dialog for the same ID, so you can setup the interface elements and add all the listeners you need for managing the dialog events. In the example I added a listener for the click events of the OK button (<em>cdOKBtn</em>) to process the data set by the user, one for the Cancel button (<em>cdCancelBtn</em>) to remove the dialog and another one for the <em>onCancel</em> event. The latter is useful to manage the case when a user presses the back button of the Android device to close the dialog because we can receive the event, but it&#8217;s our responsibility to really close the dialog maybe performing some sort of deinitialization if we need it.</p>
<p>After calling <em>onCreateDialog</em>, Android calls <em>onPrepareDialog</em> to let you initialize default values for the interface elements inside the dialog. In the example we set <em>cdField1Edit</em> to blank and we initialize <em>cdField2Edit</em> with the default value specified by the user in the <em>MainActivity</em>.</p>
<p>So why do we need both <em>onCreateDialog</em> and <em>onPrepareDialog</em>? Couldn&#8217;t we just do everything inside <em>onCreateDialog</em>? To answer this question, let&#8217;s take a look at what happens depending on the way we close the dialog. We have two options to close it: <em>removeDialog</em> and <em>dismissDialog</em>. Here is what happens in different situations depending on our implementation choices:</p>
<ul>
<li>
<strong>we close the dialog using <em>removeDialog</em>:</strong> every time we display the dialog again using <em>showDialog</em>, both <em>onCreateDialog</em> and <em>onPrepareDialog</em> are called by Android because the dialog is not reused after being closed;
</li>
<li>
<strong>we close the dialog using <em>dismissDialog</em>:</strong> the first time we display the dialog using <em>showDialog</em>, both <em>onCreateDialog</em> and <em>onPrepareDialog</em> are called by Android, but all the subsequent times we call <em>showDialog</em>, only <em>onPrepareDialog</em> is called by Android because the dialog has already been previously created and it&#8217;s reused after being closed (to save resources and the computation necessary to create the dialog every time we need to display it);
</li>
<li>
<strong>the screen orientations changes while the dialog is still open:</strong> both <em>onCreateDialog</em> and <em>onPrepareDialog</em> are called by Android because the <em>MainActivity</em> instance is created again and also the dialog needs to be created again, but using the standard Android methods to manage the dialogs, the system saves its state for us and <strong>the field values will be preserved and restored in the new dialog instance after the orientation change</strong> (even though <em>onPrepareDialog</em> is called to initialize the fields, Android restores their values after calling that method so we don&#8217;t need to care about that).
</li>
</ul>
<p>This is the important thing, <strong>Android does the job for us restoring the field values in the dialog when the screen orientation changes</strong>, all we need to do is to <strong>implement the standard methods available in every activity for dialogs management</strong> and choose a specific ID for every dialog created by the activity.</p>
<p>As usual, you can download the full source code for this example using the link on the top of the post so you can take a look at it and experiment on your own.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2011/07/creating-an-android-dialog-and-maintaining-its-state-on-screen-orientation-change/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extending the Android Application class and dealing with Singleton</title>
		<link>http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/</link>
		<comments>http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 21:21:08 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[extend]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=43</guid>
		<description><![CDATA[In this post I&#8217;m going to show the basic steps to extend the Android Application class and I&#8217;m also going to talk about why it could be useful to extend it in dealing with the Singleton design pattern.
The first thing to do is to create a MyApplication class that extends android.app.Application.


package com.devahead.extendingandroidapplication;

import android.app.Application;

public class MyApplication [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="source-link"><a href="http://www.devahead.com/blog/examples/ExtendingAndroidApplication/ExtendingAndroidApplication.zip">Source code</a></span></div>
<p style="padding-top:10px">In this post I&#8217;m going to show the basic steps to <strong>extend the <a href="http://developer.android.com/reference/android/app/Application.html">Android Application class</a></strong> and I&#8217;m also going to talk about <strong>why it could be useful to extend it in dealing with the <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton design pattern</a></strong>.</p>
<p>The first thing to do is to create a <em>MyApplication</em> class that extends <em>android.app.Application</em>.</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.extendingandroidapplication;

import android.app.Application;

public class MyApplication extends Application
{
	@Override
	public void onCreate()
	{
		super.onCreate();

		// Initialize the singletons so their instances
		// are bound to the application process.
		initSingletons();
	}

	protected void initSingletons()
	{
		// Initialize the instance of MySingleton
		MySingleton.initInstance();
	}

	public void customAppMethod()
	{
		// Custom application method
	}
}
</pre>
</div>
<p>In this class you can, for example, override the <em>onCreate</em> method to perform your initializations at the application startup and you can also implement your own methods to make them available to the rest of your application components. As you can see here we initialize also the singletons in case there are some in our application. I&#8217;ll talk later about why I do this here, but now let&#8217;s go on with the custom Application class.</p>
<p>The next thing we need to do is to open the <em>AndroidManifest.xml</em> file of our application and add a reference to <em>MyApplication</em> in the <em>android:name</em> attribute of the <em>application</em> tag, so in the end the manifest file will look similar to this one:</p>
<div class="post-source-code">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	package=&quot;com.devahead.extendingandroidapplication&quot;
	android:versionCode=&quot;1&quot;
	android:versionName=&quot;1.0&quot;&gt;

	&lt;uses-sdk android:minSdkVersion=&quot;7&quot;/&gt;

	&lt;application android:icon=&quot;@drawable/icon&quot; android:label=&quot;@string/app_name&quot;
		android:name=&quot;com.devahead.extendingandroidapplication.MyApplication&quot;&gt;

		&lt;activity android:name=&quot;.MainActivity&quot;
			android:label=&quot;@string/app_name&quot;&gt;
			&lt;intent-filter&gt;
				&lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt;
				&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt;
			&lt;/intent-filter&gt;
		&lt;/activity&gt;

	&lt;/application&gt;
&lt;/manifest&gt;
</pre>
</div>
<p>That&#8217;s it. We now have a custom <em>Application</em> class that can be used to suit our needs. We can access to it from any <em><a href="http://developer.android.com/reference/android/app/Activity.html">Activity</a></em> through the <em><a href="http://developer.android.com/reference/android/app/Activity.html#getApplication()">getApplication</a></em> method (the same <em><a href="http://developer.android.com/reference/android/app/Service.html#getApplication()">getApplication</a></em> method is available also in a <em><a href="http://developer.android.com/reference/android/app/Service.html">Service</a></em>).</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.extendingandroidapplication;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity
{
	protected MyApplication app;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Get the application instance
		app = (MyApplication)getApplication();

		// Call a custom application method
		app.customAppMethod();

		// Call a custom method in MySingleton
		MySingleton.getInstance().customSingletonMethod();

		// Read the value of a variable in MySingleton
		String singletonVar = MySingleton.getInstance().customVar;
	}
}
</pre>
</div>
<p>As you can see there are references to the <em>MySingleton</em> class also here as an example like there were in the <em>MyApplication</em> class, but we haven&#8217;t seen the singleton yet, so here it is:</p>
<div class="post-source-code">
<pre class="brush: java;">
package com.devahead.extendingandroidapplication;

public class MySingleton
{
	private static MySingleton instance;

	public String customVar;

	public static void initInstance()
	{
		if (instance == null)
		{
			// Create the instance
			instance = new MySingleton();
		}
	}

	public static MySingleton getInstance()
	{
		// Return the instance
		return instance;
	}

	private MySingleton()
	{
		// Constructor hidden because this is a singleton
	}

	public void customSingletonMethod()
	{
		// Custom method
	}
}
</pre>
</div>
<p>The <em>initInstance</em> method lets the internal instance be initialized only once and this is done in the <em>MyApplication</em> class as we saw earlier. The <em>getInstance</em> method allows to access the instance from every part of our application and the <em>MySingleton</em> constructor is kept private because we don&#8217;t want to allow the creation of multiple instances. <span id="more-43"></span></p>

<p>At this point you may ask: &quot;wait a moment&#8230; why is the singleton initialized in <em>MyApplication</em>??? Isn&#8217;t it supposed to be just a singleton so the instance can be initialized everywhere in the application like in an Activity?&quot; Here comes the tricky part&#8230; I&#8217;ve been digging around the web and in books for a long time searching for information on the static variables lifecycle in Android because I found some weird behaviors when I started programming for Android, but unfortunately there seem to be different opinions about this topic, there is a bit of confusion and I still haven&#8217;t found a single definitive source of information.</p>
<p>If you know about the activities lifecycle in Android, you also know that they can be destroyed by the system in case they&#8217;re no more used and they&#8217;re not active or some resources are needed by the system, so it happens that during the life of an application, an activity could be destroyed and created many times, while the application process remains the same. While I was developing an application, I found that <strong>sometimes some static variables bound to activities happened to be uninitialized even though they&#8217;ve previously been initialized!</strong> I thought that when a static variable is initialized it stays so for the entire life of the application, but this doesn&#8217;t seem to be the case. Among all the information I found on the web, I tried to find out a <strong>safe and reliable way to initialize static variables</strong> (and you know that the singleton design pattern requires the use of a static variable). The explanation of the weird behavior I saw that makes more sense to me is that <strong>the static variables instances are bound to the class loader of the class that first initialized them</strong>. So what does this mean? This means that if a static variable inside any class has been initialized by an activity, when that activity is destroyed also its class might be unloaded and so the variable becomes uninitialized again! While if the variable is initialized by the application class, it&#8217;s life is the same as the application process so we&#8217;re sure that it will never become uninitialized again. That&#8217;s why I chose to initialize all the singletons in the <em>MyApplication</em> class.</p>
<p>I don&#8217;t know if the solution I found is correct and makes sense as it seems that this topic is not clear for many people dealing with Android and even the official documentation seems to make the people think that static variables are not problematic and behave exactly like we are used to in other environments with the Java virtual machine, but using the technique I explained actually solved my problems with static variables deinitialization and I never had the weird behaviors I was having when I was initializing them (as well as singletons) directly from my activities.</p>
<p>If someone found a better solution or doesn&#8217;t think this approach is correct, I would be happy to hear a different opinion. This is what the web is useful for and it&#8217;s interesting to read thoughts of experienced Android developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flex exceptions are suppressed in MXML data binding expressions</title>
		<link>http://www.devahead.com/blog/2010/09/flex-exceptions-are-suppressed-in-mxml-data-binding-expressions/</link>
		<comments>http://www.devahead.com/blog/2010/09/flex-exceptions-are-suppressed-in-mxml-data-binding-expressions/#comments</comments>
		<pubDate>Wed, 15 Sep 2010 00:19:46 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[data binding]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[MXML]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=31</guid>
		<description><![CDATA[While using data binding expressions inside MXML tags, you may have noticed that sometimes there seem to be strange behaviors during expressions evaluation, for example it could happen that an expression is not updated like you expect it to be when a value of a bindable variable changes. Whenever someone new to Flex starts to [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/ExceptionsSuppressedInMXML/ExceptionsSuppressedInMXML.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/ExceptionsSuppressedInMXML/srcview/ExceptionsSuppressedInMXML.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p style="padding-top:10px">While using data binding expressions inside MXML tags, you may have noticed that sometimes there seem to be strange behaviors during expressions evaluation, for example it could happen that an expression is not updated like you expect it to be when a value of a bindable variable changes. Whenever someone new to Flex starts to work with it, I noticed that sooner or later he asks me always the same question: <strong>&quot;Why is the value of that label not being updated? I think that my expression is correct&#8230;&quot;</strong> I had the same problem too at the beginning, because it&#8217;s not something obvious, but it&#8217;s important to keep a rule in mind.</p>
<p>This is the thing to know: <strong>exceptions are suppressed in MXML data binding expressions!</strong> And it&#8217;s very important to keep in mind this rule: <strong>every data binding expression must be written in a way that avoids exceptions, considering all the possible values that each variable in the expression can get</strong>.</p>
<p>The reason why an expression sometimes is not evaluated is usually the fact that there has been an exception during the evaluation. In this case using some <em>if</em> statements in the expression generally solves the problem. Let&#8217;s take a look at an example application to show what we&#8217;re talking about.</p>

<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Flex exceptions are suppressed in MXML data binding expressions - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			[Bindable]
			protected var myVar1: String = &quot;a string&quot;;

			[Bindable]
			protected var myVar2: String = &quot;i = 0&quot;;

			[Bindable]
			protected var i: int = 0;

			protected function testFunc(value: String): String
			{
				value = value.toUpperCase(); // Exception if value == null

				i++;

				myVar2 = &quot;i = &quot; + i;

				return value;
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Label text=&quot;{'(WITH EXCEPTION) The value of myVar1 is: ' +
		myVar1.toUpperCase()}&quot;/&gt;

	&lt;mx:Label text=&quot;{'(WITH EXCEPTION FROM FUNCTION) The value of myVar1 is: ' +
		testFunc(myVar1)}&quot;/&gt;

	&lt;mx:Label text=&quot;{'(WITHOUT EXCEPTION) The value of myVar1 is: ' +
		(myVar1 != null ? myVar1.toUpperCase() : 'NULL')}&quot;/&gt;

	&lt;mx:Label text=&quot;{'myVar2: ' + myVar2}&quot;/&gt;

	&lt;mx:Spacer height=&quot;16&quot;/&gt;

	&lt;mx:Label text=&quot;Test exception in MXML tag with data binding expression:&quot;/&gt;

	&lt;mx:Button label=&quot;Set myVar1 = NULL&quot; click=&quot;{myVar1 = null}&quot;/&gt;
	&lt;mx:Button label=&quot;Set myVar1 = 'a string'&quot; click=&quot;{myVar1 = 'a string'}&quot;/&gt;

&lt;/mx:Application&gt;
</pre>
</div>
<p>In the application we use some data binding expressions inside curly braces. The value of <em>myVar1</em> is displayed in three labels, but only in the last one there&#8217;s an <em>if</em> statement that actually checks if its value is <em>null</em>. Since in every expression we try to use the function <em>toUpperCase</em> on the variable, there is clearly an exception if the variable is <em>null</em>. If you try to set <em>myVar1 = null</em> clicking on the corresponding button, you&#8217;ll see that the only label that is correctly rendered is the one with the <em>if</em> statement, because it&#8217;s data binding expression avoids generating an exception. The function <em>testFunc</em> has the purpose of demonstrating that the value of <em>i</em> is never increased whenever there&#8217;s an exception in the first line of the function&#8217;s body and the exception is never thrown because it is suppressed automatically. If you keep on clicking on both the buttons, you&#8217;ll see that the value of <em>i</em> is increased only when there are no exceptions in <em>testFunc</em>, i.e. the value of <em>myVar1</em> is not <em>null</em>.</p>
<p>So if you notice some strange behaviors in your data binding expressions evaluation, keep in mind what we&#8217;ve seen here, because you will never get a message telling you that there has been an exception, even with the debug version of the Flash Player.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/09/flex-exceptions-are-suppressed-in-mxml-data-binding-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setter is not invoked when a bindable Flex property doesn&#8217;t change</title>
		<link>http://www.devahead.com/blog/2010/05/setter-is-not-invoked-when-a-bindable-flex-property-doesnt-change/</link>
		<comments>http://www.devahead.com/blog/2010/05/setter-is-not-invoked-when-a-bindable-flex-property-doesnt-change/#comments</comments>
		<pubDate>Sat, 15 May 2010 20:35:35 +0000</pubDate>
		<dc:creator>Andrea Bresolin</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[bindable]]></category>
		<category><![CDATA[getter]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[setter]]></category>

		<guid isPermaLink="false">http://www.devahead.com/blog/?p=29</guid>
		<description><![CDATA[You&#8217;ve probably been using the Bindable metadata tag a lot of times with properties in your Flex applications. When a property is defined through getter and setter functions, you may take for granted that each time you set the value of the property, the corresponding setter is invoked, so you can perform your own operations [...]]]></description>
			<content:encoded><![CDATA[<div class="post-attachments"><span class="swf-link"><a href="http://www.devahead.com/blog/examples/SetterNotInvokedWithBindable/SetterNotInvokedWithBindable.html" target="_blank">Live demo</a></span><span class="source-link"><a href="http://www.devahead.com/blog/examples/SetterNotInvokedWithBindable/srcview/SetterNotInvokedWithBindable.zip">Source code</a> <strong><a href="about#sourcelicense">(LICENSE)</a></strong></span></div>
<p style="padding-top:10px">You&#8217;ve probably been using the <em>Bindable</em> metadata tag a lot of times with properties in your Flex applications. When a property is defined through getter and setter functions, you may take for granted that each time you set the value of the property, the corresponding setter is invoked, so you can perform your own operations in it. Well, this is not totally true with bindable properties. What I&#8217;m going to show is just something to remember whenever you use the <em>Bindable</em> metadata tag with properties defined through getter and setter. It is much easier to explain everything if we immediately look at the example application.</p>
<div class="post-source-code">
<pre class="brush: as3;">
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot;
	pageTitle=&quot;Setter is not invoked when a bindable Flex property doesn\'t change - devahead BLOG&quot;
	layout=&quot;vertical&quot; horizontalAlign=&quot;left&quot;
	viewSourceURL=&quot;srcview/index.html&quot;&gt;

	&lt;mx:Script&gt;
		&lt;![CDATA[
			private var _notBindableProp: String = &quot;&quot;;

			public function get notBindableProp(): String
			{
				return _notBindableProp;
			}

			public function set notBindableProp(value: String): void
			{
				_notBindableProp = value;

				logValueChange(&quot;notBindableProp&quot;, _notBindableProp);
			}

			private var _bindableProp: String = &quot;&quot;;

			[Bindable]
			public function get bindableProp(): String
			{
				return _bindableProp;
			}

			public function set bindableProp(value: String): void
			{
				_bindableProp = value;

				logValueChange(&quot;bindableProp&quot;, _bindableProp);
			}

			private var _bindableEventProp: String = &quot;&quot;;

			[Bindable(&quot;bindableEventPropChanged&quot;)]
			public function get bindableEventProp(): String
			{
				return _bindableEventProp;
			}

			public function set bindableEventProp(value: String): void
			{
				_bindableEventProp = value;

				logValueChange(&quot;bindableEventProp&quot;, _bindableEventProp);

				dispatchEvent(new Event(&quot;bindableEventPropChanged&quot;));
			}

			protected function logValueChange(propertyName: String, newValue: String): void
			{
				logArea.text += propertyName + &quot; setter invoked: &quot; + newValue + &quot;\n&quot;;
			}
		]]&gt;
	&lt;/mx:Script&gt;

	&lt;mx:Form&gt;
		&lt;mx:FormItem direction=&quot;horizontal&quot;
			label=&quot;New value for the NOT BINDABLE property:&quot;&gt;
			&lt;mx:TextInput id=&quot;notBindablePropText&quot; width=&quot;150&quot;/&gt;
			&lt;mx:Button label=&quot;Set&quot; click=&quot;{notBindableProp = notBindablePropText.text}&quot;/&gt;
		&lt;/mx:FormItem&gt;

		&lt;mx:FormItem direction=&quot;horizontal&quot;
			label=&quot;New value for the BINDABLE property:&quot;&gt;
			&lt;mx:TextInput id=&quot;bindablePropText&quot; width=&quot;150&quot;/&gt;
			&lt;mx:Button label=&quot;Set&quot; click=&quot;{bindableProp = bindablePropText.text}&quot;/&gt;
			&lt;mx:Label text=&quot;{bindableProp}&quot; fontWeight=&quot;bold&quot;/&gt;
		&lt;/mx:FormItem&gt;

		&lt;mx:FormItem direction=&quot;horizontal&quot;
			label=&quot;New value for the BINDABLE property WITH CUSTOM EVENT:&quot;&gt;
			&lt;mx:TextInput id=&quot;bindableEventPropText&quot; width=&quot;150&quot;/&gt;
			&lt;mx:Button label=&quot;Set&quot; click=&quot;{bindableEventProp = bindableEventPropText.text}&quot;/&gt;
			&lt;mx:Label text=&quot;{bindableEventProp}&quot; fontWeight=&quot;bold&quot;/&gt;
		&lt;/mx:FormItem&gt;
	&lt;/mx:Form&gt;

	&lt;mx:Label text=&quot;Log:&quot;/&gt;

	&lt;mx:TextArea id=&quot;logArea&quot; width=&quot;400&quot; height=&quot;300&quot;/&gt;

&lt;/mx:Application&gt;
</pre>
</div>

<p>The property called <em>notBindableProp</em> is just a simple not bindable property. Whenever you set its value, the setter is invoked. <em>bindableProp</em> is a standard bindable property. If you try to set its value, you&#8217;ll quickly find out that <strong>the setter is invoked only if the new value is different from the value returned by the corresponding getter</strong>. So you cannot rely on doing something inside the setter when the new value is exactly the same as the previous one. What if you still want a bindable property, but you need to perform some operations in the setter every time a value is set, even if it&#8217;s equal to the previous one? You can simply define a custom event name in the <em>Bindable</em> metadata tag as you can see in the <em>bindableEventProp</em>. Every time a value is set for that property, the setter is invoked and you can perform your operations and then dispatch your own event.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devahead.com/blog/2010/05/setter-is-not-invoked-when-a-bindable-flex-property-doesnt-change/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

