<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Grokking Android</title>
	
	<link>http://www.grokkingandroid.com</link>
	<description>Getting Down to the Nitty Gritty of Android Development</description>
	<lastBuildDate>Wed, 17 Apr 2013 19:21:47 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/GrokkingAndroid" /><feedburner:info uri="grokkingandroid" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>ActionViews Sample App is on Bitbucket</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/jDt4doZkr0k/</link>
		<comments>http://www.grokkingandroid.com/actionviews-sample-app-is-on-bitbucket/#comments</comments>
		<pubDate>Mon, 15 Apr 2013 06:38:19 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Demo]]></category>
		<category><![CDATA[HierarchyViewer]]></category>
		<category><![CDATA[Monkey]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[UIAutomator]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2537</guid>
		<description><![CDATA[<p>The sample app for my post about ActionViews is on Bitbucket. Besides Actionviews it serves also as the sample app for how to add ActionBarSherlock to projects, and for adding action items from within fragments. Here&#8217;s a screenshot of the demo: I plan on generating the scaffold for my demo apps so that I only [...]</p><p>The post <a href="http://www.grokkingandroid.com/actionviews-sample-app-is-on-bitbucket/">ActionViews Sample App is on Bitbucket</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">The <a href="https://bitbucket.org/grokkingandroid/actionviews" title="Sample App showcasing Android's ActionViews">sample app for my post about ActionViews is on Bitbucket</a>. Besides Actionviews it serves also as the sample app for how to add ActionBarSherlock to projects, and for adding action items from within fragments.</p>
<p>Here&#8217;s a screenshot of the demo:</p>
<div id="attachment_2555" class="wp-caption alignnone" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/actionviews_demoapp_searchview_unexpanded.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/actionviews_demoapp_searchview_unexpanded-153x300.png" alt="The demo app showing the SearchView in its collpased mode" width="153" height="300" class="size-medium wp-image-2555" /></a><p class="wp-caption-text">The demo app showing the SearchView in its collpased mode</p></div>
<p>I plan on generating the scaffold for my demo apps so that I only have to add specific stuff and keep my work for the demos to a minimum. That on the other hand makes some parts of the code look a bit weird, others look pretty generic. You wouldn&#8217;t do it that way for a single purpose project.</p>
<p>Since I like to blog about what is happening to me while developing apps, I use this post to tell you about three useful Android tools that I used while developing and preparing this app for release. </p>
<p>The first two can be used to analyze the UI, the third is useful for spotting problems with stuff you might miss because you are too knowledgable of the way your app works.</p>
<h3>HierarchyViewer vs. UI Automator Viewer</h3>
<p><a href="http://developer.android.com/tools/testing/testing_ui.html" title="Android's UI Testing site with a section about UIAutomatorViewer">UI Automator Viewer</a> is a tool that was released with Android pretty recently (sometime last year). According to the Android site it can be used to Analyze your Application&#8217;s UI. In fact it is a very nice tool to quickly get an overview of how the UI of an app is structured. UI Automator simply grabs the screen and shows you all views present. Here&#8217;s a screen of the Play Music app:</p>
<div id="attachment_2541" class="wp-caption alignnone" style="width: 590px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/play_music_in_ui_automator_viewer.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/play_music_in_ui_automator_viewer.png" alt="UI Automator Viewer displaying the hierarchy of the Play Music app" width="570" height="430" class="size-full wp-image-2541" /></a><p class="wp-caption-text">UI Automator Viewer displaying the hierarchy of the Play Music app</p></div>
<p>On the left is the UI, on the right the hierarchy at the top and some properties of the currently selected element at the bottom. As you can see I have selected a tiny image at the bottom right corner of the album shot (whatever it is for).</p>
<p>But the big downside of this tool is that it only shows what you can see. And if you wonder, why something is <em>not</em> visible, it can&#8217;t help you. Which I learned the hard way some days ago <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I extracted parts of the container&#8217;s attributes to a common style. Then I applied this style to the other containers and deleted unnecessary attributes. And by doing so I deleted one attribute too many of a <code>LinearLayout</code> &#8211; the <code>android:orientation</code> attribute. A <code>LinearLayout</code> is horizontal by default and since I already had a <code>TextView</code> inside the container (the box header) any additional view wouldn&#8217;t be visible.</p>
<p>Lint normally warns about that, but in my case I add the views in the code &#8211; and thus Lint couldn&#8217;t catch the problem. This silly mistake caused me to look in all directions, but not the right one. For way too long!</p>
<p>Here&#8217;s what it looked like:</p>
<div id="attachment_2556" class="wp-caption alignnone" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/actionviews_demoapp_missing_orientation_attribute.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/actionviews_demoapp_missing_orientation_attribute-153x300.png" alt="The demo showing the container without the links" width="153" height="300" class="size-medium wp-image-2556" /></a><p class="wp-caption-text">The demo showing the container without the links</p></div>
<p>In retrospect it&#8217;s obvious what went wrong and I wonder why I thought of other reasons at all, but well, one is always wiser in hindsight <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  I finally found the missing attribute using a plain old diff and having a closer look at what I actually had removed. But I could have spotted it earlier, had I known about UI Automator&#8217;s restriction to visible UI elements. There is a button &#8220;Toggle NAF Nodes&#8221; but that doesn&#8217;t help here either. This button is only useful to see elements which are visible but not reachable via navigational controls like a D-pad.</p>
<p>Another Android tool, <a href="http://developer.android.com/tools/debugging/debugging-ui.html" title="Documentation of Android's Hierarchy Viewer">HierarchyViewer</a>, could have saved me. This tool is so darn slow that I never really liked it. Which is why I had hoped (thought, actually) UI Automator Viewer would be enough.</p>
<p>HierarchyViewer can be extremely useful, though. It really shows <em>any</em> view that is part of the hierarchy. Visible or not! So let me show you the hierarchy of my demo app, before I corrected my <code>LinearLayout's</code> orientation in both tools.</p>
<p>In HierarchyViewer I immediately see that all my links had been added. But they were outside of the right edge of the screen. The bold red line is where my view is <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<div id="attachment_2542" class="wp-caption alignnone" style="width: 590px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/hierarchy_viewer_showing_my_missing_view.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/hierarchy_viewer_showing_my_missing_view-1024x640.png" alt="Hierarchy Viewer showing my missing view" width="570" class="size-large wp-image-2542" /></a><p class="wp-caption-text">Hierarchy Viewer showing my missing view</p></div>
<p>Now the same view in the UI Automator Viewer (with the NAF toggle on):</p>
<div id="attachment_2554" class="wp-caption alignnone" style="width: 590px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/ui_automator_viewer_not_showing_missing_views1.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/04/ui_automator_viewer_not_showing_missing_views1.png" alt="UI Automator viewer isn&#039;t showing all the views present in the LinearLayout" width="570" height="441" class="size-full wp-image-2554" /></a><p class="wp-caption-text">UI Automator viewer isn&#8217;t showing all the views present in the LinearLayout</p></div>
<p>So, don&#8217;t get me wrong: I know that UI Automator Viewer&#8217;s main task is to analyze your UI before writing  <code>uiautomator</code> tests, but it would have been nice nonetheless if it could have been used for this as well. It&#8217;s a much nicer tool than Hierarchy Viewer. </p>
<h3>Monkey</h3>
<p>As a last step before releasing, I did a <a href="http://developer.android.com/tools/help/monkey.html" title="Documentation of Android's Monkey tool">Monkey</a> run. Monkey is a tool that simulates random clicks and interactions with the devices. No user would do it that way, obviously, but by doing so monkey uses combinations and clicks on places you never would do.</p>
<p>By executing it&#8217;s random actions, Monkey helps you to find weak spots like Application Not Responding problems or unexpected crashes at odd places. Monkey uses the app in unexpected ways. Ways, of which we think, that no user in his right mind would choose them. But users do! Not because of their state of mind, but because the UI is not as intuitive as we thought. Or because they try to achieve goals that we didn&#8217;t think of.</p>
<p>While Monkey runs, the screens of your app flash in quick succession and you see all kind of button presses and so on. </p>
<p>As soon as a problem appears, Monkey stops and shows a modal dialog. One of the very rare cases where a modal dialog is okay. While monkey is running the devices isn&#8217;t usable anyway &#8211; and you want to see when something goes wrong.</p>
<p>A warning though: Do not use Monkey for arbitrary apps on your device. As I&#8217;ve said, it does all kind of things &#8211; which means that your data is probably in a bad shape afterwards <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>With that said, it&#8217;s finally time for you to go over to the <a href="https://bitbucket.org/grokkingandroid/actionviews" title="Bitbucket project page for the ActionViews demo">Bitbucket project page</a> and grab the sources. Let me know any suggestions you have. Thanks!<br />
<img src="http://vg03.met.vgwort.de/na/3ebb2ea462ac44b6b8f700742669b6fe" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/actionviews-sample-app-is-on-bitbucket/">ActionViews Sample App is on Bitbucket</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/jDt4doZkr0k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/actionviews-sample-app-is-on-bitbucket/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/actionviews-sample-app-is-on-bitbucket/</feedburner:origLink></item>
		<item>
		<title>SQLite in Android</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/U3-9BagfuRs/</link>
		<comments>http://www.grokkingandroid.com/sqlite-in-android/#comments</comments>
		<pubDate>Thu, 28 Mar 2013 06:58:45 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[SQLite Manager]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/wordpress/?p=331</guid>
		<description><![CDATA[<p>SQLite is at the heart of Android&#8217;s database support. This database was developed with embedded environments in mind &#8211; and is used not only by Android but also by Apple&#8217;s iOS and Blackberry&#8217;s system as well as lots of other systems with low memory footprint and comparatively little CPU horsepower. Why SQLite in the first [...]</p><p>The post <a href="http://www.grokkingandroid.com/sqlite-in-android/">SQLite in Android</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">SQLite is at the heart of Android&#8217;s database support. This database was developed with embedded environments in mind &#8211; and is used not only by Android but also by Apple&#8217;s iOS and Blackberry&#8217;s system as well as lots of other systems with low memory footprint and comparatively little CPU horsepower.</p>
<h3>Why SQLite in the first place?</h3>
<p>Of course there is a reason why SQLite is so dominant in the embedded and also the mobile world. The main reasons are </p>
<ul>
<li>Low memory consumption</li>
<li>Ease of use</li>
<li>Free availability</li>
</ul>
<h4>SQLite in Android consumes very little memory</h4>
<p>While SQLite&#8217;s memory footprint starts at about 50 kilobyte it&#8217;s remains low even for bigger projects with more complex data structures (at about a few hundred kilobytes). Keep in mind: In the mobile world the memory <em>per process</em> as well as <em>total usage of memory</em> is limited compared to desktop systems. Gladly SQLite should not add too much burden to the memory consumption of your app.</p>
<h4>SQLite is easy to use</h4>
<p>SQLite is a serverless system. I will detail what this means in the next section, but it makes handling of the database that much easier. No need for configuration files or complicated commands. You definitely do do not want these on mobile systems. Those systems must run out of the box without forcing the user to manually configure anything or forcing the developers to consider additional constraints.</p>
<h4>SQLite&#8217;s source code is released under the public domain</h4>
<p>SQLite has a huge commercial backing by the likes of Google, Adobe, Mozilla or Bloomberg. And it is used in many, many products and open source projects. The project is maintained actively so one can expect further imrpovements as well as optimizations in the future. Android for example uses ever newer versions in its SDKs to make use of these improvements.</p>
<h3>SQLite is not like any other database</h3>
<p>Though SQLite offers <a href="http://sqlite.org/lang.html" title="Supported SQL statements">quite an impressive feature set</a> given its size, it differs in many aspects from a conventional database system:</p>
<ul>
<li>SQLite is serverless</li>
<li>SQLite stores data in one database file</li>
<li>SQLite offers only a few data types</li>
<li>SQLite uses manifest typing instead of static types</li>
<li>SQLite has no fixed column length</li>
<li>SQLite uses cross-platform database files</li>
</ul>
<p>I will delve into each of these points a bit deeper &#8211; and add another one that&#8217;s only relevant if you want to support older Adroid versions.</p>
<h4>SQLite is serverless</h4>
<p>There is no SQLite process running at all. You use SQLite more like a library which helps you to access the database files. You do not need to configure the database in any way. No port configuration, no adding of users, no managing of access levels, no tablespace setup and what not. You simply create the database files when you need it. I will cover how to create a database in the next part of this tutorial series.</p>
<h4>All data is stored in one single database file</h4>
<p>SQLite uses one file to store all the contents of your database. This file contains the main data, as well as indices, triggers and any meta data needed by SQLite itself. Newer versions add a journal file which is used during transactions.</p>
<h4>SQLite offers fewer datatypes</h4>
<p>The following table shows all types supported by SQLite. If you use other types (like varchar) in your CREATE TABLE statement SQLite maps them as closely as possible to any of these types.</p>
<table>
<caption>SQLite datatypes</p>
<tr>
<th>Type</th>
<th>Meaning</th>
</tr>
<tr>
<td>NULL</td>
<td>The null value</td>
</tr>
<tr>
<td>INTEGER</td>
<td>Any number which is no floating point number</td>
</tr>
<tr>
<td>REAL</td>
<td>Floating-point numbers (8-Byte IEEE 754 &#8211; i.e. double precision)</td>
</tr>
<tr>
<td>TEXT</td>
<td>Any String and also single characters (UTF-8, UTF-16BE or UTF-16LE)</td>
</tr>
<tr>
<td>BLOB</td>
<td>A binary blob of data</td>
</tr>
</table>
<p>The biggest problem here is the missing datetime type. The best thing to do is to store dates as Strings in the <a href="http://en.wikipedia.org/wiki/ISO_8601" title="Wikipedia page about the ISO 8601 format">ISO 8601 format</a>. The string to represent the 28th of March 2013 (the day of publishing this post) would be &#8220;<code>2013-03-28</code>&#8220;. Together with the publishing time it would look like this: &#8220;<code>2013-03-27T07:58</code>&#8220;. Stored this way SQLite offers some date/time functions to add days, change to the start of the month and things like that. <strong>Note</strong>: In contrast to ISO 8601 SQLite doesn&#8217;t offer any timezone support.</p>
<p>Also missing is a boolean type. Booleans have to be represented as numbers (with 0 being false and 1 being true).</p>
<p>Although a blob type is listed in the table above, you shouldn&#8217;t use it on Android. If you need to store binary data (e.g. media-files) store them on the file system and simply put the filename in the database. More on SQLite types can be found on the <a href="http://sqlite.org/datatype3.html">SQLite project page</a>.</p>
<h4>SQLite doesn&#8217;t use static typing</h4>
<p>Any type information in SQLite is dependent on the <em>value</em> inserted, not on the data definition of the <code>CREATE TABLE</code> statement. Let&#8217;s say you create a column as an <code>INTEGER</code> column. Then you might still end up with <code>TEXT</code> entries in this column. That&#8217;s perfectly legal in SQLite &#8211; but to my knowledge in no other relational database management system. </p>
<p>This reliance on the value is called manifest typing &#8211; something in between static and dynamic typing. In <a href="http://www.amazon.com/gp/product/1590596730/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1590596730&amp;linkCode=as2&amp;tag=grokkandro-20" title="Amazon.com link to 'The Definitive Guide to SQLite' by Mike Owens">Mike Owens&#8217; book on SQLite</a> you can find a very good and much more detailed explanation of SQLite&#8217;s typing.</p>
<h4>SQLite has no fixed column length</h4>
<p>If you look at the table above you see that there is only a definition for text, but not for varchar(xyz), where you can limit the column to an arbitrary length. In SQLite any TEXT value is simply as long as it is. SQLite adds no restrictions. Which might be pretty bad. To enforce a restriction, you have to do this in your code. SQLite won&#8217;t help you. On the other hand you will not get into any trouble if Strings get too long or numbers too large. Well, you will not get any <code>SQLExceptions</code> &#8211; though it might break your code in other ways or destroy your UI!</p>
<h4>SQLite&#8217;s database files are cross-platform</h4>
<p>You can take a file from a device put it on your laptop and start using it as if you created it on your laptop from the outset.</p>
<p>It might come handy to pull the database file from the device (or your emulator) and run queries from within your development machine. Especially if you want to use tools with a graphical user interface. One of the best know is the SQLite Manager extension for Firefox which you might prefer to sqlite3 in some cases (see screenshot).</p>
<div id="attachment_2510" class="wp-caption alignnone" style="width: 590px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/03/sqlitemanager_music.db_select_statement.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/03/sqlitemanager_music.db_select_statement-1024x601.png" alt="SQLite Manager showing the results of an SELECT statetment" width="580" height="340" class="size-large wp-image-2510" /></a><p class="wp-caption-text">SQLite Manager showing the results of an SELECT statetment</p></div>
<p>Also you sometimes might want to prepare the database on your development machine and put a database onto your device which contains the needed set of data like a very large dataset to test for performance or a defined database for starting automated tests.</p>
<p>Thanks to SQLite&#8217;s cross platform file format it is also possible to deliver a prefilled database with your app to your users. <a href="https://plus.google.com/104992412719307414985" title="Jeff Gilfelt's profile page on Google plus">Jeff Gilfelt</a> has written a library to help you with it. You can find his <a href="https://github.com/jgilfelt/android-sqlite-asset-helper" title="Github's project page of Jeff Gilfelt's Android SQLite Asset Helper library">Android SQLite Asset hHelper library</a> on github.</p>
<h4>SQLite offers a special kind of table for fast text searches</h4>
<p>To help developers create fast text searches SQLite offers also a special kind of database table. The so called FTS3/FTS4 tables. FTS stands for &#8220;full text search&#8221;. You have to create special tables for it to work and use slightly different SELECT statements (and rarely special INSERT statements) to use them efficiently. But if you do so, you gain tremendous performance improvements for text only search. I will cover FTS in an extra blog post.</p>
<h4>Older versions of SQLite do not support referential integrity</h4>
<p>The version of SQLite integrated into older versions of Android (3.4 in the early days, later on 3.5.9) doesn&#8217;t support referential integrity. This changed with Android 2.2. Thus this problem should fade away pretty soon and is only relevant if you want to support API level 7 or lower. In this case this limitation forces you to take special care when using foreign keys within tables. Since databases on Android are usually way less complex than those of enterprise projects this might not be as bad a problem as it sounds. But still, you have to be careful. Of course being careful is never wrong <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>For more information on how SQLite differs from other database go to the <a href="http://www.sqlite.org/different.html" title="SQLite website">SQLite website</a>.</p>
<p>Of course what is not different from other SQL Database systems is the use of SQL to create tables, and query and update them. And of course <strong>SQLite is relational</strong> &#8211; that is, you deal with tables which store your data and the results of your queries also take the form of tables.</p>
<h3>Where are those database files on Android?</h3>
<p>As I have mentioned, a database in SQLite is more or less simply a file accessed through the SQLite API. In Android these files are by default stored within the </p>
<p><code>/data/data/&lt;<em>package-name</em>&gt;/databases</code></p>
<p>directory. Thus if your package is called <code>com.grokkingandroid.android</code> and your database is called &#8220;sample.db&#8221; the actual file would be <code>/data/data/com.grokkingandroid.android/databases/sample.db</code>. </p>
<h3>Keep security in mind</h3>
<p>As usual in Android the access rights of the database file determine who can use your database. If you follow the standard way presented in the following posts of this series, your database file will be located within the private directory of your app. This means that your app owns the database file and no one else can access it. Even using the other less common ways to create the database you can only grant access to the file. Thus others can access all of your database or nothing. There is no middle ground. </p>
<p>Still: You should never rely on data being safe from prying eyes in the database. <strong>Any sensitive data should be encrypted.</strong> Very sensitive data should not be stored on the device at all. Keep in mind that if the device gets lost, any misbehaving finder of the device can gain access to the database file as well as to your app. On a rooted device all files can be read. Apps like SQLite Editor make it easy to read even sensitive data &#8211; if they are not encrypted:</p>
<div id="attachment_2516" class="wp-caption alignleft" style="width: 590px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/03/sqlite_editor_showing_tables_of_contacts_app.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/03/sqlite_editor_showing_tables_of_contacts_app-1024x640.png" alt="SQLite Editor showing the two databases of the contacts app" width="580" height="340" class="size-large wp-image-2516" /></a><p class="wp-caption-text">SQLite Editor showing the two databases of the contacts app</p></div>
<p>In cases where data privacy is of utmost importance, you have to revert to secured services or force the user to enter a secret every time before encrypting and storing the data or reading and decrypting them respectively.</p>
<h3>Android differs from the standard Java way</h3>
<p>Apart from SQLite&#8217;s own peculiarities there is also the way Android deals with this database. First of all SQLite is an integral part of Android. <strong>Every app developer can rely on SQLite being present on an Android system.</strong> Though which version of SQLite is dependent of the SDK which the device uses. &#8211; which of course is a good thing, since SQLite is developed actively and future Android versions should make use of those improvements.</p>
<p>The biggest Android-speciality of course is how Android treats the database. <strong>Android doesn&#8217;t use JDBC</strong>. And so also no JDBC driver for SQLite. This means that you are stuck with using SQLite the Android way or using another database which you have to include in the download of your app (though I see no need for any other database). It also means that you have to learn a new way to deal with databases. Any prior JDBC-knowledge is of no use in the Android world. The rest of this series will be about the special API Android provides to deal with SQLite in your JAVA-code. </p>
<h3>Lessons learned</h3>
<p>You have seen why Google chose SQLite as the underlying database for Android&#8217;s apps. It has many advantages, most of all it&#8217;s low memory footprint and it&#8217;s ease of use.</p>
<p>Furthermore you learned about how SQLite differs from most other relational database systems and what implications this might have.</p>
<p>With this knowledge you are well prepared to start using SQLite. In the next installments of this series I&#8217;m going to show you how to create the database, how to insert, update and delete data and how to query those records. I&#8217;m also going to post about SQLite&#8217;s full text searches feature and how to use it.</p>
<p><em>Disclaimer: This post contains a link with my Amazon.com referral ID. For each sale this provides me with a small commission. Thank you for your support!</em><br />
<img src="http://vg03.met.vgwort.de/na/ad379942b07848fda855251187463fbb" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/sqlite-in-android/">SQLite in Android</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/U3-9BagfuRs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/sqlite-in-android/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/sqlite-in-android/</feedburner:origLink></item>
		<item>
		<title>Two Days at the moosecon Conference</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/DDc_hSJPTss/</link>
		<comments>http://www.grokkingandroid.com/two-days-at-moosecon/#comments</comments>
		<pubDate>Sat, 09 Mar 2013 11:21:53 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Conference]]></category>
		<category><![CDATA[moosecon]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2435</guid>
		<description><![CDATA[<p>This year the German IT trade show CeBIT tried something new: A conference for mobile developers, called moosecon (mobile operating system conference). The conference lasted three days, of which I was present at two, Wednesday and Thursday. Here&#8217;s a short recap of the talks, I visited. Wednesday &#8211; March 6, 2013 / day one Thanks [...]</p><p>The post <a href="http://www.grokkingandroid.com/two-days-at-moosecon/">Two Days at the <i>moosecon</i> Conference</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">This year the German IT trade show <a href="http://www.cebit.com" title="German IT trade show CeBIT">CeBIT</a> tried something new: A conference for mobile developers, called <a href="http://www.moosecon.com/" title="Website of the moosecon conference">moosecon</a> (mobile operating system conference).</p>
<p>The conference lasted three days, of which I was present at two, Wednesday and Thursday. Here&#8217;s a short recap of the talks, I visited.</p>
<h3>Wednesday &#8211; March 6, 2013 / day one</h3>
<p>Thanks to the German railway system I was late. Nearly one hour later than expected. Thus I missed much of the first talk of the conference. And to make matters worse, the conference organizers decided to change the schedule. </p>
<h4>HTML5 for the mobile web &#8211; Firefox OS<br />
Chris Heilmann, Mozilla</h4>
<p>The train delay and the reorganization both resulted in me missing most of Chris Heilmann&#8217;s talk about Firefox OS. From what little I could hear of the talk, it probably was the most interesting talk of day one. Especially since I am very interested in Firefox OS. </p>
<p>Those that follow me at Google plus know that I hope  for FirefoxOS to become a viable competitor to iOS and Android &#8211; even though I remain sceptic of the chance to get there. I think it can only be good for innovation in the field if there is a bit more competition and if there are more <em>open</em> players. I am an Android developer and intend to stay one, but this doesn&#8217;t mean that I might not have a look at other systems. </p>
<p>Right now I mostly despise HTML5 apps on Android &#8211; simply because they do not fit. They often lack the necessary visual integration into Android and just do not feel right. That&#8217;s not too surprising, because right now most apps, if not all HTML5 apps, are created to save money while deploying the same app on multiple platforms. That&#8217;s something that simply doesn&#8217;t work too well. It has been a problem for Java apps on the desktop for years and it&#8217;s no different for HTML5 &#8211; so I guess it&#8217;s not something that will just vanish when HTML5 gets more mature, it&#8217;s API more stable and unified across browsers and so on.</p>
<p>Nevertheless I think there <em>is</em> a place for HTML5: For apps within a browser or if HTML5 apps are first class citizens of the OS as in Firefox&#8217; case. In the latter case the problems that apply to webapps on Android are simply no problems, because all apps are webapps &#8211; with probably some kind of standard look &amp; feel as well. Performance problems though <em>might</em> remain.</p>
<p>What I heard of Heilmann&#8217;s talk centered mostly around Web-Activities. Those more or less resemble intents. Google had introduced a proposal of Web-Intens before &#8211; but from what I understood at the conference, Google doesn&#8217;t use those any more and both now work together on Web-Activities (though this was a bit vague).</p>
<p>I still haven&#8217;t seen Firefox OS in action and if Chris has shown a live demo I must have been to late for it. But from this talk, I still consider it to be an interesting approach.</p>
<p>If you want to know more about developing for Firefox OS, visit <a href="https://marketplace.firefox.com/developers/" title="Mozilla's developer site for FirefoxOS">Mozilla&#8217;s developer site for Firefox OS</a>. </p>
<h4>Effects of Firefox OS<br />
NN,Telekom</h4>
<p>Someone from Telekom&#8217;s management replaced Martin Kurze, who got ill. I didn&#8217;t get his name, but he was pretty high up. Given that he was management it was surpirsing that his slides were the worst ones presented. Whatever you can do wrong on a slide, you could find it here. But apart from that the talk was more interesting than I had expected. </p>
<p>He outlined why the Telekom is supporting Firefox OS. Purportedly because Telekom is all for openness. He made a big fuss about HTML5 and that this is an open standard and what not. Yes, it is and that&#8217;s what I like about it as well. But in the case of Telekom I guess it has more to do with them not wanting Google, Apple or Microsoft to be the only ones profiting.</p>
<p>Be it as it may, this carrier as well as many other carriers is supporting Mozilla to create another competitor and to keep relevant and get a share of the revenue. While I couldn&#8217;t care less who get&#8217;s the biggest piece of the cake, it could prove important for Mozilla in getting some traction &#8211; especially in markets in which customers are still using feature phones by a large margin (Telekom for example starts with handsets in Poland).</p>
<h4>Successful Inhouse Enterprise Apps<br />
Patrick Blitz, Weptun</h4>
<p>This talk centered mainly around two aspects: Security and Connectivity. The talk was too high-fly for me to really like it. Nothing wrong with giving an overview. But moosecon is a developer conference. And as such I would have liked to see some remarks about difficulties and problems in implementing each of the solutions. </p>
<p>Maybe he should have sticked to just covering security. After all connectivity is a problem common to nearly all apps and thus not specific to in-house enterprise apps. </p>
<p>Enterprise apps nearly always have to deal with very sensitive data. Data that has to be kept private &#8211; no matter what. I really would have liked to hear more about that. </p>
<p>The bad audio situation didn&#8217;t help the talk either. Not the fault of the speaker who spoke clearly and articulate, but of the conference setup. More about that later on.</p>
<p>I think a bit more in-depth coverage of what the biggest problems are (from a developer point of view) would have helped this talk.</p>
<h4>Creating Backends in Minutes<br />
Lutz Kohl and Philipp Michel, Apiomat</h4>
<p>The speakers presented backends as a service (BaaS) in general and exemplified the key points with apiomat, the solution of their company.</p>
<p>Obviously the speakers had an interest to present BaaS in the best possible light &#8211; and they did a good job at this. There are very good reasons for using backend services in the mobile environment. Their main point was that it reduces time to market, that it helps safe costs and that you do not have to care about getting the necessary amount of power and of getting this right. Time to market is probably correct, depending on the flexibility of the BaaS provider. I also think that it&#8217;s difficult to estimate the necessary computing power and that for many projects it&#8217;s an unnecessary burden to have to think about load balancing, redundancy, failover solutions and what not. So far I&#8217;m in the BaaS camp.</p>
<p>But I think the speakers purposefully underestimated the complexity around REST &#8211; which will remain independent from using a BaaS solution or a selfmade one. Thus I do not believe their cost estimate at all &#8211; but well, of course they were a bit biased <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />   Granted, BaaS probably <em>is</em> cheaper, but the difference is much smaller than presented here.</p>
<p>They showed how to use apiomat, how to generate code from their website, where to create custom business logic besides simple CRUD-logic and how to integrate apiomat into your app. Both speakers did a good job, but some stuff could have been a bit more detailed. Also the dashboard and any reports would have been interesting.</p>
<p>Nevertheless BaaS solutions are interesting and can help your project siginificantly. Apiomat is a German solution targeting the European market, so maybe they are the right solution for you. Which BaaS provider to use comes down to a business and a trust decision. The latter is very important since BaaS requires a trustworthy partner. And don&#8217;t forget the privacy aspects as well. At least we Germans are very sensitive when it comes to this. </p>
<h4>Push Notifications<br />
Benjamin Broll, Little Postman</h4>
<p>Benjamin talked about push notifications and how complex this can get &#8211; especially if you want to use push for different target platforms. The latter is made worse because each platform has it&#8217;s own notification model and each provider handles communication between your backend and the notification delivery service (e.g. Google Play Services for Android or Amazon Device Messaging if you care about the Kindle Fire). He detailed the problems you have to deal with if you want to do so on your own. Well, of course he was on a mission as well &#8211; but this part of his talk was really good!</p>
<p>He also stated reasons why push is a good solution and that it might help user satisfaction &#8211; especially if you find innovative uses for push &#8211; the examples he gave were also interesting to hear.</p>
<p>So far so good. But why not show how to do all that with Little Postman? After all, that&#8217;s his company and there&#8217;s nothing wrong to present your stuff if your general points are presented in a more or less neutral fashion. I think he missed an opportunity here to drive home the message, that Little Postman could be the solution of choice for you.</p>
<h4>Overall impression of day one</h4>
<p>I have heard some nice talks but obviously missed a very large part of the most interesting talk. All in all it was too little code and often too high-fly for a developer conference. </p>
<p>But the worst thing was, that it didn&#8217;t get the attention that is so important for conferences. Attendee numbers were quite low &#8211; especially in the closed area. So one of the great by-products of conferences &#8211; being able to meet people you know via the many social channels as well as to network with other devs &#8211; was nearly completely missing for me.</p>
<p>Audio quality also was a big problem &#8211; at times nearly unbearable. The sound level at trade shows is always very bad. But in this case the open and closed stages were too close to each other, which sometimes made listening unnecessary hard.</p>
<h3>Wednesday &#8211; March 7, 2013 / day two</h3>
<p>I was on time &#8211; great. But there had been a shuffling of talks once again. The first two talks at the open stage were swapped. Thus I couldn&#8217;t hear the Google TV talk I originally had planned to go to and instead listened to a white-collar talk I hadn&#8217;t had on my agenda.</p>
<h4>Cross Platform for White Collar Workers<br />
Marcus Ross, Zahlenhelfer Consulting</h4>
<p>Marcus is developer and project manager &#8211; but in this talk he was all project manager. The title of the talk says it all: It was no technical talk.</p>
<p>Obviously Marcus thinks much more of HTML5 apps as a cross-platform solution than I do. He believes that they can be a good fit for apps, that must run on multiple platforms. He mitigated this by saying that it depends on the requirements, but still&#8230;</p>
<p>According to Marcus, often some kind of hybrid is needed where you access certain hardware features via a wrapper API and otherwise use HTML5 to develop your app. Another point of Marcus was, that unless you are doing in-house stuff or cannot use the app market for business reasons (e.g. for publishers the Apple app store often is no option), you should always use at least some kind of wrapper to market-enable your app. </p>
<p>I think though, that this is risky: Putting your app on the platform specific appstore might make marketing sense, but it also sets certain expectations of the customers. I think HTML5 apps should stay on the web, be clearly recognizable as web apps and as such should use a standalone UI that doesn&#8217;t try to mimic the native UI. Marcus obviously disagrees and showed samples of apps that try to resemble native apps as closely as possible. Well being an Android native developer, it&#8217;s kind of my duty, to disagree <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>If you wonder how this fits in with my Firefox OS hopes, keep in mind that on Firefox OS it&#8217;s a completely different story &#8211; there HTML5 is native! And I wouldn&#8217;t recommend to use a Firefox OS app on Android within some native wrapper. I have no problems with them though, if they run within a browser! </p>
<p>At the end the organizers started talking at the second stage &#8211; which caused many (including me) to leave this stage. But then the talk actually didn&#8217;t begin for another five minutes. Sorry, but this shouldn&#8217;t have happened. The organizers should have been more careful. It simply was not fair to Marcus. </p>
<h4>Ugly thruth about HTML5<br />
Robert Virkus, Enough Software</h4>
<p>This talk was some kind of counterpoint to the previous one. Robert prefers native. And it&#8217;s not just what I&#8217;ve written above, but there are technical reasons why cross-platform is not as cross-platform as management thinks. Most platforms (Microsoft&#8217;s Windows Phone OS and Mozilla with Firefox OS being two exceptions) use Webkit as the default rendering engine, but that&#8217;s just one part of the story. When it comes to Javascript &#8211; and you will need to use Javascript &#8211; each vendor uses its own engine. And even worse: Webkit is not the same everywhere. There are tons of compile time flags and Android uses different ones then iOS. Thus you can use some stuff on Android which isn&#8217;t available on iOS and vice versa.</p>
<p>Than he mentioned the <a href="http://en.wikipedia.org/wiki/Uncanny_valley" title="Wikipedia on the uncanny valley hypothesis in robotics">uncanny valley</a>. That&#8217;s a robotics theory stating that when humanoids get more and more close to actual humans people at first like this, until it suddenly changes and people start to strongly dislike those robots &#8211; until approval rises again when the humanoid is nearly indistinguishable from a real human. </p>
<p>He applied this uncanny valley theory to mobile apps. People will dislike your app if it tries to be like a native app, but fails to actually deliver. Thus his advice for any HTML5 apps: &#8220;Don&#8217;t mimic the native UI &#8211; use an HTML5 UI&#8221;. Couldn&#8217;t agree more!</p>
<p>BTW: That&#8217;s the reason why HTML5 works for games that do not need native speed. Games most often do follow their own style and thus do not mimic the native UI anyway. And since games never did, customers won&#8217;t wonder about this. Instead they expect games to be different. In my opinion games are thus currently the only real option for HTML5 apps.</p>
<h4>Mobile Market News<br />
Sacha Pallenberg, MobileGeeks</h4>
<p>Well, i don&#8217;t know. I&#8217;m no big fan of him. But he definitely is a great speaker and he knows his stuff (mobile hardware) very well. Thus this talk was indeed very interesting. His talk was lively and it was obvious that he really enjoys his field and also talking about it. His talk was hampered by severe technical problems (the beamer going off every now and then for roughly two/three minutes) but he managed to work around that effortlessly. </p>
<p>First he talked about SoCs. Something I&#8217;m not much interested in.</p>
<p>Interesting though his take on the battle of mobile operating systems and if competitors to iOS and Android can play any significant role. In short: He&#8217;s not very optimistic about any of the other platforms &#8211; with the exception of Windows Phone. One point for FirefoxOS is that it has the backing of many carriers, but he doesn&#8217;t believe that it will help them that much. </p>
<p>What took me totally by surprise was his statement, that Nokia managed to keep it&#8217;s ship afloat because of its Windows Phone transition. Huh? Right now I still think this strategy is not working too well for them. But let&#8217;s wait what the future might hold. Predictions in this area are not worth too much anyway <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h4>Lessons Learned from Prime Guide<br />
Markus Junginger, greenrobot</h4>
<p>Finally two Android related talks. Markus talk about <a href="https://play.google.com/store/apps/details?id=de.greenrobot.tvguide" title="Prime Guide on the Play store">Prime Guide</a> &#8211; an Android only TV programme app that I highly recommend and use myself &#8211; came first. His talk contained some interesting surprises. Lessons learned are always great and probably should be covered more often (on conferences as well as on blogs or in magazines). Why not learn form others?</p>
<p>The Prime Guide team took great care to deliver an outstanding Android experience &#8211; a necessity to compete in the crowded TV-programme market. And it can be seen: As a user of this app, I can confirm that it indeed performs well and looks great. The good ratings of the app are another proof that they did a good job. </p>
<p>The devs made heave use of libraries or created some while developing the app. Something Markus recommends highly to all Android devs. But even with using libraries, the app took still way longer than expected &#8211; not least because its developers had to move to customer projects and couldn&#8217;t work continously on the app. Markus estimated the total amount for the app was more than one person year. </p>
<p>Especially fragments gave them headaches. To quote: &#8220;Fragments are one of the most difficult APIs&#8221; in Android. Especially together with multi-threading and funny (or rather not so funny) life-cycle issues. </p>
<p>Prime Guide is a good example for why BaaS makes sense. They have two big peaks when it comes to backend hits: In the evening when people actually start to watch TV they use this app the most. From the graph presented it&#8217;s an enormous spike and to cope with that, you definitely have to use a cloud based service &#8211; or use a set-up that idles away most of the day. The second spike comes from when the server downloads and processes TV programme data.</p>
<p>In his talk, Markus mentioned some problems with app engine. One of them stuck with me: When they started out, AppEngine offered no SQL database. And according to Markus &#8220;that&#8217;s not cool&#8221; at all (so much for the NoSQL rage) &#8211; but instead caused them to adapt the data model to app engines&#8217; special needs. </p>
<p>The thing though, that surprised me the most was his statement, that they shouldn&#8217;t have published the app for all device categories at the same time. Since I think this app is extremely well suited for tablets, I asked him if they wouldn&#8217;t have been missing out had they done a phone only app first. Markus states that they could have released the app much earlier had they made a phone only app. I guess there is no arguing about that. He also states that when they started out Android tablets had not been as wide-spread as nowadaays. Granted, but I still wonder. </p>
<p>Would their initial rating (4.6 in the first week) have been as good? Wouldn&#8217;t many have complained and demanded a tablet version? Which might have caused them to rush one with potential implications for the overall app quality. Finally a tablet later strategy might have lead to some serious refactoring when adding the tablet-related aspects later on. With probably even more complexity and headaches. I don&#8217;t know. Markus has way more experience than I have, so I really would like you to chime in. What do you think about releasing for the phone first? And is this still a viable strategy &#8211; now that many more tablets are in use? Please let me know on G+ or in the comment section.</p>
<p>Oh, and here&#8217;s one last but important advice from Markus: Release early! Don&#8217;t wait till it&#8217;s perfect! Users might have different needs anyway (in their case for example they wanted more channels within the app).</p>
<p>In short: Great talk!</p>
<p><strong>Edit:</strong> After reading my draft, Markus send me some clarification about this: In this clarification he suggest to only offer the most essential functionality for tablets right from the beginning and to add more later on. Do not waste time with every detail on every screen for all three versions (Google TV, tablets and phones) but concentrate on phones and only for some especially central screens  on tablets. Even with this clarification I still would like to hear your thoughts on this in the comments!</p>
<h4>AB-Test Library for Android<br />
Hasan Hosgel, Immobilienscout24</h4>
<p>In his talk, Hasan Hosgel presented his library CustomersChoice, that you can use to enable AB-Testing within your apps. It&#8217;s an open source Android library and <a href="https://github.com/alosdev/CustomersChoice" title="CustomerChoice project page on github">the project page of CustomerChoice</a> is hosted on github.</p>
<p>Hasan first stated why he created it. The point is that product managers often have no clear idea which features are really useful or how to present those features. Usually you create a short user test to find out, but often you still don&#8217;t get a clear picture. That&#8217;s where this library comes into play.</p>
<p>While ImmobilienScout24 (Hasan&#8217;s employer) can afford customer surveys and user tests, small shops or indie developers sure can&#8217;t. Thus this library is even more useful.</p>
<p>After this he showed how to use the library. You only need a few lines of code to choose a variation and to report a success &#8211; if the user found and used the feature you test.</p>
<p>Configuration needs a bit more code but is still pretty straightforward. Configuration can be done in multiple ways. Either in code or by a JSON definition that the library can download from the web, read from the SD card or get from a resource definition within the app. Here you define the variants and their variations. A variant is one feature you AB-test. A variation is one specific implementation of this variant. So if you want to test which of three colors is the best this would be one variant with three variations.</p>
<p>Each variant has a name you later use in code. They also have optional start and end dates to scope the test. And you can set the ratios between the variations &#8211; the default being a uniform distribution of course.</p>
<p>Finally Hasan showed the library in action and it&#8217;s integration into his code. You can also download a <a href="https://play.google.com/store/apps/details?id=de.alosdev.customerschoice.demo" title="The demo of the CustomerChoice library in the Play Store">demo of Customer&#8217;s Choice</a> to have a look yourself.</p>
<p>My only beef with this library is it&#8217;s name. It suggest a conscious decision by customers about which features to implement in which ways. Which generally is no good idea. You should listen to customers, of course, but which features to implement and especially in which way should be your decision based on user goals, usability concerns, the direction you want to move forward in and the general style of your app. Thus I think CustomersChoice is a misleading name. </p>
<p>So to clarify: This library let&#8217;s you find out which possible implementation works best for your user base. Exactly what we sometimes need.</p>
<p>Good talk and an interesting library. I suggest to have a look at it.</p>
<h4>How Paypal uses Open Identity<br />
Tim Messerschmidt,Paypal</h4>
<p>Now, to be honest: If Tim hadn&#8217;t been in my Google plus circles I never would have watched this talk. Paypal is not my most liked service on the web. Apparently I&#8217;m not alone with it, because Tim tried to destroy any doubts about using a Paypal solution <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>First Tim explained the concept of identity within his talk. It&#8217;s mainly about authenticating a user. All those &#8220;Log in with Twitter&#8221; buttons basically allow you to use one account to access multiple websites.</p>
<p>And here is where Paypal comes in. For shopping sites you may not want to use your Twitter account but a more reliable partner that either already has your credit card information or which you trust enough to hand over your payment information.</p>
<p>Paypal uses OpenID Connect which, according to Tim, is much easier to use for us developers than plain OAuth 2 &#8211; even though it uses OAuth under the hoods. He explained that OAuth has developed in a direction where you basically need a custom implementation all the time without being able to leverage code reuse. Something that OpenID Connect seems to solve. Whether that&#8217;s true or not, I do not know &#8211; but I know that OAuth has a reputation of being a mess.</p>
<p>He also showed the different levels of information clients can get from Paypal. As usual the user gets a short list of what is offered by the provider (here Paypal) to the site. In Paypals case this ranges from just a confirmation of the name and the email address to the real-world address of the user to his age information. Finally Tim concluded his talk with a short demo.</p>
<p>Paypal might actually be the appropriate solution in some situations. But for now the only important thing for me is to know that it exists &#8211; should I ever have a need for it.</p>
<h3>Overall impression of day two</h3>
<p>Apart form two things this day was much better. Sound problems were not as pressing &#8211; especially since in the afternoon only one stage was used. The problem with the beamer &#8211; well this can happen. Not too much of a problem &#8211; though they were lucky that it happened while a seasoned speaker was on stage. Totally unacceptable was the early opening of the second stage while a speaker was giving his talk on the other stage. Given the sound condition it was no wonder that many people thought the next talk was starting.</p>
<p>Apart form the first talk, this day was more technical &#8211; which obviously is more to my liking. And this day I also met people I knew. I&#8217;ve met Hasan Hosgel at last years Google devfest in Berlin and together with others we stayed at c-base for quite some time in the evening. It was nice seeing him again &#8211; though I prefer the c-base atmosphere any day! I hope for another devfest this year. I also knew Markus Junginger, Matthias Friedrich (no speaker) and Tim Messerschmidt from Google plus. Great meeting them as well.</p>
<h3>How the moosecon should change</h3>
<p>I think the moosecon has a future, but it must improve in some areas. It should be more technical and more dev centric &#8211; or offer two slots: One for devs and designers and one for management. </p>
<p>Having mentioned designers: I wonder why they aren&#8217;t invited as speakers to these events? The design (as well as the usability, which is something completely different) plays an important part in the success of an app &#8211; still it&#8217;s ignored way too often. I&#8217;m a dev, I have no talent at all for design, but even I notice apps that are either too complicated to use (bad UX) or simply visually too off-putting to use. The one problem here of course is that UI and UX concepts of all platforms are vastly different. But so are the programming models.</p>
<p>I think speakers should be instructed to give a technical talk (unless the conference offers the two slots I mentioned above, in which case I only speak for the dev slot). To concentrate on those aspects that are most interesting to fellow devs like problems encountered and tips how to deal with them. Or talk about how to use your libraries/products, how to integrate them.</p>
<p>In general the conference must attract more people. The organizers must concentrate on that. Good talks are one way to achieve this, but not the only one. Maybe more hands-on stuff would help. Some kind of app-dev-contest, hackathon or what not. Or offer some power workshops. It was simply too little content. </p>
<p>Another possibility would be to only use two days but more stages. Given that the early as well as the last talks were not visited well it might also be worth to consider reducing the overall time on stage and offer other things like workshops afterwards.</p>
<p>As a final note: The catering was excellent. Thanks!<br />
<img src="http://vg03.met.vgwort.de/na/ea757253ecbe433ab461ecd1d74536d0" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/two-days-at-moosecon/">Two Days at the <i>moosecon</i> Conference</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/DDc_hSJPTss" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/two-days-at-moosecon/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/two-days-at-moosecon/</feedburner:origLink></item>
		<item>
		<title>Adding ActionViews to Your ActionBar</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/YO_inxbpvYA/</link>
		<comments>http://www.grokkingandroid.com/adding-actionviews-to-your-actionbar/#comments</comments>
		<pubDate>Fri, 08 Feb 2013 06:44:32 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Action Bar]]></category>
		<category><![CDATA[ActionViews]]></category>
		<category><![CDATA[android:actionLayout]]></category>
		<category><![CDATA[SearchView]]></category>
		<category><![CDATA[setActionView()]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2368</guid>
		<description><![CDATA[<p>As you have seen in the previous tutorials about ActionBarSherlock and the ActionBar, you can add action items easily and they show up either in the ActionBar itself or in the overflow menu. But so far all you could add were normal action items. And those consisted either of icons, of text or of a [...]</p><p>The post <a href="http://www.grokkingandroid.com/adding-actionviews-to-your-actionbar/">Adding ActionViews to Your ActionBar</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">As you have seen in the previous <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/" title="Adding ActionBarSherlock to Your Project">tutorials about ActionBarSherlock</a> and the <a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/" title="Adding ActionBar Items From Within Your Fragments">ActionBar</a>, you can add action items easily and they show up either in the ActionBar itself or in the overflow menu.</p>
<p>But so far all you could add were normal action items. And those consisted either of icons, of text or of a combination of both &#8211; depending on the available space and of the way you configured the items to show up.</p>
<p>That&#8217;s not always sufficient. Sometimes you would like to display a custom layout. And that&#8217;s what ActionViews are for.</p>
<h3>What are ActionViews</h3>
<p>Action views allow to display arbitrary layouts instead of the usual icons or texts. They were introduced in Honeycomb together with the ActionBar.</p>
<p>Of course the available place for your layout limits your possibilities. Since &#8211; by a large margin &#8211; most Android devices are phones, your layout should take this into consideration.</p>
<p>With Ice Cream Sandwich ActionViews were improved further. Since then Android does not always display them fully expanded but allows for a collapsed mode as well. In this mode ActionViews show an icon as usual and only when the user clicks on the icon does it expand to the full layout.</p>
<h3>When to use ActionViews</h3>
<p>Basically you use ActionViews when you need to replace the icon with something else or when you need a more interactive widget.</p>
<p>Android itselfs comes bundled with the SearchView that adds an <code>EditText</code> widget for search. I will cover this widget in the next section.</p>
<p>Another common use case is to replace an action item with a progress indicator when the action is bound to last longer. Most often this is used together with a refresh action item.</p>
<h3>Using Android&#8217;s SearchView</h3>
<p>Android comes with the <a href="https://developer.android.com/reference/android/widget/SearchView.html" title="Documentation of Android's class Searchview">SearchView</a> as the only bundled implementation of an ActionView.</p>
<p>I covered all you need to know about <a href="http://www.grokkingandroid.com/android-tutorial-adding-search-to-your-apps/" title="Android Tutorial: Adding Search to Your Apps">searching on Android</a> and <a href="http://www.grokkingandroid.com/android-tutorial-adding-suggestions-to-search/" title="Android Tutorial: Adding Search Suggestions">search suggestions</a> in previous tutorials. Here I will cover only how to make use of the <code>SearchView</code>.</p>
<p>Let me first show you some screenshots:</p>
<p><div id="attachment_2407" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/searchview_collapsed.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/searchview_collapsed-153x300.png" alt="Collapsed Searchview showing only the search icon" width="153" height="300" class="size-medium wp-image-2407" /></a><p class="wp-caption-text">Collapsed Searchview showing only the search icon</p></div><br />
<div id="attachment_2406" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/searchview_expanded.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/searchview_expanded-153x300.png" alt="Expanded Searchview showing the EditText field together with the search icon and the search hint" width="153" height="300" class="size-medium wp-image-2406" /></a><p class="wp-caption-text">Expanded Searchview showing the EditText field together with the search icon and the search hint</p></div><br />
<div id="attachment_2405" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/searchview_expanded_with_entered_text.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/searchview_expanded_with_entered_text-153x300.png" alt="Expanded SearchView with entered text" width="153" height="300" class="size-medium wp-image-2405" /></a><p class="wp-caption-text">Expanded SearchView with entered text</p></div></p>
<p class="clear">The first shows the action bar with the search icon &#8211; thus the action view is in collapsed mode. The second screenshot shows the view after the user has clicked on the icon. It expands to an <code>EditText</code> widget together with the search hint of <a href="http://www.grokkingandroid.com/android-tutorial-adding-search-to-your-apps/" title="Android Tutorial: Adding Search to Your Apps">your searchable configuration</a>. The microphone symbol is also the result of the search configuration file. The last screen shows the <code>EditText</code> widget after the user has entered some characters.</p>
<p>If you have added search capabilities to your app, getting the <code>SearchView</code> to support this is pretty easy. All you have to do is tell it about the search configuration. For this you need to get a <a href="https://developer.android.com/reference/android/app/SearchableInfo.html" title="Documentation of Android's SearchableInfo class">SearchableInfo</a> object from the <code>SearchManager</code> and call <code>setSearchableInfo()</code> with this object on the <code>SearchView</code> object used for your ActionBar. Well for me code is often the best explanation, so here is what you have to do:</p>
<pre class="brush: java; highlight: [6,7,8,9,10,11]; title: ; notranslate">
@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getSupportMenuInflater().
         inflate(R.menu.activity_actionview, menu);
   MenuItem item = menu.findItem(R.id.actionView);
   SearchView searchView = 
         (SearchView)item.getActionView();
   SearchManager searchManager = 
         (SearchManager)getSystemService(Context.SEARCH_SERVICE);
   SearchableInfo info = 
         searchManager.getSearchableInfo(getComponentName());
   searchView.setSearchableInfo(info);
   return true;
}
</pre>
<p>You should understand most of it from <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/" title="Adding ActionBarSherlock to Your Project">my previous tutorial on ActionBarSherlock</a>. New are the lines 6 to 11. These are where you add your search configuration to the <code>SearchView</code>.</p>
<p>As you can see in the code above, I use the <code>SearchView</code> together with ActionBarSherlock. ActionBarSherlock added a <code>SearchView</code> with its 4.2 release. As a deviation from ABS&#8217; normal API level 7 support, the <code>SearchView</code> only work from API level 8 onwards. The reason for this is that the <code>SearchableInfo</code> interface was added with API level 8. So a support for a <code>SearchView</code> prior to that makes no sense.</p>
<p>The version in ActionBarSherlock&#8217;s 4.2 release had some problems with search suggestions. These were fixed by <a href="https://plus.google.com/100594318038403965929/" title="Google+ profile of Matt Kranzler">Matt Kranzler&#8217;s</a> accepted <a href="https://github.com/JakeWharton/ActionBarSherlock/pull/653/files" title="Matt Kranzler's pull request to ActionBarSherlock">pull request to ABS</a>. But this fix is currently only available in the <a href="https://github.com/JakeWharton/ActionBarSherlock/tree/dev" title="ActionBarSherlock's dev branch containing important fixes for the SearchView">dev branch of ActionBarSherlock</a>.</p>
<p><strong>Update:</strong> With the 4.3 release of ActionBarSherlock <a href="https://github.com/JakeWharton/ActionBarSherlock/blob/master/CHANGELOG.md#readme" title="ActionBarSherlock's changelog for the 4.3 release">suggestions now work</a>. So if you want to use them, you have to include ActionBarSherlock 4.3 (or any follow-up releases).</p>
<p>The next screenshot shows the suggestions provider at work with ActionBarSherlock&#8217;s dev branch fixes on a 2.2 device:</p>
<div id="attachment_2378" class="wp-caption alignnone" style="width: 210px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/abs_suggestions_optimus_one.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/abs_suggestions_optimus_one-200x300.png" alt="Suggestions working in ActionBarSherlock when using the dev branch" width="200" height="300" class="size-medium wp-image-2378" /></a><p class="wp-caption-text">Suggestions working in ActionBarSherlock when using the dev branch</p></div>
<p>Be very careful, if you use this branch. After all the current development is taking place here. It&#8217;s not yet finalized for production!</p>
<h3>A custom ActionView</h3>
<p>As mentioned you can also create arbitrary action views. You have some options to do so:</p>
<ul>
<li>You can link to a layout file from within your <code>menu.xml</code></li>
<li>You can set the layout when the action item is clicked</lI>
<li>You can write a custom <a href="https://developer.android.com/reference/android/view/View.html" title="Documentation of Android's View class">View</a> implementation</li>
</ul>
<p>I do not cover the last one. That&#8217;s because it&#8217;s the least likely solution for you and also because I haven&#8217;t yet covered how to create custom views in Android in this blog.</p>
<p>So let me show you how to use the first two.</p>
<h3>Linking to a layout file</h3>
<p>In this case you create a layout file and point to it directly from within your menu xml file:</p>
<pre class="brush: xml; highlight: [3,6]; title: ; notranslate">
&lt;item 
   android:id=&quot;@+id/actionViewLayout&quot;
   android:showAsAction=&quot;ifRoom|collapseActionView&quot;
   android:icon=&quot;@drawable/ic_action_add&quot;
   android:title=&quot;Add&quot;
   android:actionLayout=&quot;@layout/activity_actionview_edittext&quot;
/&gt;
</pre>
<p>In line six you can see how the layout is referenced directly from within the menu item definition.</p>
<p>You still have the option to show it in expanded or in collapsed mode right from the outset. Line three in the xml snippet above uses a collapsed mode at first. The difference becomes obvious in the next screenshots. The first set shows the item in collapsed mode first. When you press the add item, Android expands the layout and moves all other action items into the overflow menu.</p>
<p><div id="attachment_2410" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/add_actionview_collapsed.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/add_actionview_collapsed-153x300.png" alt="The add Actionview in collapsed mode" width="153" height="300" class="size-medium wp-image-2410" /></a><p class="wp-caption-text">The add Actionview in collapsed mode</p></div><br />
<div id="attachment_2411" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/add_actionview_expanded_after_click.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/add_actionview_expanded_after_click-153x300.png" alt="Add ActionView in expanded mode" width="153" height="300" class="size-medium wp-image-2411" /></a><p class="wp-caption-text">Add ActionView in expanded mode</p></div></p>
<p class="clear">If you use the layout expanded all the time, it&#8217;s present all the time and takes up the place it needs. All other action items are visible &#8211; as long as some place is left for them. That&#8217;s what you see in the next screenshot. This option is the most space-constrained option you have. If your ActionView is always expanded, you probably have not much room left for any other action items. That&#8217;s the reason I use a landscape screenshot. So make sure you use the value <code>ifRoom</code> for the <code>android:showAsAction</code> attributes of all the other items &#8211; and to limit the action view to as little space as absolutely necessary.</p>
<div id="attachment_2402" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/add_actionview_expanded_right_away_final.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/add_actionview_expanded_right_away_final-300x153.png" alt="ActionView expanded right away" width="300" height="153" class="size-medium wp-image-2402" /></a><p class="wp-caption-text">ActionView expanded right away</p></div>
<p>To use the expanded view all the time you simply have to remove the <code>collapseActionView</code> value and the pipe symbol from line 3 of above&#8217;s xml snippet.</p>
<p>Of course it depends on the use case at hand and what your layout is, but I think this option generally is best used with an expanded layout all the time. Otherwise users might get confused by the disappearing action items when they expand the layout. And users might not know that they can use the back button to collapse the view again. If you plan to expand the layout on an action item click you&#8217;re probably better off with the option of the next paragraph.</p>
<h3>Setting the layout when the user clicks the item</h3>
<p>This option combines both methods of the former paragraph. Once again two screenshots demonstrate best what I am talking about:</p>
<p><div id="attachment_2415" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/refresh_actionview_collapsed.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/refresh_actionview_collapsed-153x300.png" alt="Refresh ActionView in collapsed mode" width="153" height="300" class="size-medium wp-image-2415" /></a><p class="wp-caption-text">Refresh ActionView in collapsed mode</p></div><br />
<div id="attachment_2416" class="wp-caption alignleft" style="width: 163px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/refresh_actionview_replaced_with_progressbar.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/02/refresh_actionview_replaced_with_progressbar-153x300.png" alt="Refresh icon replaced by ProgressBar spinner" width="153" height="300" class="size-medium wp-image-2416" /></a><p class="wp-caption-text">Refresh icon replaced by ProgressBar spinner</p></div></p>
<p class="clear">The first screenshot shows the refresh icon as a normal action item. The layout file looks like any other menu item:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;item
   android:id=&quot;@+id/progress&quot;
   android:icon=&quot;@drawable/ic_action_reload&quot;
   android:showAsAction=&quot;ifRoom&quot;
   android:title=&quot;@string/progress&quot;
/&gt;
</pre>
<p>But as soon as you click the refresh button, Android replaces it with the progress spinner. That&#8217;s because I set an action view in reaction to the action item click. The first code shows the <code>onOptionsItemSelected()</code> method in which I react to the item click:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   if (item.getItemId() == R.id.progress) {
      new DummyAsyncTask().execute((Void[])null);
      return true;
   }
   return super.onOptionsItemSelected(item);
}
</pre>
<p>The AsyncTask is a sample implementation showing you how to change the action view values:</p>
<pre class="brush: java; highlight: [13,18,19]; title: ; notranslate">
private class DummyAsyncTask extends 
      AsyncTask&lt;Void, Void, Void&gt; {

   @Override
   protected Void doInBackground(Void... params) {
      // simulate doing some time-consuming stuff:
      SystemClock.sleep(2000);
      return null;
   }
   @Override
   protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      ActionViewActivity.this.mProgress.setActionView(null);
   }   
   @Override
   protected void onPreExecute() {
      super.onPreExecute();
      ActionViewActivity.this.mProgress.
            setActionView(R.layout.activity_actionview_progress);
   }
}
</pre>
<p>As soon as the work is done and the new values have been downloaded, you simply set the action view to <code>null</code> again &#8211; in the code above I do this in the <code>onPostExecute()</code> method.</p>
<p>As you can see it uses an expanded mode &#8211; but only for the time, the user actually needs this view. Do not use the value <code>collapseActionView</code> in your menu item definition. Otherwise the layout expands on the left of the ActionBar and not in place of the icon!</p>
<h3>Lessons learned</h3>
<p>In this tutorial you have seen how to make use of ActionViews. Very useful is the <code>SearchView</code> &#8211; thus I detailed how to add this to your ActionBar and how to link it to your search configuration in this post.</p>
<p>You have also seen that in the current 4.2 release of ActionBarSherlock SearchSuggestions are not yet working correctly. But thanks to a fix those will be part of the next ABS release.</p>
<p>Finally you learned how to create an ActionView on your own, though use cases for this are limited. Probably the most common one is replacing an update icon with the progress spinner widget.</p>
<p>There is also some sample code waiting for you. Alas, it is not yet ready for publication. For the sake of publishing this post early, I took some shortcuts <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  </p>
<p>I am going to finalize the code this weekend so that you can expect an update early next week. This will also be a sample of my upcoming GrokkingAndroid demo app &#8211; so stay tuned.</p>
<p>Until then: Happy coding!<br />
<img src="http://vg03.met.vgwort.de/na/c8b0e8f79bfa405997e4d7bb0c9d2813" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/adding-actionviews-to-your-actionbar/">Adding ActionViews to Your ActionBar</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/YO_inxbpvYA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/adding-actionviews-to-your-actionbar/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/adding-actionviews-to-your-actionbar/</feedburner:origLink></item>
		<item>
		<title>Adding ActionBar Items From Within Your Fragments</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/OdH5Cp3jm6A/</link>
		<comments>http://www.grokkingandroid.com/adding-action-items-from-within-fragments/#comments</comments>
		<pubDate>Thu, 17 Jan 2013 11:25:20 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Action Bar]]></category>
		<category><![CDATA[Action Items]]></category>
		<category><![CDATA[Menu]]></category>
		<category><![CDATA[MenuItem]]></category>
		<category><![CDATA[onCreateOptionsMenu()]]></category>
		<category><![CDATA[onOptionsItemSelected()]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2315</guid>
		<description><![CDATA[<p>This tutorial shows you how to add action items to the ActionBar from within your Fragments and how to disable or enable action items depending on the state of your fragment. All code works with the stock Android ActionBar object as well as with ActionBarSherlock. Why do you want to add action items? In a [...]</p><p>The post <a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/">Adding ActionBar Items From Within Your Fragments</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">This tutorial shows you how to add action items to the ActionBar from within your Fragments and how to disable or enable action items depending on the state of your fragment. All code works with the stock Android <a href="https://developer.android.com/reference/android/app/ActionBar.html" title="Documentation of Android's ActionBar class">ActionBar</a> object as well as with ActionBarSherlock.</p>
<h3>Why do you want to add action items?</h3>
<p>In a previous post you have seen that <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/" title="Getting Started With Fragments and the Support Library">Android makes it easy to provide responsive interfaces</a>. And given the vast distribution of devices sizes that is something you should do.</p>
<p>This post continues with the app, you have developed in the first posts of this series. The user has a list of items, a detail screen and an edit screen.</p>
<p>On a phone the startscreen simply shows a list of items. Here you have an action item to add a new item to the list:</p>
<div id="attachment_2344" class="wp-caption alignnone" style="width: 210px"><a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/listactivity/" rel="attachment wp-att-2344"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/01/listactivity-200x300.png" alt="Screen showing the ListFragment only" width="200" height="300" class="size-medium wp-image-2344" /></a><p class="wp-caption-text">Screen showing the ListFragment only</p></div>
<p>The detail screen shows all the relevant details of this item and offers you to edit the item:</p>
<div id="attachment_2352" class="wp-caption alignnone" style="width: 210px"><a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/detail_screen-2/" rel="attachment wp-att-2352"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/01/detail_screen1-200x300.png" alt="Screen showing the DetailFragment only" width="200" height="300" class="size-medium wp-image-2352" /></a><p class="wp-caption-text">Screen showing the DetailFragment only</p></div>
<p>Now here&#8217;s what the tablet version looks like:</p>
<div id="attachment_2346" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/tablet_version_portrait_snip/" rel="attachment wp-att-2346"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/01/tablet_version_portrait_snip-300x219.png" alt="Top part of the tablet version containing both fragments" width="300" height="219" class="size-medium wp-image-2346" /></a><p class="wp-caption-text">Top part of the tablet version containing both fragments</p></div>
<p>As you can see, it now sports both icons since it also presents both fragments. Now this app is pretty dull so far, and the detail screen even more so, so let me show you a real app. I take <a href="https://play.google.com/store/apps/details?id=com.gabrielittner.timetable" title="Play store link of Timetable">Timetable</a>, an app that does this nicely.</p>
<div id="attachment_2348" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/timetable-2/" rel="attachment wp-att-2348"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/01/timetable1-300x187.png" alt="Timetable app showing action items of multiple fragments" width="300" height="187" class="size-medium wp-image-2348" /></a><p class="wp-caption-text">Timetable app showing action items of multiple fragments</p></div>
<p>In this screen the edit and trash icon are from the selected element and are only added when a lecture has been selected. The plus and the search icon though are from the <code>ListFragment</code>.</p>
<h3>Adding action items programatically</h3>
<p>As the post title implies the additional action items are inserted by the fragment. In fact not much different from how you add the items within your Activities. You use the <code>onCreateOptionsMenu()</code> method for it:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public void onCreateOptionsMenu(
      Menu menu, MenuInflater inflater) {
   inflater.inflate(R.menu.activity_itemdetail, menu);
}
</pre>
<p>As you can see the signature of this method is different from the one of the <code>Activity</code> class. With fragments your method takes a <code>MenuInflater</code> as second parameter. And the fragment&#8217;s <code>onCreateOptionsMenu()</code> method also doesn&#8217;t return a boolean value.</p>
<p>Even with this method in place Android still doesn&#8217;t display any additional menu items unless you explicitly tell it to call this method. To do so, you first have to call <code>setHasOptionsMenu()</code> within the fragment&#8217;s <code>onCreate()</code> method:</p>
<pre class="brush: java; title: ; notranslate">
setHasOptionsMenu(true);
</pre>
<p>Now your fragments menu items will be displayed in the ActionBar.</p>
<p>Of course, if you do so, you have to stop using the same entries in your Activity. Otherwise it would look fine on any screen that makes use of your multi-pane layouts but you would end up with doubled icons on single-pane screens. </p>
<p>For the sample screen I have used a menu xml file containing only the about entry in the activity. And I use an xml file containing only the edit entry in the fragment. The about entry is not needed in the fragment, because it is added by the activity, no matter whether you are in single-pane or double-pane mode.</p>
<h3>Changing the order of action items</h3>
<p>By default Android displays the action items of your fragment behind those of the activity. If you use multiple fragments Android displays them in the order the fragments are created.</p>
<p>This default order is not necessarily what you want. For example it is very likely that you want to display an about item as the very last entry within your overflow-menu &#8211; no matter if fragments later on add more overflow-menu entries. Also some actions are more often used than others. You want to put them more to the left, so that, depending on the screen size, those are always visible. And which items are more important depends on which fragments are in use.</p>
<p>Tio help you achieve this you can make use of the <code>android:orderInCategory</code> attribute of the <code>item</code> elements.</p>
<p>The <code>fragment_itemdetail.xml</code> menu file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;
   &lt;item
      android:id=&quot;@+id/edit_item&quot;
      android:icon=&quot;@drawable/ic_action_edit&quot;
      android:showAsAction=&quot;ifRoom&quot;
      android:orderInCategory=&quot;10&quot;
      android:title=&quot;@string/edit_item&quot;&gt;
   &lt;/item&gt;
&lt;/menu&gt;
</pre>
<p>The <code>activity_itemdetail.xml</code> menu file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;
   &lt;item
      android:id=&quot;@+id/about&quot;
      android:icon=&quot;@drawable/ic_action_info&quot;
      android:showAsAction=&quot;never&quot;
      android:orderInCategory=&quot;9999&quot;
      android:title=&quot;@string/about&quot;&gt;
   &lt;/item&gt;
&lt;/menu&gt;
</pre>
<p>And finally the <code>activity_itemlist.xml</code> menu xml file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;menu xmlns:android=
      &quot;http://schemas.android.com/apk/res/android&quot; &gt;
   &lt;item
      android:id=&quot;@+id/add_item&quot;
      android:icon=&quot;@drawable/ic_action_add&quot;
      android:orderInCategory=&quot;20&quot;
      android:showAsAction=&quot;ifRoom&quot;
      android:title=&quot;@string/add_item&quot;&gt;
   &lt;/item&gt;
   &lt;item
      android:id=&quot;@+id/about&quot;
      android:icon=&quot;@drawable/ic_action_info&quot;
      android:showAsAction=&quot;never&quot;
      android:orderInCategory=&quot;9999&quot;
      android:title=&quot;@string/about&quot;&gt;
   &lt;/item&gt;
&lt;/menu&gt;
</pre>
<p>The higher the number the later your action item is displayed. So use an absurdly high value for the about item. And order all other elements by importance. </p>
<p>Since all elements have an order value of zero by default, you have to use numbers for <em>all</em> action items as soon as you want to move one to the front.</p>
<pre class="brush: xml; title: ; notranslate">
android:orderInCategory=&quot;9999&quot;
</pre>
<h3>Handling events</h3>
<p>As usual you can handle menu item clicks in the <code>onOptionsItemSelected()</code> method:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   // handle item selection
   switch (item.getItemId()) {
      case R.id.edit_item:
         // do s.th.
         return true;
      default:
         return super.onOptionsItemSelected(item);
   }
}
</pre>
<p>But bear in mind that the Activity&#8217;s <code>onOptionsItemSelected()</code> method is called first. <strong>Your fragment&#8217;s method is called only, when the Activity didn&#8217;t consume the event!</strong></p>
<h3>Adding and removing action items</h3>
<p>So far I have only mentioned how to use action items, that are defined within an xml file. But that often is not sufficient. </p>
<p>See this screenshot of a German TV program app. Please ignore, that it&#8217;s in German, I explain what is relevant to you. </p>
<div id="attachment_2354" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/prime_guide/" rel="attachment wp-att-2354"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/01/prime_guide-300x187.png" alt="The Prime Guide app showing icons only when relevant" width="300" height="187" class="size-medium wp-image-2354" /></a><p class="wp-caption-text">The Prime Guide app showing icons only when relevant</p></div>
<p>In this app you can select a program to get more information about it. If you select a program that hasn&#8217;t started yet, you can bookmark it and set an alarm for it. If on the other hand the program either has already started or ended those actions are not displayed. It simply makes no sense to add an alarm for some program that has already started. But all other icons are visible in both cases.</p>
<p>So how to do that? You could either use different menu xml files for a static set of action items. Or you could add or remove menu actions programatically. Since the second approach is more flexible I deal with it in the next paragraphs.</p>
<p>First you need to get hold of a <a href="https://developer.android.com/reference/android/view/Menu.html" title="Documentation of Android's Menu class">Menu</a> object. You can do so in the <code>onCreateOptionsMenu()</code> method shown above.</p>
<p>Now you can use this <code>Menu</code> object to either change the visibility of action items or to remove them from the menu entirely.</p>
<p>You can change the visibility like this:</p>
<pre class="brush: java; title: ; notranslate">
if (mMenu != null) {
   mMenu.findItem(R.id.edit_item).setVisible(false);
}
</pre>
<p>The <code>null</code> check in the code is necessary, because of the order in which the methods of your fragment are called. Of course Android executes the lifecycle methods before finally calling <code>onCreateOptionsMenu()</code>. Thus your <code>Menu</code> object is <code>null</code> in the <code>onCreateView()</code> method, which you probably use to create event handlers.</p>
<p>If you want to entirely remove the action item, you can do so easily as well:</p>
<pre class="brush: java; title: ; notranslate">
if (mMenu != null) {
   mMenu.removeItem(R.id.edit_item);
}
</pre>
<p>As you will see in the next few paragraphs, adding a menu item is slightly more cumbersome than just making it visible again. Thus if you want to toggle action items depending on the state of your fragment, I suggest to change the visibility instead of removing and re-adding the items.</p>
<p>So far I have only shown you how to get rid of action items. Of course you also can add new items. You can use one of the several <code>add()</code> methods of the <code>Menu</code> class. For example the following code fragment would add the item in the same way, as with the xml code for inflating it:</p>
<pre class="brush: java; title: ; notranslate">
MenuItem item = 
      mMenu.add(Menu.NONE, R.id.edit_item, 10, R.string.edit_item);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setIcon(R.drawable.ic_action_edit);
</pre>
<p>The first parameter sets the group. If you have no groups, use <a href="https://developer.android.com/reference/android/view/Menu.html#NONE" title="Documentation of the final field Menu.NONE">Menu.NONE</a>. The second parameter sets the id you want to use. It&#8217;s the same one you later use in the <code>onOptionsItemSelected()</code> method to react to menu item clicks. The third parameter is the order value and the last one the title text you want to use. Remember, that <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/" title="Adding ActionBarSherlock to Your Project">Android uses the title text to display usage hints or to read out this value with a screenreader app</a>. So never use <code>null</code> for this value.</p>
<p>As the code sample shows, you have to add the icon and the <code>showAsAction</code> attribute value with separate method calls later on.</p>
<p>I don&#8217;t know why there is no way to add a complete <a href="https://developer.android.com/reference/android/view/MenuItem.html" title="Documentation of Android's MenuItem class">MenuItem</a> object directly. To me that would be better readable. But that&#8217;s just a tiny detail <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Wrapping up</h3>
<p>In this post I have shown that you can use the <code>onCreateOptionsMenu()</code> method to add action items related to your fragment to the existing icons of the ActionBar.</p>
<p>Since the default order in which Android adds these items is often not the preferred one, you can change this easily by adding the <code>android:orderInCategory</code> attribute to your menu items in the xml files.</p>
<p>Finally you have seen how to change the visibility of menu items, how to remove them completely or how to add new menu items.</p>
<p>Please let me know in the comments, if any questions are left open and which way you prefer to remove action items from the ActionBar. And don&#8217;t forget to plus one and share this post if you found it useful!<br />
<img src="http://vg03.met.vgwort.de/na/40ac8b7fc73948718a7bd842484c0fa5" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/adding-action-items-from-within-fragments/">Adding ActionBar Items From Within Your Fragments</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/OdH5Cp3jm6A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/adding-action-items-from-within-fragments/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/adding-action-items-from-within-fragments/</feedburner:origLink></item>
		<item>
		<title>ActionBarSherlock: Up Navigation</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/e66VXReK9Lo/</link>
		<comments>http://www.grokkingandroid.com/actionbarsherlock-up-navigation/#comments</comments>
		<pubDate>Thu, 10 Jan 2013 10:07:53 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[ActionBarSherlock]]></category>
		<category><![CDATA[NavUtils]]></category>
		<category><![CDATA[setDisplayHomeAsEnabled()]]></category>
		<category><![CDATA[setHomeButtonEnabled()]]></category>
		<category><![CDATA[Up Navigation]]></category>
		<category><![CDATA[Up vs. Back]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2256</guid>
		<description><![CDATA[<p>In this tutorial I am going to cover some initial thoughts on navigation. The ActionBar allows multiple navigation modes. In this post I state which navigation modes exist, how to get to the ActionBar object in the first place and how to deal with the so-called up navigation. Less code than in the previous parts [...]</p><p>The post <a href="http://www.grokkingandroid.com/actionbarsherlock-up-navigation/">ActionBarSherlock: Up Navigation</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">In this tutorial I am going to cover some initial thoughts on navigation. The ActionBar allows multiple navigation modes. In this post I state which navigation modes exist, how to get to the ActionBar object in the first place and how to deal with the so-called up navigation.</p>
<p>Less code than in the previous parts because code-wise there is not much to it. But the concept is the cause for user confusion mostly caused by inconsistent implementations. I hope this post helps to get you on track to implement the up navigation in a correct way so that users understand your app easily.</p>
<p>Back and up navigation is a topic that&#8217;s always causing lot&#8217;s of discussions. When in doubt, please go to the <a href="https://plus.google.com/communities/105153134372062985968" title="The official Android developers community">developers community on Google+</a> or the <a href="http://ux.stackexchange.com/" title="User Experience Q&amp;A community">user experience equivalent of StackOverflow</a> and discuss the way you want to use it and if this is correct or not. If you have technical issues, though, please use <a href="http://stackoverflow.com/" title="StackOverflow - a Q&amp;A community for code related questions">StackOverflow</a>.</p>
<h3>The structure of the ActionBar</h3>
<p>Let me go back for a second and explain the way the ActionBar is partitioned. I follow the terminology of the <a href="http://developer.android.com/design/patterns/actionbar.html" title="The ActionBar pattern as described on Android's design site">ActionBar pattern page</a> in Android&#8217;s design guidelines here.</p>
<div id="attachment_2311" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/actionbarsherlock-up-navigation/detail_actionbar_android_2-2/" rel="attachment wp-att-2311"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2013/01/detail_actionbar_android_2.2-300x45.png" alt="ActionBar of the detail screen on a 2.2 device" width="300" height="45" class="size-medium wp-image-2311" /></a><p class="wp-caption-text">ActionBar of the detail screen on a 2.2 device</p></div>
<p>On the left side of the ActionBar is the app icon and possibly some indicator for the up navigation or the slide-out menu. Next comes the View control. This is often a text showing where you are. It could also contain tabs or a spinner as alternative means for navigating your app. Those elements are aligned to the left.</p>
<p>On the right side we have the action buttons followed by the action overflow &#8211; if an overflow menu is present.</p>
<p>What is important is to distinguish both areas. The left area is the part where you put navigational elements. Like moving up, tabs or a spinner. The right part is where you put actions that belong to the view. Like actions to add or delete elements, to update a list or for adding songs to your favorite lists. </p>
<p>I do not discuss those action items in this post. I have already described <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/" title="Adding ActionBarSherlock to Your Project">how to add action items and how to use the overflow menu</a>. I probably cover the split ActionBar in another post and I will also deal with Action Providers and Action Views in a later post.</p>
<h3>Navigation types of the ActionBar</h3>
<p>Basically there are four types of navigation supported by the ActionBar pattern:</p>
<ul>
<li>Go to the start screen of the app</li>
<li>Go up in the navigational hierarchy</li>
<li>Switch to another tab</li>
<li>Select another Spinner item</li>
</ul>
<h3>Accessing the ActionBar object</h3>
<p>Before you can use any of the navigational modes, you need access to the ActionBar object, though. Since there is no public Javadoc page for the ActionBarSherlock library, I recommend to use the <a href="http://developer.android.com/reference/android/app/ActionBar.html" title="Android's documentation of the ActionBar class">documentation of Android&#8217;s own ActionBar class</a>, if you need to know about methods or fields of the ActionBar class. ActionBarSherlock&#8217;s class offers the exact same methods. Of course the signature is different since it uses ActionBarSherlock counterparts for any parameters or return values that use object of the ActionBar API &#8211; but should you migrate to ABS from a project that already makes use of the stock ActionBar, just changing the imports should suffice.</p>
<p>Using ActionBarSherlock you get the ActionBar object by calling <code>getSupportActionBar()</code> from within your <code>SherlockActivity</code>:</p>
<pre class="brush: java; title: ; notranslate">
ActionBar actionBar = getSupportActionBar();
</pre>
<p>If your API target is at least API level 14 you could be tempted to use <code>getActionBar()</code> instead. After all this method appears first among the code-completion suggestions. But that won&#8217;t work on older devices &#8211; which is the reason to use ActionBarSherlock in the first place. So do the right thing and always call <code>getSupportActionBar()</code>!</p>
<p>Gladly <a href="http://tools.android.com/recent/lintonsave" title="Lint on save feature of the Android Development Tools project">Lint</a> reminds you to do so:</p>
<pre class="brush: plain; title: ; notranslate">
Class requires API level 11 (current min is 7): android.app.ActionBar
</pre>
<p>But Lint cannot do so, when you added the Annotation <code>SuppressLint("NewApi")</code> to your code &#8211; so better be careful right from the beginning.</p>
<p>The method <code>getSupportActionBar()</code> is not available for fragments. But you can get access to the activity by calling <code>getSherlockActivity()</code>. And from here you can go on as shown above.</p>
<p>Be very careful here as well. If you call <code>getActivity()</code> instead, you will get an object of type <code>android.support.v4.app.FragmentActivity</code>. Since this class doesn&#8217;t have the <code>getSupportActionBar()</code> method you are even more prone to call the wrong method.</p>
<h4>How does ActionBarSherlock&#8217;s ActionBar relate to Android&#8217;s ActionBar</h4>
<p>ActionBarSherlock creates a wrapper to a native ActionBar object on all devices with an API level of at least 14 (ICS). And it creates a compatibility object for older devices. Both inherit from <code>com.actionbarsherlock.app.ActionBar</code>.</p>
<p>This is important to know. Because if you develop using an emulator or a device with a newer API level, you get away with being sloppy. Well, until you start to actually use an older device. When you start your app on an older device, your app will force close because of a <code>NoSuchMethodError</code>. Not too surprising, since the method <code>getActionBar()</code> was not available for Activities back then.</p>
<h3>Navigating to the start screen</h3>
<p>The ActionBar pattern has emerged before an official implementation existed. That&#8217;s the common way patterns emerge. The very first post on Juhani Lehtimäki&#8217;s excellent blog androiduipatterns.com shows some <a href="http://www.androiduipatterns.com/2010/11/action-bar.html" title="Screenshots of apps that made use of the ActionBar before Honeycomb">examples of apps that implemented the ActionBar in 2010</a>. With the introduction of Honeycomb the Android team added the ActionBar to the API in 2011.</p>
<p>Back then it was all the rage to use the app icon as something akin to the home button or the logo on websites. It would get you immediately to the initial screen of the app. Of course back then it looked as if the dashboard would gain traction and so a click on the app icon would immediately bring you back to this hub. This all has changed, but you still could use the app icon that way.</p>
<p>But <strong>I advise not to use the home navigation model. Instead make use of the up navigation</strong>. Using the up model <a href="http://developer.android.com/design/patterns/navigation.html" title="Android Design Site about Navigation">is the recommended pattern of Android&#8217;s design guidelines</a>. I explain the up navigation in the next section. The code for home navigation would be nearly identical (it&#8217;s just another target Activity) &#8211; but you prefer to follow the guidelines anyway, don&#8217;t you?</p>
<h3>Up navigation</h3>
<p>With Ice Cream Sandwich the Android team has introduced the so-called <a href="http://developer.android.com/design/patterns/actionbar.html" title="ActionBar pattern page of Android's design site.">up affordance</a> to the platform. <a href="http://www.jnd.org/dn.mss/affordances_and.html" title="Don Norman's clarification of what affordance means in the context of visual design">Perceived</a> <a href="http://www.interaction-design.org/encyclopedia/affordances.html" title="What means affordance - by the Interaction Design Foundation">affordance</a> is a visual clue helping users understand what a certain element does. In this case the up affordance helps the user to understand that he is going up (or back) a hierarchical level.</p>
<p>To be honest: I am still not convinced that this button is a useful addition to the Android platform, but that&#8217;s just me. In fact it&#8217;s a common pattern found in many current apps, it&#8217;s pushed by Google and it&#8217;s recommended on the design site. It looks like this pattern has established itself firmly. Thus, <strong>I recommend to use it</strong>, despite my misgivings!</p>
<h4>So what is up navigation?</h4>
<p>Up means getting up a hierarchy level. If you go up a level you usually also go back a level, thus the affordance, this tiny little left pointing caret, is not as weirdly chosen as it might sound.</p>
<p>Let me give you an example: Say you have a list of items and select one item. The detail screen would be the next hierarchical level. Up in this case would go back to the list of items. That&#8217;s what the app used in this series does so far. But apps often have multiple levels in their hierarchy. And using the up button can help users navigate the app faster &#8211; an important consideration in the mobile environment.</p>
<p>Before discussing this any further, let me first show you how to do this.</p>
<h4>Adding the up affordance</h4>
<p>Navigating within hierarchies means that the up affordance should be visible as soon as you navigate down one level. Which basically means that all screens after the initial screen of the app should sport the up affordance.</p>
<p>If you followed this series so far, you added the following lines to the <code>ItemDetailActivity</code> in the first part about <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/" title="Getting Started With Fragments and the Support Library">using fragments and the support library</a>:</p>
<pre class="brush: java; title: ; notranslate">
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB) {
   getActionBar().setDisplayHomeAsUpEnabled(true);
}
</pre>
<p>You had to add the <code>if</code> statement as a temporary workaround to make your project compile before you have added ActionBarSherlock to it. Remember that <code>getActionBar()</code> only works on newer devices. </p>
<p>Now that <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/" title="Adding ActionBarSherlock to Your Project">you have added ActionBarSherlock in the last post</a> of this series, you can use <code>getSupportActionBar()</code> instead. And since this works on older devices as well, you can drop the <code>if</code> statement instead:</p>
<pre class="brush: java; title: ; notranslate">
// Show the Up button in the action bar:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</pre>
<h4>Reacting to an up click</h4>
<p>When a user clicks on the home button of your app (not the home button of your device), you should navigate to the Activity that is logically one hierarchy above the current one. You do so within the <code>onOptionsItemSelected()</code> method of your <code>ItemDetailActivity</code>. In fact the Android developer tools did that already when you created the project:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
      case android.R.id.home:
         // This ID represents the Home or Up button. In the case of this
         // activity, the Up button is shown. Use NavUtils to allow users
         // to navigate up one level in the application structure. For
         // more details, see the Navigation pattern on Android Design:
         //
         // http://developer.android.com/design/patterns/navigation.html#up-vs-back
         //
         NavUtils.navigateUpTo(this,
               new Intent(this, ItemListActivity.class));
         return true;
   }
   return super.onOptionsItemSelected(item);
}
</pre>
<p><a href="https://developer.android.com/reference/android/support/v4/app/NavUtils.html#navigateUpTo(android.app.Activity, android.content.Intent)" title="Documentation of NavUtil's navigateUpTo() method">NavUtils&#8217; navigateUpTo() method</a> takes care of setting the flag <a href="https://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP" title="Documentation of the Flag FLAG_ACTIVITY_CLEAR_TOP">FLAG_ACTIVITY_CLEAR_TOP</a> and finishing the current activity. This flag ensures that a previous instance of this Activity within your task stack is reused, if available, and removes any activities on top of that activity.</p>
<h4>Disabling the home button on the initial screen</h4>
<p>Now when you already are at the root level of your app, there is no more up navigation possible. Thus you should disable the home button and the up affordance.</p>
<p>Doing so is simple. Just call <code>setHomeButtonEnabled()</code> and pass in a <code>false</code> value. For the project you have created in this series the home Activity is your <code>ItemListActivity</code>. Thus add this line to the <code>onCreate()</code> method somewhere after your call to the <code>super</code> method.:</p>
<pre class="brush: java; title: ; notranslate">
// disable the home button and the up affordance:
getSupportActionBar().setHomeButtonEnabled(false);
</pre>
<h3>So how is up different to the back button?</h3>
<p>From what I have said so far, you might think that up is nothing else than the usual back button. But that&#8217;s not the case!</p>
<p>Both buttons can go back to the same screen, that&#8217;s true, but that&#8217;s not always the case.</p>
<p>Granted, for the app, you have developed so far in this mini-series, there is no difference between up and back. But most often you can get to a certain screen in your app in multiple ways. And that&#8217;s when back and up start to behave differently. </p>
<p>Up takes you always to a defined point of the app: The previous point in the hierarchy &#8211; no matter how you got to this point. Back though follows the trail you have chosen in reverse.</p>
<p>This is even more important if your app offers exported Activities for use by other applications. In this case the user might get to a screen of your app from an external app. </p>
<p>Up would still bring him up a hierarchical level within your app. Back on the other hand should bring the user back to where he came from &#8211; in this case the other app. </p>
<p>Even within your own app there can be differences. Say you are creating a conference app. From the schedule view the user selects one talk. The detail screen of the talk also links to other talks which are related as well as to talks that are by the same speaker. The user now might follow those links and thus view multiple talks. Now to return to the schedule fast, the user simply clicks the up icon and goes back to the schedule. With the back button though she would have to use multiple clicks &#8211; depending on the number of talks she has viewed.</p>
<h3>Be wary of bad examples!</h3>
<p>Don&#8217;t have a look at how other apps do it. Have a look at the design guide instead. There are way too many apps that do not behave correctly. There might be good reasons for doing so, but usually it adds to user confusion. It hurts the Android platform in general. Something you do not want to do, do you?</p>
<p>For example Google Play behaves incorrectly. You can go to the games category directly from the start screen. Or you can get there by going to apps and then selecting the games category. But up behaves differently, depending on where you came from. I can understand the reasoning behind it. They want to avoid confusion. But one level deeper the up button suddenly starts to work as up and not as back aynmore. What should users make of this?</p>
<p>As good-intentioned as this might be, I think it actually adds to the confusion. How should users grok the up button when it sometimes behaves incorrectly and works differently depending on where you are in the app? So, please, if you want to deviate from the guidelines, think twice. Think thrice. Discuss it with peers. Discuss it with usability experts. Do some users tests! Do your users and us all this favor!</p>
<h3>What about the slide-out menu?</h3>
<p>When discussing how to add the up affordance I said that you shouldn&#8217;t show an up affordance and that the home button shouldn&#8217;t be enabled when the user is on the initial screen of your app.</p>
<p>Obviously that&#8217;s not the case for the YouTube app, not for the Google+ app and an increasing number of other apps. YouTube as well as Google+ show the up affordance on the home screen and when you press the app icon again, the so-called slide-out menu appears. This is a relatively new pattern that has replaced the dashboard. </p>
<p>The slide-out menu has its name because it appears in a slide-out motion from the left side of the screen. It can be accessed using the up button &#8211; and sometimes by using a bezel-swipe from the left.</p>
<p>Keep in mind that this pattern is highly controversial. <a href="https://plus.google.com/108284392618554783657/" title="Google+ profile of Jake Wharton">Jake Wharton</a>, the creator of ActionBarSherlock, for example is a strong opponent of it. I personally like it, though I agree that it has some shortcomings. But with this in mind, carefully think whether your app needs one or not. Do not just add one, because it seems to be en-vogue right now. <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I won&#8217;t deal with this pattern here. There is a short paragraph on the ActionBar pattern page in the design guide. And you can find a <a href="http://www.androiduipatterns.com/2012/06/emerging-ui-pattern-side-navigation.html" title="The slide-out menu presented on androiduipatterns.com">detailed presentation of the slide-out navigation pattern</a> on Juhani&#8217;s androiduipatterns.com site.</p>
<p>What you need to know is, that the trigger for this menu with regards to the ActionBar is also the up button. You react to it as described above. Of course you do not simply start a new Activity but have to show the menu instead. One library to help you do so is <a href="https://plus.google.com/102743663990441974480/posts" title="Google+ profile of Jeremy Feinstein">Jeremy Feinstein&#8217;s</a> <a href="https://github.com/jfeinstein10/SlidingMenu" title="SlidingMenu library to realize slide-out menus">SlidingMenu library</a>. Of course, there are others as well, but I happen to like this one. </p>
<h3>Lessons learned</h3>
<p>In this post you learned about the up navigation and how to implement it. You added the up affordance to one activity and disabled the home button on the other one.</p>
<p>You also learned what the difference between up and back is and how well-intentioned deviations from the standard can cause user confusion.</p>
<p>I didn&#8217;t cover how to properly deal with Widget or Notification clicks to your app. I am totally opposed to the recommended behavior and probably would rant too much. Well actually this might be a topic for another post so as to vent off a bit and explain why I don&#8217;t like it <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  &nbsp; But not in this series.</p>
<p>I also left out how to create a new task and a simulated back stack when using the up button after a user got to your app from another app. I might do so in some other post if the need arises. But currently I think <a href="http://developer.android.com/training/implementing-navigation/ancestral.html" title="Android's training class about ancestral navigation">it&#8217;s explained sufficiently in the Android training class about ancestral navigation</a>. The current app is too simple to explain this properly.</p>
<p>Has this post helped you? Do you have any more questions about up vs. back? Let me know about questions left open, any remarks you want to make or any mistakes you have spotted in the comment section.<br />
<img src="http://vg03.met.vgwort.de/na/e724a22986c74bc28f90c2b8eb5a823c" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/actionbarsherlock-up-navigation/">ActionBarSherlock: Up Navigation</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/e66VXReK9Lo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/actionbarsherlock-up-navigation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/actionbarsherlock-up-navigation/</feedburner:origLink></item>
		<item>
		<title>Adding ActionBarSherlock to Your Project</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/aq-ZPAfFH84/</link>
		<comments>http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/#comments</comments>
		<pubDate>Fri, 14 Dec 2012 09:24:00 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Action Bar]]></category>
		<category><![CDATA[ActionBarSherlock]]></category>
		<category><![CDATA[getSherlockActivity()]]></category>
		<category><![CDATA[getSupportActionBar()]]></category>
		<category><![CDATA[Overflow Menu]]></category>
		<category><![CDATA[SherlockFragment]]></category>
		<category><![CDATA[SherlockFragmentActivity]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2135</guid>
		<description><![CDATA[<p>In my last post I had a look at how to set up a Fragment project that uses a master detail view. This week I am going to show you the necessary steps to make this project use the ActionBarSherlock library. ActionBarSherlock is a library by Jake Wharton, that enables you to use action bars [...]</p><p>The post <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/">Adding ActionBarSherlock to Your Project</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">In my last post I had a look at <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/" title="Getting Started With Fragments and the Support Library">how to set up a Fragment project that uses a master detail view</a>. This week I am going to show you the necessary steps to make this project use the ActionBarSherlock library.</p>
<p><a href="http://actionbarsherlock.com/" title="Homepage of the ActionBarSherlock project">ActionBarSherlock</a> is a library by <a href="https://plus.google.com/108284392618554783657/posts" title="Google Plus profile page of Jake Wharton">Jake Wharton</a>, that enables you to use action bars even on older devices without having to code an action bar from scratch. This library deals with all the details you do not want to care about. Even Googlers like <a href="https://plus.google.com/113735310430199015092/posts/TCaGvy8dFue" title="Roman Nurik recommends to use ABS and to ditch ActionBarCompat">Roman Nurik</a> or <a href="https://developers.google.com/events/io/sessions/gooio2012/1400/" title="Nick Butcher code lab on Google IO makes use of ABS">Nick Butcher</a> recommend to use this library and the <a href="http://code.google.com/p/iosched/" title="The project page of the Google IO App">Google IO app</a> also makes use of this lib. So should you!</p>
<p>With this post I start my series about the action bar by simply adding an action bar to the project of my last post, adding some action items to it and explaining some basics of action bars. The focus of this post is mainly on getting ActionBarSherlock to run on your project. As such it is an introductory post about the action bar. </p>
<p>Since the action bar offers many functions and is the most important navigational component Android has, more posts about it will follow in the next weeks.</p>
<h3>Getting ActionBarSherlock and adding it to Eclipse</h3>
<p>The first thing you have to do, is to <a href="http://actionbarsherlock.com/" title="Homepage of the ActionBarSherlock project">download the library from actionbarsherlock.com</a>. After this unzip/untar it. The download contains three folders: <code>library</code>, <code>samples</code> and <code>website</code>. The <code>samples</code> folder contains four sample projects to showcase what you can do and to show you how to do it. You should have a look at them. The <code>website</code> folder contains the code of the project website. The <code>library</code> folder finally contains ActionBarSherlock&#8217;s source code.</p>
<p>Now go to Eclipse and add the ABS-library as an Android project. <strong>Do not use Eclipse&#8217;s import tool</strong> to import the ActionBarSherlock library &#8211; it would not work immediately and you would have to fix some settings. <strong>Instead use the project creation wizard</strong> of the Android Developer Tools.</p>
<p>Open File -&gt; New -&gt; Project -&gt; Android Project From Existing Code. </p>
<div id="attachment_2141" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/import_abs_project.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/import_abs_project-300x244.png" alt="Creating an Adnroid project from existing source" width="300" height="244" class="size-medium wp-image-2141" /></a><p class="wp-caption-text">Creating an Android project from existing source</p></div>
<p>In the next screen select the folder, which Eclipse then uses to search for projects. If you select the ActionBarSherlock root folder, Eclipse suggests a list of projects to create. Leave the &#8220;library&#8221; project checked and uncheck all others:</p>
<div id="attachment_2149" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/selecting_library_project.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/selecting_library_project-300x267.png" alt="Select the library project" width="300" height="267" class="size-medium wp-image-2149" /></a><p class="wp-caption-text">Select the library project</p></div>
<p>Click &#8220;Finish&#8221; to create the project.</p>
<p>Eclipse will now create a new project named &#8220;library&#8221;. I prefer a more useful name, so select the project called &#8220;library&#8221; and hit F2 to rename the project. I have renamed the project in Eclipse to &#8220;ActionBarSherlock&#8221;, so all following screens will refer to this name.</p>
<h3>Adding the library to your project</h3>
<p>Now that ABS is a library project you have to tell your own project to use it. I will use <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/" title="Getting Started With Fragments and the Support Library">the project of my last post</a> for this. Go to FragmentStarter&#8217;s project settings and switch to the Android tab.</p>
<p>If necessary scroll down until you see the Library panel. Click &#8220;Add&#8221;:</p>
<div id="attachment_2151" class="wp-caption alignnone" style="width: 255px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/adding_library_to_project.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/adding_library_to_project-245x300.png" alt="Adding libraries to an Android project" width="245" height="300" class="size-medium wp-image-2151" /></a><p class="wp-caption-text">Adding libraries to an Android project</p></div>
<p>In the next window all available library projects will be listed. Select ActionBarSherlock and click &#8220;Ok&#8221;. </p>
<div id="attachment_2153" class="wp-caption alignnone" style="width: 284px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/selecting_library.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/selecting_library-274x300.png" alt="Select ActionBarSherlock from the list of libraries" width="274" height="300" class="size-medium wp-image-2153" /></a><p class="wp-caption-text">Select ActionBarSherlock from the list of libraries</p></div>
<p>When the window disappears the library should be listed in the library panel of the Android properties tab:</p>
<div id="attachment_2152" class="wp-caption alignnone" style="width: 257px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/check_if_all_is_good.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/check_if_all_is_good-247x300.png" alt="Check if the library has been added succesfully" width="247" height="300" class="size-medium wp-image-2152" /></a><p class="wp-caption-text">Check if the library has been added succesfully</p></div>
<p>What is slightly annoying is that the Android Developer Tools do not use the name of a project to reference it, but instead point to the directory itself. And what&#8217;s even more annoying is that a symlink gets translated to its real path, which is bound to change more often than a symlink. </p>
<p>Should you ever want to change the directory, you have to delete the reference to the library with the old path and link to the newly imported library. But unless you do a fresh install for blog posts, this probably won&#8217;t happen too often <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>That&#8217;s it. Your project bundles the lib from now on. </p>
<p>But wait a moment! If you have a look at your project, you will notice that it now sports a red warning icon. Go to the error tab and you will see lots of warnings. Eclipse states for <code>Fragment</code>, <code>FragmentActivity</code> and all the other classes of the support library, that they &#8220;cannot be resolved to a type&#8221;. Whoops!</p>
<div id="attachment_2160" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/unknown_classes.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/unknown_classes-300x130.png" alt="Unknow type problems after adding ActionBarSherlock" width="300" height="130" class="size-medium wp-image-2160" /></a><p class="wp-caption-text">Unknow type problems after adding ActionBarSherlock</p></div>
<p>The reason is, that ActionBarSherlock comes bundled with the library as well. And most of the time the <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/" title="Getting Started With Fragments and the Support Library">support library added when following my  post about fragments</a> is different from the one bundled with ActionBarSherlock. In the console tab of Eclipse you see the message &#8220;Jar mismatch! Fix your dependencies&#8221; with the hashcodes of the mismatching files and where these files are stored:</p>
<pre class="brush: plain; highlight: [1,7,10,11]; title: ; notranslate">
[FragmentStarterProject] Found 2 versions of android-support-v4.jar in the dependency list,
[FragmentStarterProject] but not all the versions are identical (check is based on SHA-1 only at this time).
[FragmentStarterProject] All versions of the libraries must be the same at this time.
[FragmentStarterProject] Versions found are:
[FragmentStarterProject] Path: /opt/workspace/FragmentStarterProject/libs/android-support-v4.jar
[FragmentStarterProject] 	Length: 385685
[FragmentStarterProject] 	SHA-1: 48c94ae70fa65718b382098237806a5909bb096e
[FragmentStarterProject] Path: /opt/libs/ActionBarSherlock/library/libs/android-support-v4.jar
[FragmentStarterProject] 	Length: 349252
[FragmentStarterProject] 	SHA-1: 612846c9857077a039b533718f72db3bc041d389
[FragmentStarterProject] Jar mismatch! Fix your dependencies
</pre>
<p>To fix this, simply delete the support library from you project. Go to the libs folder, select the <code>android-support-v4.jar</code> file and delete it. You can still use the support library because it&#8217;s also part of the ABS project.</p>
<p>If you need a newer version of the support library than the one bundled with ActionBarSherlock, remove the support library from both projects and add it anew to the ActionBarSherlock project.</p>
<p>With this done your project is good again. The next step, of course, is to change some code.</p>
<h3>Changing the types to their ActionBarSherlock counterparts</h3>
<p>Just adding the library won&#8217;t magically add an action bar to your project. Instead you have to change some of your code.</p>
<p>The first thing you have to do, is to change the classes from which you inherit. Instead of <code>Activity</code> use <code>SherlockActivity</code>, instead of <code>FragmentActivity</code> use <code>SherlockFragmentActivity</code>, instead of <code>Fragment</code> use <code>SherlockFragment</code> and so on. Now do this for the two activities and the two fragments you created while reading the last post.</p>
<p>You will notice that the <code>ItemDetailActivity</code> won&#8217;t compile any more. Whenever you add ActionBarSherlock to an existing project, this is bound to happen. Why is that?</p>
<p>Have a look at the error message Eclipse is displaying: &#8220;<code>Cannot override the final method from SherlockFragmentActivity</code>&#8220;. The method is the following:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   // ...
}
</pre>
<p>ActionBarSherlock overrides every method of it&#8217;s superclasses that takes either a <code>Menu</code>, <code>MenuItem</code> or <code>MenuInflater</code> object of the <code>android.view</code> package as parameter and declares those methods as final. You need to know that all the items in an action bar are actually menu items. Thus only by doing it this way ActionBarSherlock can take control of all the menu-handling and change it for older Android versions.</p>
<p>While the error message might sound bad, it actually isn&#8217;t. ActionBarSherlock provides<br />
for every final method another method with the same name and the same number of arguments. Even the class names of the arguments are the same. Only the packages differ.</p>
<p>This way ActionBarSherlock makes migration of existing projects very easy. You can keep your methods and do not have to change and adjust any logic. Simply delete all <code>import</code> statements to the menu-related classes of the package <code>android.view</code>. After this hit Ctrl-O to optimize and correct the import statements and when Eclipse displays the list of imports to choose from, choose those of the ActionBarSherlock library:</p>
<div id="attachment_2168" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/organize_imports.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/organize_imports-300x145.png" alt="Choose ActionBarSherlock&#039;s classes for imports" width="300" height="145" class="size-medium wp-image-2168" /></a><p class="wp-caption-text">Choose ActionBarSherlock&#8217;s classes for imports</p></div>
<p>If you do this for <code>ItemDetailActivity</code> the warnings disappear. Whenever you use Eclipse (or any other IDE for that matter) to generate the import statements for you, take care to select the types of the ActionBarSherlock library. Those all start with <code>com.actionbarsherlock</code>.</p>
<p>Now that your code looks fine, you should try to run the project. Whether this run is successful or not depends on the Android version of your device. If you run this code on a device with at least Android 4.0 everything runs fine. But not so on older devices. Here you will get a Force Close dialog due to an <code>IllegalStateException</code>:</p>
<pre class="brush: plain; title: ; notranslate">
java.lang.IllegalStateException: 
      You must use Theme.Sherlock, 
      Theme.Sherlock.Light, 
      Theme.Sherlock.Light.DarkActionBar, 
      or a derivative.
</pre>
<p>Gladly the exception is pretty specific: You have to use one of the Sherlock themes to get your project to run. ActionBarSherlock needs many definitions to get the action bar styled correctly. Thus it needs these styles and you have to use the ABS themes. You <em>can</em> use your own theme, of course, but you must use one of Sherlock&#8217;s themes as a base for yours. See the <a href="http://actionbarsherlock.com/theming.html" title="Guide on theming ActionBarSherlock">Sherlock theming guide</a> for more information on this.</p>
<p>Since adding the action bar to older devices is the reason to use ActionBarSherlock in the first place, you have to change the theme. Change your <code>AndroidManifest.xml</code> file to use a Sherlock theme:</p>
<pre class="brush: xml; highlight: [5]; title: ; notranslate">
&lt;application
   android:allowBackup=&quot;true&quot;
   android:icon=&quot;@drawable/ic_launcher&quot;
   android:label=&quot;@string/app_name&quot;
   android:theme=&quot;@style/Theme.Sherlock.Light&quot; &gt;
   &lt;!-- ... --&gt;
&lt;/application&gt;
</pre>
<p>Now finally the app runs fine. And yes, there is an ActionBar. As you can see it works fine on current as well as on older devices:</p>
<p><div id="attachment_2229" class="wp-caption alignleft" style="width: 235px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbarsherlock_on_2-1/" rel="attachment wp-att-2229"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbarsherlock_on_2.1-225x300.png" alt="Initial action bar on a 2.1 device" width="225" height="300" class="size-medium wp-image-2229" /></a><p class="wp-caption-text">Initial action bar on a 2.1 device</p></div><br />
<div id="attachment_2230" class="wp-caption alignleft" style="width: 210px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbarsherlock_on_4-2-1-3/" rel="attachment wp-att-2230"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbarsherlock_on_4.2.12-200x300.png" alt="Initial action bar on a 4.2 device" width="200" height="300" class="size-medium wp-image-2230" /></a><p class="wp-caption-text">Initial action bar on a 4.2 device</p></div></p>
<h3 class="clear">Adding items to the ActionBar</h3>
<p>The action bar is basically what the old menu was before Honeycomb. This means that you have to create a menu to see an action bar.</p>
<p>Create a file with the name <code>activity_itemlist.xml</code> in the folder <code>/res/menu</code> and add the following code to it. This file describes the structure of your action bar:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;menu xmlns:android=
      &quot;http://schemas.android.com/apk/res/android&quot; &gt;

    &lt;item
        android:id=&quot;@+id/add_item&quot;
        android:icon=&quot;@drawable/ic_action_add&quot;
        android:showAsAction=&quot;ifRoom&quot;
        android:title=&quot;@string/add_item&quot;
        android:titleCondensed=&quot;@string/add_item&quot;&gt;
    &lt;/item&gt;
    &lt;item
        android:id=&quot;@+id/about&quot;
        android:icon=&quot;@drawable/ic_action_info&quot;
        android:showAsAction=&quot;never&quot;
        android:title=&quot;@string/about&quot;
        android:titleCondensed=&quot;@string/about&quot;&gt;
    &lt;/item&gt;

&lt;/menu&gt;
</pre>
<p><strong>Note</strong>: I use icons from the icon pack <a href="http://www.androidicons.com/" title="Android icon packs of opoloo">&#8220;Android Developer Icons 2&#8243; of opoloo</a>. The values I use for the <code>android:icon</code> attributes are specific to this icon pack. As soon as you want to try this code, you have to prepare icons that match this code or change the attribute value to fit your icons. See the <a href="#appendix" title="Appendix for getting appropriate icons">appendix</a> for more on this.</p>
<p>Only the xml file won&#8217;t suffice. You also need to override the <code>onCreateOptionsMenu()</code> method to inflate this file:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getSupportMenuInflater();
   inflater.inflate(R.menu.activity_itemlist, menu);
   return true;
}
</pre>
<p>This is the result when you run the project again. Note the differences between the 2.1 device and the 4.2 device:</p>
<p><div id="attachment_2215" class="wp-caption alignleft" style="width: 235px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbar_with_icons_on_2-1/" rel="attachment wp-att-2215"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbar_with_icons_on_2.1-225x300.png" alt="Action bar with icons running on a 2.1 device" width="225" height="300" class="size-medium wp-image-2215" /></a><p class="wp-caption-text">Action bar with icons running on a 2.1 device after pressing the menu button</p></div><br />
<div id="attachment_2231" class="wp-caption alignleft" style="width: 210px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbar_with_icons_on_4-2/" rel="attachment wp-att-2231"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbar_with_icons_on_4.2-200x300.png" alt="Action bar with icons running on a 4.2 device" width="200" height="300" class="size-medium wp-image-2231" /></a><p class="wp-caption-text">Action bar with icons running on a 4.2 device</p></div></p>
<h3 class="clear">The overflow menu</h3>
<p>When you compare the screenshots of the previous section, you quickly understand what the so-called overflow menu is. This is the menu hidden behind the three dots are the far end of the action bar on modern devices. </p>
<p>Android shows as many items as it can directly on the action bar. But especially on phones the place for action items is quite limited. Thus Android shows all those items, that do not fit on the action bar directly, in the overflow menu. You can also tell Android to put items in the overflow menu regardless of the space. You can do so by using the value <code>never</code> for the attribute <code>android:showAsAction</code> of these items. More on this attribute later on.</p>
<p>The items of the overflow menu are only visible if you click the three dots on the right of the action bar or press the menu button on those devices that have such a button.</p>
<p>The three dots appear only on devices without a menu button. That&#8217;s the way to indicate to the user that more items are available and it&#8217;s also the only way how users can access these items. On devices with a menu button on the other hand you do not have any indicator, but users can always check if an overflow menu is present by clicking the menu key. I actually think the solution for devices without menu button is way better than the solution on devices with a menu button. On these latter devices users always have to guess if an overflow menu is present or not. Alas Samsung, the vendor that sells by far the most Android devices, still ships devices with menu buttons <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<p>Sort your items by importance so that the most important actions are visible all the time. Those actions are the ones your users are most likely to perform on this screen. Think thoroughly about the importance of each item.</p>
<p>Other items should always be in the overflow menu, no matter how much space is left. For example if your app has an about screen, or some license info for the open source libs you use (well, ActionBarSherlock for example) or some information about what has changed with the recent version, I would put all those items into the overflow menu &#8211; no matter how much screen estate you have left.</p>
<p>The Android design page has some more guidance on this on their <a href="http://developer.android.com/design/patterns/actionbar.html" title="Android design page for the action bar pattern">action bar pattern page</a> and also shows you roughly how many items fit on the screen for some selected devices.</p>
<h3>Use the android:icon as well as the android:title attribute</h3>
<p>As you can see the action bar shows only an icon for the &#8220;Add Items&#8221; action. But that doesn&#8217;t mean that you should neglect the strings. First of all these strings are used for screenreaders so that visually impaired people still can use your app. And secondly, if users do not understand an icon immediately, they can longpress those icons until a hint appears that displays the text. Of course this hint is no excuse for confusing icons!</p>
<p>Another thing to note. Overflow menu items show only text. But not so on older devices. There you see the icon and the text. <strong>So always provide values for <code>android:icon</code> and for <code>android:title</code>!</strong></p>
<h3>Use android:showAsAction to define the appearance of the action items</h3>
<p>The <code>item</code> element of the xml file for the action bar can contain four attributes that are only relevant for the action bar: <code>android:showAsAction</code>, <code>android:actionLayout</code>, <code>android:actionViewClass</code> and <code>android:actionProviderClass</code>. Of these I describe only the frst here, the other three are a topic for an extra post.</p>
<p>You can use the attribute <code>android:showAsAction</code> to decide which icons to display and in which way. It can take the following five values:</p>
<table>
<caption>Possible values for the android:showAsAction attribute</caption>
<tr>
<th>Value</th>
<th>Meaning</th>
</tr>
<tr>
<td>ifRoom</td>
<td>Display item if enough room is left for this item</td>
</tr>
<tr>
<td>always</td>
<td>Display this item, regardless of the existing place</td>
</tr>
<tr>
<td>never</td>
<td>This item is not displayed in the action bar directly but in the overflow menu</td>
</tr>
<tr>
<td>withText</td>
<td>Display the icon together with the title text</td>
</tr>
<tr>
<td>collapseActionView</td>
<td>Only relevant for collabsible action views &#8211; not covered in this post</td>
</tr>
</table>
<p>As a rule of thumb you should always use <code>ifRoom</code>, if you want the icon to be part of your action bar and you should use <code>never</code> if you want the item to always be part of the overflow menu.</p>
<p>The <a href="http://developer.android.com/guide/topics/resources/menu-resource.html" title="Android documentation of the menu xml resource file elements and attributes">Android documentation for menu resources</a> explicitly urges you to use <code>always</code> with great care. You should use this attribute only if the element is absolutely necessary. If you use this on multiple items and the place in the action bar is too small to do this properly Android displays overlapping icons. In this case the items are even less accessible than those of the overflow menu.</p>
<p>While you have to pick one of the first three, you can combine these with the value <code>withText</code>. This value decides whether Android shows only the icon or the icon plus the text of the <code>android:title</code> attribute. But Android does show the text only, if enough room is left.</p>
<p>As an example change the menu file to the following code:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &gt;
   &lt;item
      android:id=&quot;@+id/add_item&quot;
      android:icon=&quot;@drawable/ic_action_add&quot;
      android:showAsAction=&quot;ifRoom|withText&quot;
      android:title=&quot;@string/add_item&quot;&gt;
   &lt;/item&gt;
   &lt;item
      android:id=&quot;@+id/reload_list&quot;
      android:icon=&quot;@drawable/ic_action_reload&quot;
      android:showAsAction=&quot;ifRoom|withText&quot;
      android:title=&quot;@string/reload_list&quot;&gt;
   &lt;/item&gt;
   &lt;item
      android:id=&quot;@+id/about&quot;
      android:icon=&quot;@drawable/ic_action_info&quot;
      android:showAsAction=&quot;never&quot;
      android:title=&quot;@string/about&quot;&gt;
   &lt;/item&gt;
&lt;/menu&gt;
</pre>
<p>Now these are the resulting screens depending on the Android version:</p>
<p><div id="attachment_2224" class="wp-caption alignleft" style="width: 235px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbar_with_multiple_icons_on_2-1/" rel="attachment wp-att-2224"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbar_with_multiple_icons_on_2.1-225x300.png" alt="Action bar with multiple icons running on a 2.1 device" width="225" height="300" class="size-medium wp-image-2224" /></a><p class="wp-caption-text">Action bar with multiple icons running on a 2.1 device</p></div><br />
<div id="attachment_2232" class="wp-caption alignleft" style="width: 210px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbar_with_multiple_icons_on_4-2/" rel="attachment wp-att-2232"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbar_with_multiple_icons_on_4.2-200x300.png" alt="Action bar with multiple icons running on a 4.2 device" width="200" height="300" class="size-medium wp-image-2232" /></a><p class="wp-caption-text">Action bar with multiple icons running on a 4.2 device after selecting the overflow menu</p></div></p>
<p class="clear">As you can see on phones Android still only displays the icons. Note what happens on small devices that have no menu button. Android had to put the second item into the overflow menu because it had not enough place for it. On devices with a menu button the second item would be directly visible in the action bar.</p>
<p>This is what the same app looks like on a tablet:</p>
<div id="attachment_2226" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/actionbar_with_multiple_icons_on_4-2_tablet/" rel="attachment wp-att-2226"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/12/actionbar_with_multiple_icons_on_4.2_tablet-300x187.png" alt="Action bar with multiple icons and text running on a 4.2 tablet " width="300" height="187" class="size-medium wp-image-2226" /></a><p class="wp-caption-text">Action bar with multiple icons and text running on a 4.2 tablet</p></div>
<p>Now the <code>withText</code> value makes a difference. While I like items to display text on tablets, it is very unusual. Have a look at other apps to see how they do it, before you decide whether to display text or not. But do not use text to gloss over weaknesses in your icon design.</p>
<h3>Dealing with user input</h3>
<p>So far you have created the action bar and made it look right. But when you click on an item, nothing happens.</p>
<p>What you have to do is to implement the <code>onOptionsItemSelected()</code> method. You do this as you always did for menu item selections:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   // Handle item selection
   switch (item.getItemId()) {
      case R.id.add_item:
         // do s.th.
         return true;
      case R.id.about:
         // do s.th.
         return true;
      default:
         return super.onOptionsItemSelected(item);
   }
}
</pre>
<p>Action bar interaction is like any other user interaction and all the usual rules about the UI thread apply. So don&#8217;t put any stuff in here that&#8217;s long-lasting. Use <code>Loaders</code>, <code>AsyncTasks</code>, <code>IntentServices</code> or whatever you prefer for the specific job to do the heavy lifting.</p>
<h3>What&#8217;s next?</h3>
<p>In this first part of the ActionBar tutorial you have changed your project so that your activities and fragments now inherit from ActionBarSherlock&#8217;s classes and then made it compile and run.</p>
<p>After this you added items to the action bar, learned about the overflow menu and about the ActionBar-related attributes of the menu xml files. But with this you barely scratched the surface of what the action bar covers.</p>
<p>According to the <a href="http://developer.android.com/design/patterns/actionbar.html" title="The action bar pattern page of Android's design guidelines">design guidelines</a> the &#8220;action bar is one of the most important design elements you can implement&#8221;. No wonder it features all sorts of possibilities. And, yes, it brings with it some complexity as well. So there is more to the action bar than just this post.</p>
<p>In the next post I am goig to cover the different navigation types the action bar supports. After this I will write yet another post about the so-called contextual action bar. </p>
<p><a></a><br />
<h3>Appendix</h3>
<p>As mentioned all icons that I use are icons of opoloo&#8217;s <a href="http://androidicons.com" title="Opoloo's Icon Pack page">Android Developers Icons 2</a>. You have to either get this pack, create icons for yourself or download the &#8220;<a href="http://developer.android.com/design/style/iconography.html" title="Iconography page of the Android design guidelines">Action Bar Icon Pack</a>&#8221; from the design site. The latter icon pack contains no &#8220;Add&#8221; icon, so you have to adapt the XML. </p>
<p>You can also use totally inappropriate icons and hassle with the design later on. For the sake of following this tutorial you could use something like <code>@android:drawable/ic_menu_add</code>. But you should never use these for anything else than for just getting on with this tutorial.</p>
<p>You have to add the icons you want to use to the respective folders within your <code>/res</code> folder. For details on how to name these folders see the <a href="http://developer.android.com/guide/topics/resources/providing-resources.html" title="Android guide on how to provide resources">Android documentation about providing resources</a>.<br />
<img src="http://vg03.met.vgwort.de/na/8d441b11b1f249b6adf366287faf0cd7" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/">Adding ActionBarSherlock to Your Project</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/aq-ZPAfFH84" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/</feedburner:origLink></item>
		<item>
		<title>Getting Started With Fragments and the Support Library</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/P1Mduu1MzvA/</link>
		<comments>http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/#comments</comments>
		<pubDate>Thu, 29 Nov 2012 21:15:07 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Fragments]]></category>
		<category><![CDATA[FragmentTransactions]]></category>
		<category><![CDATA[Suppport Library]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2079</guid>
		<description><![CDATA[<p>Fragments are modular building blocks for creating a responsive Android UI. They help you to target different devices and screen sizes while at the same time avoiding code duplication. This post starts with the Android Developers Tools generating a project for you. I then explain some of the generated code and will show you how [...]</p><p>The post <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/">Getting Started With Fragments and the Support Library</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">Fragments are modular building blocks for creating a responsive Android UI. They help you to target different devices and screen sizes while at the same time avoiding code duplication. </p>
<p>This post starts with the Android Developers Tools generating a project for you. I then explain some of the generated code and will show you how to make this code work on older devices. To do this kind of post was suggested by a user of a German forum. Let&#8217;s see if this works well.</p>
<p>This project will grow over time. In the next post I will add the <a href="http://actionbarsherlock.com/" title="Website of the ActionBarSherlock project">ActionBarSherlock</a> library to the project &#8211; but this time it&#8217;s all about understanding the basics. </p>
<p>This post is not taking the approach, <a href="https://plus.google.com/108238734975008671651/" title="Martin van Z's Google plus profile">Martin van Z</a> or <a href="https://plus.google.com/112283223674539938062/" title="Sebastian Kaspari's Google plus profile">Sebastian Kaspari</a> are taking with their respective series &#8220;<a href="http://martin.cubeactive.com/creating-your-own-android-app-part-1-concept/" title="First post of Martin van Z's series on making Android apps">Creating your own Android app</a>&#8221; and &#8220;<a href="http://www.androidzeitgeist.com/p/instant-mustache.html" title="Sebastian Kaspari's overview page for his Instant Moustache series">Instant Moustache</a>&#8220;. They cover planning  stages, sketching and the like as well. Both series make for very interesting reading!</p>
<h3>The basics of fragments</h3>
<p>Fragments constitute a part of your Activity you present to the user. Most often they are used to display some section of the screen and to react to events that happen within this section. Fragments are modular, come with their own lifecycle and help you to avoid code duplication. </p>
<p>Fragments come in two varieties. Either the normal <a href="https://developer.android.com/reference/android/app/Fragment.html" title="Documentation of Android's normal Fragment class">Fragment</a> class within the <code>android.app</code> package that was introduced with API level 11 (Honeycomb). And the support library <a href="https://developer.android.com/reference/android/support/v4/app/Fragment.html" title="Documentation of the Fragment class of Android's support library">Fragment</a> of the package <code>android.support.v4.app</code>. Both have subclasses like <code>DialogFragment</code> or <code>ListFragment</code>. <strong>You cannot use a mix of normal and support libary fragments.</strong></p>
<p>If you want to target older devices in your project, always go for the classes of the support library. If you only care about newer Android releases, you can use the normal fragments.</p>
<p>In this post I specifically have a look at how to make fragments work with the support library. Given the vast amount of Android 2.2 and 2.3 devices currently out there I still recommend to always try to target these devices where possible. And since the differences in the Android framework between Android 2.1, 2.2 and 2.3 are not too big, I suggest to try with 2.1 and only increase the minimum API level if you have a need for this.</p>
<p>Fragments have a UI on their own. As usual you inflate your view, which you have defined in XML files. While Fragments without any UI are possible, I won&#8217;t cover those in this post. </p>
<p>View creation is nothing special. Apart from one thing. If you use the <code>android:onClick</code> attribute for your view elements, you cannot implement the method in the fragment. You have to implement it in the activity. If you want to deal with click events in your fragment you have to add <a href="https://developer.android.com/reference/android/view/View.OnClickListener.html" title="Documentation of Android's View.OnClickListener interface">OnClickListeners</a> for those view elements programmatically.</p>
<p>Fragments have a lifecycle of their own. It is a bit more complex than those of Activities, because Fragments can be attached to and detached from their enclosing activities. I will cover some of the lifecycle methods below. </p>
<p>So much for the background on fragments. If you want to learn more, head over to <a href="http://developer.android.com/guide/components/fragments.html" title="Google's documentation of Android's fragments">Google&#8217;s documentation about Fragments</a> after reading this post.</p>
<p>In the next section I start by creating the project using <a href="http://developer.android.com/tools/help/adt.html" title="Documentation of the Android Developer Tools">Android&#8217;s Developer Tools</a>.</p>
<h3>Creating the project using the Android Developer Tools</h3>
<p>To follow the steps outlined here you must have Eclipse together with the Android Developer Tools plugins installed. You can <a href="http://developer.android.com/sdk/index.html" title="Android SDK bundle download page">download complete bundles on Android&#8217;s SDK page</a>.</p>
<p>In Eclipse go to File -&gt; New Project -&gt; Android Application Project and click &#8220;Next&#8221;. A wizard pops up:</p>
<div id="attachment_2101" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/new_project_wizard.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/new_project_wizard-300x300.png" alt="Android Developer Tools project wizard" width="300" height="300" class="size-medium wp-image-2101" /></a><p class="wp-caption-text">Android Developer Tools project wizard</p></div>
<p>Fill in the required fields as shown above and click next until you come to the screen where you can select the type of project you want to create:</p>
<div id="attachment_2103" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/minimum_api_level_11.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/minimum_api_level_11-300x286.png" alt="Project wizard for master detail projects" width="300" height="286" class="size-medium wp-image-2103" /></a><p class="wp-caption-text">Project wizard for master detail projects. Note the API level warning.</p></div>
<p>Select the master detail project type. That means that you have a list of elements on the left and a detail view on the right &#8211; if your screen is big enough. </p>
<p>As you can see the API level we have chosen isn&#8217;t supported. So go back to the beginning and switch to API level 11. You will correct this later on:</p>
<div id="attachment_2104" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/switch_to_api_level_11.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/switch_to_api_level_11-300x286.png" alt="Switch to API level 11 in the project wizard" width="300" height="286" class="size-medium wp-image-2104" /></a><p class="wp-caption-text">Switch to API level 11 in the project wizard</p></div>
<p>Now go on until you come to the screen showing the name for the entities you want to deal with:</p>
<div id="attachment_2105" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/select_entity_name.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/select_entity_name-300x286.png" alt="Select an enity name in the wizard" width="300" height="286" class="size-medium wp-image-2105" /></a><p class="wp-caption-text">Select an enity name in the wizard</p></div>
<p>Item is the default here. I do not bother to change this, but you can change it to whatever your app is going to deal with &#8211; like Book, File and so on. Keep in mind that the wizard creates the names of the classes accordingly. So whenever I refer to <code>Item</code>, <code>ItemListFragment</code> and so on, substitute Item with the noun you have chosen in this dialog.</p>
<p>Now click Finish and the Eclipse generates the project for you. </p>
<p>If you never have downloaded the support library and do not use the adt bundle, the following dialog will pop up. It forces you to download the library and attaches it to your project:</p>
<div id="attachment_2111" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/adding_support_library.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/adding_support_library-300x286.png" alt="The wizard alerts you that the support library is missing" width="300" height="286" class="size-medium wp-image-2111" /></a><p class="wp-caption-text">The wizard alerts you that the support library is missing</p></div>
<h3>Fragments lifecycle</h3>
<p>I do not cover the entire lifycycle of Fragments. Much of it is comparable to the lifecycle of Activities. But by having a look at the code, I will show some common lifecycle methods you should know about.</p>
<p>First, have a look at <code>ItemDetailFragment</code>. This fragment inflates a view. But it does not do so in the <code>onCreate()</code> method like you would do in an activity, but within the <code>onCreateView()</code> method. Android passes the inflater you need to use for view inflation into the method, as well as the container for your view.</p>
<p>The inflation always looks like this:</p>
<pre class="brush: java; title: ; notranslate">
View rootView = inflater.inflate(
      R.layout.fragment_item_detail,
      container, false);
</pre>
<p>The last parameter states that your view should not be attached to the container. It must always be <code>false</code> for fragment view inflation. Android adds your view to the container itself!</p>
<p>Since fragments can be attached or detached from an activity, there also exist <code>onAttach()</code> and <code>onDetach()</code> methods. After your fragment has been attached, you can use <code>getActivity()</code> within your fragment to get to the enclosing activity.</p>
<p>The <code>ItemListFragment</code> makes use of both methods to set a callback interface. I explain this interface in the next section.</p>
<p>The other lifecycle methods are the same as for activities. You can read <a href="http://developer.android.com/guide/components/fragments.html#Creating" title="Android's documentation about Fragments">more about the lifecycle in Android&#8217;s documentation</a>.</p>
<h3>Callback interface</h3>
<p>Fragments and activities need to communicate with each other. But you do not want to couple them closely. Your fragment might end up in multiple activities, so it should never have a direct link back to the activity it belongs to. Instead it is common practice to use interfaces to deal with this. Your fragments define callback interfaces and your Activities must implement these interfaces.</p>
<p>Have a look at the <code>ItemListFragment</code>. It contains the interface named <code>Callbacks</code>. The fragment uses this interface to communicate to the activity that an item has been selected:</p>
<pre class="brush: java; title: ; notranslate">
public interface Callbacks {
   /**
    * Callback for when an item has been selected.
    */
   public void onItemSelected(String id);
}
</pre>
<p>This interface is used in the onListItemClick() method:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public void onListItemClick(ListView listView, View view, int position,
      long id) {
   super.onListItemClick(listView, view, position, id);
   
   // Notify the active callbacks interface (the activity, if the
   // fragment is attached to one) that an item has been selected.
   mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}
</pre>
<p>See also the methods <code>onAttach()</code> and <code>onDetach()</code>. That&#8217;s where the internal member <code>mCallbacks</code> is set to the enclosing activity or to a dummy implementation, if this fragment is no longer part of an activity.</p>
<p>The <code>ItemListActivity</code> implements this interface. So look at the activity&#8217;s <code>onItemSelected()</code> method. It first checks if you are in dual pane or single pane mode (see next section). And depending on the result it either starts another activity or replaces the second fragment.</p>
<p>When you have many callbacks and multiple fragments using interfaces for every fragment can become pretty unwieldy. In this case I recommend to use a bus based approach like <a href="https://github.com/greenrobot/EventBus" title="Project page of the EventBus library">EventBus</a> or <a href="http://square.github.com/otto/" title="Project page of the Otto library">Otto</a>. But that&#8217;s a topic for another post. At the current state of the project the interface approach works fine.</p>
<h3>Dual pane or not</h3>
<p>The most important reason to use fragments is to make your app responsive. That means make it adapt nicely to a change in orientation and to different screen sizes and aspect ratios.</p>
<p>The generated project shows this by using two panes on tablets and a single pane on phones. It defines two layouts for the <code>ItemListActivity</code> in the layout folder: <code>activity_item_list.xml</code> and <code>activity_item_twopane.xml</code>. </p>
<div id="attachment_2112" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/layout_folder.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/layout_folder-300x108.png" alt="The files in the layout folder" width="300" height="108" class="size-medium wp-image-2112" /></a><p class="wp-caption-text">The files in the layout folder</p></div>
<p>Wait a moment. Two layouts for the same activity with different names and both in the default <code>layout</code> folder? What&#8217;s up with that?</p>
<p>Well have a look at the <code>values</code> folders in the <code>res</code> directory:</p>
<div id="attachment_2114" class="wp-caption alignnone" style="width: 219px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/values_folder1.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/values_folder1.png" alt="The different values folders" width="209" height="256" class="size-full wp-image-2114" /></a><p class="wp-caption-text">The different values folders</p></div>
<p>Of interest in this case are the <code>values-large</code> and the <code>values-sw600dp</code> folders. Both contain a file named <code>refs.xml</code> which references the <code>activity_item_twopane.xml</code> file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;resources&gt;
   &lt;!--
   Layout alias to replace the single-pane version of the layout with a
   two-pane version on Large screens.
   
   For more on layout aliases, see:

http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters

   --&gt;
   &lt;item name=&quot;activity_item_list&quot; type=&quot;layout&quot;&gt;@layout/activity_item_twopane&lt;/item&gt;
&lt;/resources&gt;
</pre>
<p>Note the <code>name</code> attribute of the reference. Its value is <code>activity_item_list</code>. This means that when you use <code>R.layout.activity_item_list</code> in your code, Android will replace this value with <code>R.layout.activity_item_twopane</code>. Of course only if one of the two qualifiers <code>large</code> or <code>sw600dp</code> applies. That way you have to declare the layout only once and can refer to it in multiple places. </p>
<p>You have to use the <code>large</code> qualifier even though a more specific qualifier is present, because the <code>swXYZdp</code> qualifier will only be recognized from API level 13 onwards. Prior to this only the screen qualifiers folders (small, normal, large and xlarge) have been recognized.</p>
<p>If you look at the <code>activity_item_twopane.xml</code> file, you will see that a fragment and a <code>FrameLayout</code> is declared.</p>
<p>You can declare fragments either directly in your layout files or you can use <code>FragmentTransactions</code> to add fragments programmatically. In this case one fragment is added using the xml file while the other is added using a transaction. The <code>FrameLayout</code> within this file is the container that you later add the fragment to in your transaction.</p>
<p>In the <code>ItemListActivity</code> you finally find this code snippet:</p>
<pre class="brush: java; title: ; notranslate">
if (findViewById(R.id.item_detail_container) != null) {
   // The detail container view will be present only in the
   // large-screen layouts (res/values-large and
   // res/values-sw600dp). If this view is present, then the
   // activity should be in two-pane mode.
   mTwoPane = true;
   
   //...
}
</pre>
<p>So by either finding this container or not, the activity knows whether Android selected the two pane layout or not. </p>
<p>Depending on this, the activity handles a list item click differently in the <code>onItemSelected()</code> callback method. </p>
<p>There is also another approach used on some of Google&#8217;s Android training pages and mentioned by Kiran Rao in the comment section. The other approach uses a boolean variable in xml files. Have a look at Kiran&#8217;s comment to learn more about this approach.</p>
<p>You should really dig deeper into how to deal with multiple screen sizes. It is a very important concept for supporting multiple device sizes in Android. Thus I recommend you take the <a href="http://developer.android.com/training/multiscreen/screensizes.html" title="Training about supporting different screen sizes">training about multiple screensizes</a> on the Android site after reading this post. Do not write apps for phones only. As has just been published, the <a href="http://techcrunch.com/2012/11/28/ipad-and-android-tablet-market-share-margin-narrows-much-faster-than-originally-predicted/" title="Report  about shift in tablet market share">tablet market for Android is gaining serious traction</a>. Don&#8217;t miss out on this. And don&#8217;t risk bad ratings just because you ignored bigger screens!</p>
<h3>FragmentTransactions</h3>
<p><a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html" title="Documentation of the support library's FragmentTrasaction class">FragmentTransactions</a> are Android&#8217;s way of adding, removing, hiding or replacing fragments to or from your activity. As the name transaction implies either all actions of the transaction are done or none. So you transfer from one valid state of your app to another one. </p>
<p>But you not only manage the fragments themself, you can also define custom animations to display for fragments being attached and detached.</p>
<p>And you can add a complete transaction to your backstack. In this case clicking back would do everything within the transaction in exactly the reverse order. If you do not use the addToBackStack() method to add your transaction to the backstack, this transaction will be ignored. You can see this in the sample app in two pane mode. Clicking on different list items starts a transaction and causes a replacement of fragments. But by clicking back you just leave the app. Which makes sense, since you do not want every list item click to be added to the back stack.</p>
<p>I have covered here just some basics of FragmentTransactions. To learn more about them, visit Daniel Lew&#8217;s <a href="http://daniel-codes.blogspot.de/2012/06/fragment-transactions-reference.html" title="Daniel Lew's post about FragmentTransactions">blog post about FragmentTransactions</a>.</p>
<h3>Make it run on older devices</h3>
<p>The code was generated by the wizard for API level 11. But it uses the support library already &#8211; so shouldn&#8217;t it run on older versions as well?</p>
<p>The heavy lifting already has been done. The wizard created both activities as subclasses of <code>FragmentActivity</code>. This is a class of the support library that allows you to access an <code>FragmentManager</code> using <code>getSupportFragmentManager()</code>. </p>
<p>Two changes are needed to make it run on older versions.</p>
<p>First the generated class <code>ItemListFragment</code> contains a layout constant that has been introduced in API level 11: <code>simple_list_item_activated_1</code>. This specific layout highlights activated list items. Which is useful, if you have a multi-pane layout, because it shows the user which list item is selected and displayed in the details pane.</p>
<p>I ignore the highlighting for now and just try to get the code to run:</p>
<pre class="brush: java; title: ; notranslate">
int layout = android.R.layout.simple_list_item_1;
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB) {
   layout = android.R.layout.simple_list_item_activated_1;
}
setListAdapter(new ArrayAdapter&lt;DummyContent.DummyItem&gt;(
      getActivity(),
      layout,
      android.R.id.text1, 
      DummyContent.ITEMS));
</pre>
<p>The second problem is the ActionBar, which is not available on older devices without adding an additional library. Since this is the topic of my next post, I simply ignore the ActionBar on older devices for now. Change the line with <code>getActionBar()</code> to this in the <code>ItemDetailActivity</code>: </p>
<pre class="brush: java; title: ; notranslate">
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB) {
   getActionBar().setDisplayHomeAsUpEnabled(true);
}
</pre>
<p>Now you get a Lint warning. That the call requires API level 11 but that your manifest file states API level 7 as a minimum. Add an annotation to suppress the new API warnings for the <code>onCreate()</code> method:</p>
<pre class="brush: java; title: ; notranslate">
@SuppressLint(&quot;NewApi&quot;)
</pre>
<p>Now change your <code>AndroidManifest.xml</code> file to support API level 7:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;uses-sdk
   android:minSdkVersion=&quot;7&quot;
   android:targetSdkVersion=&quot;16&quot; /&gt;
</pre>
<p>With these changes, you can now run the project on older devices.</p>
<h3>Lessons learned</h3>
<p>You have seen how to create a master detail project using the Android Developer Tools and how the generated project works.</p>
<p>I have given you details about what fragements are and what to use them for. And I have shown you some code snippets of the generated project and explained why it is done that way.</p>
<p>Also I have shown to you how to make this project backwards compatible. That way you can run the code on older devices as well.</p>
<p>Keep in mind: The Android Developer Tools project is evolving at a rapid pace. So if you read this post in a few months some of this probably has changed &#8211; though the basics should remain the same. </p>
<p>I strongly recommend to keep an eye on updates to the developer tools. Check for updates in Eclipse regularly. </p>
<p>And if you want to know of what&#8217;s to come, visit the <a href="http://tools.android.com/" title="Homepage of the ADT project">project page of the ADT team</a> and especially their <a href="http://tools.android.com/recent" title="Announcements of changes of the Android Developer Tools">announcements of recent changes</a>. The team announces preview versions there on a regular basis. </p>
<p>Next week you will add an ActionBar using the library ActionbarSherlock to your project. Until then have a good look at the code and jump to <a href="http://developer.android.com/training/basics/fragments/index.html" title="Android training series about fragments">Android&#8217;s training session about fragments</a> to learn more. Fragments are very important and it is essential to fully understand them!<br />
<img src="http://vg03.met.vgwort.de/na/c032d072d64a4b82883d482992275f34" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/">Getting Started With Fragments and the Support Library</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/P1Mduu1MzvA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/getting-started-with-fragments-and-the-support-library/</feedburner:origLink></item>
		<item>
		<title>Android: How to Use Two Data Sources in ListViews?</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/_c79pBHrNpw/</link>
		<comments>http://www.grokkingandroid.com/android-how-to-use-two-data-sources/#comments</comments>
		<pubDate>Thu, 22 Nov 2012 10:34:15 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[ListView]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/wordpress/?p=43</guid>
		<description><![CDATA[<p>Sometimes in our apps we have the need to link to data of other sources. You have a database of your own for your app, but some records also point to the MediaStore content provider to calendar entries or to contacts. For all detail pages this is not much of a problem. You get the [...]</p><p>The post <a href="http://www.grokkingandroid.com/android-how-to-use-two-data-sources/">Android: How to Use Two Data Sources in ListViews?</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">Sometimes in our apps we have the need to link to data of other sources. You have a database of your own for your app, but some records also point to the MediaStore content provider to calendar entries or to contacts.</p>
<p>For all detail pages this is not much of a problem. You get the data from your database and query the external content provider for additional data based on the id or lookup uri that you stored in your database.</p>
<p>But what to do, if you want to show data in <code>ListViews</code>? Say contact pictures, event titles for multiline list elements and so on. Then it gets complicated.</p>
<p>From what I see, we have the following choices. Neither is fully satisfying &#8211; which is why I would like to hear how you deal with these kind of problems.</p>
<ul>
<li>
You get a list of all elements of the <code>ListView</code> by querying your database. And you query the content provider for each list entry using an <code>AsyncTask</code>. This is the a very memory efficient solution.</p>
<p>For images (album covers, contact pictures&#8230;) this is probably the best option. Especially if combined with an in-memory cache. Even if users would love to see images immediately, they know this is not feasible and accept some lag before images are displayed. </p>
<p>But not so for any text elements. The second line of a multiline list element should be visible instantaneously. So for text this option is not acceptable.
</li>
<li>
You could query the content provider for all entries at startup, put them in a HashMap and use this map later on. Well this might work if the content provider has only a few entries. But there might be thousands of media files on a SD card or thousands of contacts for a big company. In cases like these this won&#8217;t work. It would be a big waste of memory &#8211; especially since you probably only need very few of these rows at all.</p>
<p>The Hashmap would also need too long to be created in the first place. The waiting period for the inital screen would be inacceptable. So this is basically a no-go.
</li>
<li>
You could keep redundant data in your own database. For every record that contains a link to the external content provider you also include the data, you need in the listview (e.g. the band name). That&#8217;s the option I have chosen. You only cache the results you actually need. </p>
<p>There are two drawbacks to this solution: First you are wasting device memory. That is flash memory not RAM. No problem for most high end devices but low cost devices often have very limited memory available.</p>
<p>Second you have to sync the data whenever your app restarts. If your app stays in the background for quite a while, the user might have changed the external data source. In fact this might even happen while your app is in the foreground if a sync adapter changes values based on changes of the backend. Now your list reflects the wrong values until your database has re-synced with the external provider. </p>
<p>You could choose to <a href="http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/" title="Use Android’s ContentObserver in Your Code to Listen to Data Changes">listen to changes in the content provider</a> in a service and update your database when needed. Activities then could query for changes.</p>
<p>Whether these two issues of this option pose problems for you depend on the type of app. In most cases a correction of a changed value later on should be okay. And if you do not have hundreds or thousands of rows in your own table the inefficiencies are not that bad as well.
</li>
</ul>
<p>Now I would really like to hear what you think. Probably there are other options, I have overlooked. Or better ways to make one of these three options work. Please let me know in the comments, on G+ or on Twitter. Thanks!</p>
<p>If you are curious about the G+ discussion, have a look at <a href="https://plus.google.com/101948439228765005787/posts/LafBGnKrApF" title="G+ announcement of this post">my G+ announcement of this post</a>.</p>
<p><img src="http://vg03.met.vgwort.de/na/89cd6e5bf7864c118c387988edef1831" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/android-how-to-use-two-data-sources/">Android: How to Use Two Data Sources in ListViews?</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/_c79pBHrNpw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/android-how-to-use-two-data-sources/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/android-how-to-use-two-data-sources/</feedburner:origLink></item>
		<item>
		<title>Use Android’s ContentObserver in Your Code to Listen to Data Changes</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/jcnaYR64Mtc/</link>
		<comments>http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/#comments</comments>
		<pubDate>Thu, 15 Nov 2012 08:44:26 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[ContentObserver]]></category>
		<category><![CDATA[onChange()]]></category>
		<category><![CDATA[Quick Tip]]></category>
		<category><![CDATA[registerContentObserver()]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1907</guid>
		<description><![CDATA[<p>When you are using a content provider as a client, chances are that you want to know whenever the data changes. That&#8217;s what Android&#8217;s class ContentObserver is for. To use the ContentObserver you have to take two steps: Implement a subclass of ContentObserver Register your content observer to listen for changes Implement a subclass of [...]</p><p>The post <a href="http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/">Use Android&#8217;s ContentObserver in Your Code to Listen to Data Changes</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">When you are using a content provider as a client, chances are that you want to know whenever the data changes. That&#8217;s what Android&#8217;s class <a href="http://developer.android.com/reference/android/database/ContentObserver.html" title="Documentation of Android's ContentObserver class">ContentObserver</a> is for.</p>
<p>To use the <code>ContentObserver</code> you have to take two steps:</p>
<ul>
<li>Implement a subclass of <code>ContentObserver</code></li>
<li>Register your content observer to listen for changes</li>
</ul>
<h3>Implement a subclass of ContentObserver</h3>
<p><code>ContentObserver</code> is an abstract class with no abstract methods. Its two <code>onChange()</code> methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them. </p>
<p>Since Google added one of the two overloaded <code>onChange()</code> methods as recently as API-level 16, this method&#8217;s default behavior is to call the other, older method. </p>
<p>Here is, what a normal implementation would look like:</p>
<pre class="brush: java; title: ; notranslate">
@SuppressLint(&amp;quot;NewApi&amp;quot;)
class MyObserver extends ContentObserver {		
   public MyObserver(Handler handler) {
      super(handler);			
   }

   @Override
   public void onChange(boolean selfChange) {
      this.onChange(selfChange, null);
   }		

   @Override
   public void onChange(boolean selfChange, Uri uri) {
      // do s.th.
      // depending on the handler you might be on the UI
      // thread, so be cautious!
   }		
}
</pre>
<p>Some things are important with the above code. The first thing you must know, is that the second method is only available from API level 16 onwards. That&#8217;s why I added the <code>SuppressLint</code> annotation. The code works fine on older devices, but in this case Android obviously always calls the old one. So your code should not rely on a URI to work properly.</p>
<p>Also notice the <a href="http://developer.android.com/reference/android/os/Handler.html" title="Documentation of Android's Handler class">Handler</a> parameter in the constructor. This handler is used to deliver the <code>onChange()</code> method. So if you created the <code>Handler</code> on the UI thread, the <code>onChange()</code> method will be called on the UI thread as well. In this case avoid querying the <code>ContentProvider</code> in this method. Instead use an <code>AsyncTask</code> or a <code>Loader</code>. </p>
<p>If you pass a <code>null</code> value to the constructor, Android calls the <code>onChange()</code> method immediately &#8211; regardless of the current thread used. I think it&#8217;s best to always use a handler when creating the <code>ContentObserver</code> object.</p>
<h3>Register your content observer to listen for changes</h3>
<p>To register your <code>ContentObserver</code> subclass you simply have to call the <code>ContentResolver's</code> <code>registerContentObserver()</code> method:</p>
<pre class="brush: java; title: ; notranslate">
getContentResolver().
      registerContentObserver(
            SOME_URI, 
            true, 
            yourObserver);
</pre>
<p>It takes three parameters. The first is the URI to listen to. I cover the URI in more detail in the next section.</p>
<p>The second parameter indicates whether all changes to URIs that start with the given URI should trigger a method call or just changes to exactly this one URI. This can be handy for say the <a href="https://developer.android.com/reference/android/provider/ContactsContract.html" title="Documentation of Android's ContactsContract content provider">ContactsContract</a> URI with its many descendants. But it can also be detrimental in that the actual change, that caused the method call, is even more obscure to you.</p>
<p>The third parameter is an instance of your <code>ContentObserver</code> implementation.</p>
<h3>The URIs you can observe</h3>
<p>As described in my <a href="http://www.grokkingandroid.com/android-tutorial-content-provider-basics/" title="Android Tutorial: Content Provider Basics">introduction to content providers</a> content URIs can be directory-based or id-based.</p>
<p>Both of these URI-types can be used for your content observer. If you have a detail screen you would use an id-based URI for your observer, and when you use a list of data a directory-based URI is more appropriate. </p>
<p>This does not always work, though. <code>ContactsContract</code> for example always triggers a change, whenever any contact was changed, even if you are listening to a more specific URI. It depends on the correct implementation of the content provider. I have filed a <a href="http://code.google.com/p/android/issues/detail?id=39698" title="Issue for ContactsContract incorrect notification behavior">bug report for the ContactsContract provider</a>. Please vote for this issue, if you agree.</p>
<p>When you write a content provider for your app, <strong>take care of notifying the correct URI.</strong> Only if you do so, the feedback mechanism described here works. This is important for your observers &#8211; or if the provider is exported for your clients&#8217; observers as well. And it is also important for Loaders. See my post about <a href="http://www.grokkingandroid.com/android-tutorial-writing-your-own-content-provider/" title="Android Tutorial: Writing your own Content provider">how to write content providers</a> to learn more about this.</p>
<p><strong>Note</strong>: If <a href="http://www.grokkingandroid.com/using-loaders-in-android/" title="How to Use Loaders in Android">you use Loaders</a> you do not need to listen to changes yourself. In this case Android registers a <code>ContentObserver</code> and triggers your <a href="https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html" title="Documentation of Android's LoaderCallbacks interface">LoaderCallbacks</a> <code>onLoadFinished()</code> method for any changes.</p>
<h3>Do not forget to unregister your content observer</h3>
<p>When you have registered a content observer, it is your responsibility to also unregister it. Otherwise you would create a memory leak and your Activity would never be garbage collected.</p>
<p>To unregister you call the <code>unregisterContentObserver()</code> method of the <code>ContentResolver</code>:</p>
<pre class="brush: java; title: ; notranslate">
getContentResolver().
      unregisterContentObserver(yourObserver);
</pre>
<p>You register your observer in the <code>onResume()</code> lifecycle method and you unregister it in the <code>onPause()</code> method.</p>
<p>This is not relevant to ContentObservers alone but applies to everything you register. <strong>As a general rule of thumb: Whenever you start coding <code>registerXYZ()</code> immediately also add the code to <code>unregisterXYZ()</code></strong>. Otherwise you might later forget about it and inadvertently create memory leaks.</p>
<h3>Sometimes you wish you would know more about the changes</h3>
<p>The main downside with content observers is, that you do not get any additional information about what has changed. For directory-based URIs it would be nice to get a list of IDs that have changed. Some providers can have many records and re-reading all records, if only a few have changed, is a waste of resources in a mobile environment. Also some hint of the type of change would be nice. Like if a record was deleted or inserted.</p>
<p>The <code>ContentProvider</code> responsible for the change knows all this. So this would be no problem to add. Of course it has to be added in a backwards-compatible way.</p>
<p>API level 16 added a URI to the <code>onChange()</code> method, but this isn&#8217;t sufficient for updates of multiple records and also doesn&#8217;t tell you anything about the type of change.</p>
<h3>Wrapping up</h3>
<p>This quick tip showed you how to leverage Android&#8217;s <code>ContentObserver</code>. This makes it easy to react to updates of the data you are using.</p>
<p>As you have seen, it is pretty easy to implement the <code>ContentObserver</code> subclass. You have also seen that you can register it to listen to id-based as well as directory-based URIs. </p>
<p>Of course this works only, if the content provider for the URI you are observing, is correctly implemented and notifies clients of changes. If you are implementing a content provider yourself, have a look at my <a href="http://www.grokkingandroid.com/android-tutorial-writing-your-own-content-provider/" title="Android Tutorial: Writing your own Content provider">tutorial on writing a content provider</a> for how to do so.<br />
<img src="http://vg03.met.vgwort.de/na/1cd83a63fb91456b960e897829735154" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/">Use Android&#8217;s ContentObserver in Your Code to Listen to Data Changes</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/jcnaYR64Mtc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/</feedburner:origLink></item>
		<item>
		<title>What You Need to Know About the Intents of Android’s Calendar App</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/k98cU_0Glmc/</link>
		<comments>http://www.grokkingandroid.com/intents-of-androids-calendar-app/#comments</comments>
		<pubDate>Thu, 08 Nov 2012 06:53:41 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[ACTION_EDIT]]></category>
		<category><![CDATA[ACTION_INSERT]]></category>
		<category><![CDATA[ACTION_VIEW]]></category>
		<category><![CDATA[Calendar Intents]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1891</guid>
		<description><![CDATA[<p>When your app needs to access calendar data you have to choose whether to use the CalendarContract content provider or whether to use Intents to start specific Activities of the Calendar app. This post covers the intents offered by the official Calendar app. While with using Intents your possibilities are limited compared to those of [...]</p><p>The post <a href="http://www.grokkingandroid.com/intents-of-androids-calendar-app/">What You Need to Know About the Intents of Android&#8217;s Calendar App</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">When your app needs to access calendar data you have to choose whether to use the <a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/" title="Android’s CalendarContract Content Provider">CalendarContract content provider</a> or whether to use Intents to start specific Activities of the Calendar app. This post covers the intents offered by the official Calendar app.</p>
<p>While with using Intents your possibilities are limited compared to those of the content provider, using intents has the advantage that the user already knows the Calendar app and that some things get automated for you (e.g. alarm and attendee settings). And if you only use intents, your app doesn&#8217;t need the permissions you need for the content provider.</p>
<p>As of now you can do exactly four things:</p>
<ul>
<li>You can open the Calendar app at a specific date</li>
<li>You can view events</li>
<li>You can create new events</li>
<li>You can edit events</li>
</ul>
<p>Well, actually you can only do three things, since the last intent doesn&#8217;t work. More on this later.</p>
<p>From ICS onwards the Calendar is part of Android&#8217;s standard apps. So it is very unlikely that the Calendar app is missing. Nevertheless you should always test for the availability of Intents. I omit this in the code samples in the next paragraphs since these are examples only &#8211; but you should not! You can read more about this in my post about <a href="http://www.grokkingandroid.com/checking-intent-availability/" title="Checking Intent Availability in Android">how to test for Intent availability</a>.</p>
<h3>Opening the Calendar app</h3>
<p>Maybe you want to give the user the possibility to view her calendar. In this case you can use the <code>ACTION_VIEW</code> and <code>CalendarContract.CONTENT_URI</code> as the Uri to start the app. </p>
<p>You have to add the time at which you want to open the calendar. You can either do this by concatenating Strings or by using Android&#8217;s <code>Uri.Builder</code> helper class.</p>
<p>In the following code fragment I show how you would open the calendar with a date two month in the future:</p>
<pre class="brush: java; title: ; notranslate">
Calendar cal = new GregorianCalendar(); 
cal.setTime(new Date()); 
cal.add(Calendar.MONTH, 2); 
long time = cal.getTime().getTime(); 
Uri.Builder builder = 
      CalendarContract.CONTENT_URI.buildUpon(); 
builder.appendPath(&quot;time&quot;); 
builder.appendPath(Long.toString(time)); 
Intent intent = 
      new Intent(Intent.ACTION_VIEW, builder.build()); 
startActivity(intent); 
</pre>
<h3>Creating an event</h3>
<p>Probably more interesting is creating an event. In this case the action to use is <code>ACTION_INSERT</code> and the URI to use is <code>Events.CONTENT_URI</code>. What makes this option so compelling is that you do not have to add any Intent extras. You can open the event editor without any data &#8211; in which case only some default values of the form are prefilled as you can see in the next screen.</p>
<div id="attachment_2007" class="wp-caption alignnone" style="width: 210px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/create_event_activity.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/create_event_activity-200x300.png" alt="Form for entering events" width="200" height="300" class="size-medium wp-image-2007" /></a><p class="wp-caption-text">Form for entering events</p></div>
<p>If the user has no calendar account added, Android shows a dialog that warns the user that no events can be added as long as no account exists. This is pretty common on the emulator &#8211; but should be the exception on a real device. Normally device vendors have a calendar with some sync adapter of their own. But even if this is not the case, your app will not crash. The next screenshot shows the message in this case.</p>
<div id="attachment_2006" class="wp-caption alignnone" style="width: 210px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/no_calendar_account_warning.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/11/no_calendar_account_warning-200x300.png" alt="Warning when no calendar account exists" width="200" height="300" class="size-medium wp-image-2006" /></a><p class="wp-caption-text">Warning when no calendar account exists</p></div>
<p>The simplest code to create an event with an intent is this:</p>
<pre class="brush: java; title: ; notranslate">
Intent intent = 
      new Intent(Intent.ACTION_INSERT, Events.CONTENT_URI);
startActivity(intent); 
</pre>
<p>But if you want, you can add data so that the form is prefilled with these values. You can basically set all the data, that you can use to c<a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/" title="Android’s CalendarContract Content Provider">reate events with the content provider</a>. For attendees and alarms you have to use other constants, since they are not part of the <code>Events</code> class. Strangely Google has decided that for the start- end end-time of the event you also need special constants. Why they didn&#8217;t use the constants of the Events class is beyond me. This makes the code kind of ugly and the API harder to understand than necessary. As you can see in the next code fragment these constants from differing classes do not look that good:</p>
<pre class="brush: java; title: ; notranslate">
Calendar cal = new GregorianCalendar(); 
cal.setTime(new Date()); 
cal.add(Calendar.MONTH, 2); 
Intent intent = new Intent(Intent.ACTION_INSERT); 
intent.setData(Events.CONTENT_URI); 
intent.putExtra(Events.TITLE, &quot;Some Test Event&quot;); 
intent.putExtra(Events.ALL_DAY, true); 
intent.putExtra(
      CalendarContract.EXTRA_EVENT_BEGIN_TIME, 
      cal.getTime().getTime()); 
intent.putExtra(
      CalendarContract.EXTRA_EVENT_END_TIME, 
      cal.getTime().getTime() + 600000); 
intent.putExtra(
      Intent.EXTRA_EMAIL, 
      &quot;attendee1@yourtest.com, attendee2@yourtest.com&quot;); 
startActivity(intent); 
</pre>
<h3>Viewing an event</h3>
<p>In addition to creating a new event you sometimes want users to view an event. Once again an intent is useful here because the presentation of the intent is done in a way that the user is accustomed to. But to do so, you need to have the event id &#8211; for which you need the content provider.</p>
<p>For the next example I assume that you already have the id for the event. In this case the code is really simple:</p>
<pre class="brush: java; title: ; notranslate">
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri.Builder uri = Events.CONTENT_URI.buildUpon();
uri.appendPath(Long.toString(yourEventId));
intent.setData(uri.build());
startActivity(intent);
</pre>
<p>That&#8217;s all nice and swell. Alas, the default Calendar app manipulates the back stack and pressing back does not jump back to your app but to the calendar view. That&#8217;s the correct behavior when started from the calendar widget but not when the calendar app has been called from another app.</p>
<p>Your users have to press back twice to get back to the point where they came from. And they will blame you for this even though it&#8217;s not your fault. Because of this try to avoid the need for viewing events. It might be better to open the calendar at the correct date.</p>
<p>I have filed a <a href="http://code.google.com/p/android/issues/detail?id=28704" title="Bug report for bad back button behaviour">bug report for this issue</a>. If you agree, that this is annoying, please star this issue.</p>
<p>And it&#8217;s not just me, at least <a href="http://stackoverflow.com/questions/13081767/how-to-return-back-to-my-application-after-calling-external-intent-calendar-ap" title="StackOverflow user asking how to deal with the back button problem">one developer at StackOverflow complains about the same bug</a>.</p>
<h3>Editing an Event</h3>
<p>The final Intent that the calendar app supports is editing an event. Well at least according to the <a href="https://developer.android.com/guide/topics/providers/calendar-provider.html#intent-edit" title="Documentation about the Intents supported. In this case the edit intent">Android documentation</a>.</p>
<p>Now it would have been nice if it worked. But not so. What you actually see if you use the intent for editing is the read-only version of the editing activity. In this case you can only change minor stuff like the reminders or the timezone.  Theoretically you can provide additional data &#8211; though this unsurprisingly also doesn&#8217;t work. </p>
<p>Add to this that the back button causes trouble again. When you click &#8220;Done&#8221; the Calendar-View is shown. The more natural behaviour would have been to save the changes and then return to where you came from. At least clicking &#8220;Cancel&#8221; or the back button works as expected.</p>
<p>This is pretty annoying since this is a very useful intent &#8211; or would be if it worked. If your app needs to edit events there is no other way to do so than to create the necessary form yourself. Not what users have come to expect in Android. And not what we developers love on Android.</p>
<p>I have also filed a <a href="http://code.google.com/p/android/issues/detail?id=39402" title="Bug report for the terrible ACTION_EDIT intent support">bug report for this issue</a>. Please vote for this as well.</p>
<p>For this bug I have also found another fellow <a href="http://stackoverflow.com/questions/13072275/using-an-intent-to-edit-calendar-event-doesnt-work/" title="StackOverflow user complaining about not being able to edit an event using intents">StackOverflow user complaining about it</a>.</p>
<p><a name="intents_or_provider"></a></p>
<h3>Choosing between Intents and the CalendarContract provider</h3>
<p>When to use which approach depends on the needs of your app. The following bullet points list some pros and cons of each approach:</p>
<p><strong>Advantages of using intents</strong></p>
<ul class="multilist">
<li>You do not need to use permissions</li>
<li>The user of your app can decide which backend calendar to use for an event</li>
<li>familiar interface of the calendar app</li>
<li>common behavior in Android</li>
</ul>
<p><strong>Disadvantages of intents</strong></p>
<ul class="multilist">
<li>Only very few use cases are supported; an important one doesn&#8217;t work correctly</li>
<li>The consistency of the user experience within your app might get lost when opening the Calendar app.</li>
</ul>
<p><strong>Advantages of the content provider</strong></p>
<ul class="multilist">
<li>Significant changes of nearly all data possible</li>
<li>The only way for sync adapters to sync calendar related data</li>
<li>Might happen in the background without the user knowing much about it</li>
</ul>
<p><strong>Disadvantages of the content provider</strong></p>
<ul class="multilist">
<li>You have to add permissions to your app</li>
<li>If your app is not acting as a sync adapter you might not know which calendar id to use</li>
</ul>
<h3>Lessons learned</h3>
<p>You have ssen how to leverage intents to open up the Calendar view at a specific date, how to create new events and how to view existing ones. </p>
<p>You have also learned about the weak spots of the app&#8217;s intents: The incorrect back behavior for viewing events and the total mess of the edit event intent.</p>
<p>Thus you have to choose carefully which and if intents are the correct way for your app to deal with events.<br />
<img src="http://vg03.met.vgwort.de/na/549ec753dc574d478cfee2b5d323e2be" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/intents-of-androids-calendar-app/">What You Need to Know About the Intents of Android&#8217;s Calendar App</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/k98cU_0Glmc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/intents-of-androids-calendar-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/intents-of-androids-calendar-app/</feedburner:origLink></item>
		<item>
		<title>Half a Year of Blogging About Android Development</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/bDte0I5VkVI/</link>
		<comments>http://www.grokkingandroid.com/half-a-year-of-blogging/#comments</comments>
		<pubDate>Mon, 05 Nov 2012 06:47:18 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Blogging]]></category>
		<category><![CDATA[Statistics]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1893</guid>
		<description><![CDATA[<p>Exactly six months ago I published my &#8220;Hello World&#8221; post. And one week later my first post with serious content followed: Android: Checking Connectivity. Over the last half year I have continuously blogged and there were only two weeks in which I didn&#8217;t publish any posts. According my general feeling my blog progresses nicely. And [...]</p><p>The post <a href="http://www.grokkingandroid.com/half-a-year-of-blogging/">Half a Year of Blogging About Android Development</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">Exactly six months ago I published my &#8220;Hello World&#8221; post. And one week later my first post with serious content followed: <a href="http://www.grokkingandroid.com/android-checking-connectivity/" title="Android: Checking Connectivity">Android: Checking Connectivity</a>. </p>
<p>Over the last half year I have continuously blogged and there were only two weeks in which I didn&#8217;t publish any posts. According my general feeling my blog progresses nicely. And Google Analytics, G+ reshares and the number of G+ followers seem to confirm this. So, reason enough to celebrate <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I will share many stats with you, but if you do not care about numbers, please head directly to the sections about my plan to <a href="#change_hosting" title="Changing my hosting plan">change the current hosting solution</a>, my current unwillingness to offer a <a href="#responsive_design" title="Why no responsive design on Grokking Android">responsive version of this website</a> and for <a href="#whats_to_expect" title="What's to expect in the coming months">what&#8217;s to expect in the coming months</a>.</p>
<h3>Published posts</h3>
<p><strong>Total number</strong> of posts published: 32 (my Hello World not included)</p>
<p><strong>Tutorials</strong> published: 11</p>
<p><strong>Quick tips</strong> published: 2</p>
<p>Obviously I should expand on the Quick tip type <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Usage stats</h3>
<p><strong>Visitors</strong> per day: Roughly 300 (on weekends less, on posting days about twice as much) &#8211; steadily increasing</p>
<p><strong>Page views</strong> per day: Above 450</p>
<p><strong>Bounce rate</strong>: 78 per cent (I do not know whether this is good or bad &#8211; if you blog, please let me know how you do in this regard)</p>
<p>Ratio of <strong>new vs. returning</strong> visitors: 61 to 39 (I also do not know what to make of this number)</p>
<h3>Favorite topics</h3>
<p>The two top posts are my tutorial on <a href="http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/" title="Android Tutorial: BroadcastReceiver">BroadcastReceivers</a> and on <a href="http://www.grokkingandroid.com/android-tutorial-adding-search-to-your-apps/" title="Android Tutorial: Adding Search to Your Apps">making your app searchable</a>. Both get about 50 hits each daily.</p>
<p>The topic with the most hits so far is the <a href="http://www.grokkingandroid.com/useful-android-libraries-crouton/" title="Useful Android Libraries: Crouton">post about the library Crouton</a>. This post caused the biggest traffic spike yet and was really loved on the three social media sites I use (Google plus, Reddit and DZone). But as was to be expected this post is nowhere near the previous two on daily views.</p>
<p>Generally speaking tutorials are liked much more. This also is no big surprise since they tend to get more search traffic.</p>
<h3>Traffic sources</h3>
<p>Search: 50%<br />
Referrals: 30%<br />
Direct traffic: 16%<br />
Campaigns: 4%</p>
<p>Campaigns is an odd term. In my case this are visits originating from an RSS reader.</p>
<p>Referrals are all visits that come via a link from any other site. This can be social media sites, blog links, newsletters seen on the web or coming via a redirect and so on &#8211; unless it is a search result.</p>
<p>Search is obviously a visit via Google (Bing is nearly irrelevant with about half a per cent of all search traffic &#8211; yahoo is even worse). </p>
<p>Direct traffic are those people entering the domain directly into the browser. I can only assume that many people copy links before opening them, use Chrome&#8217;s incognito mode or hide the referrer in other ways. This number is definitely too high.</p>
<h3>Referring blogs</h3>
<p>A whopping ten per cent of all referrals (see above) come via <a href="https://plus.google.com/102272971619910906878/posts" title="Google plus profile of Juhani Lehtimäki">Juhani Lehtimäkis</a> blog <a href="http://www.androiduipatterns.com/">androiduipatterns.com</a>. That&#8217;s the next big traffic source directly after Reddit and Google plus. And these visitors are an especially interested crowd (low bounce rate, long duration of average visit). </p>
<p>So if anyone hasn&#8217;t been to his fantastic blog it&#8217;s about time to have a look. And since you&#8217;re in the right mood, <a href="http://eu.wiley.com/buy/9781118387283">why not buy his book &#8220;Smashing Android UI&#8221;</a>? Should be in every Android developers and designers bag anyway! And, no, I do not get any affiliate commissions for this link!</p>
<p>Other blogs are also doing well. Readers coming from blogs are on average much more interested than those coming via social networking sites. I think this is not surprising. A reader of another blog found the content of that blog interesting. And if the other blogger recommends yet another blog, chances are good that the reader likes this blog as well. </p>
<p>So if you haven&#8217;t done so, please have a look at my blogroll. These blogs are highly recommended by me and  all deal with Android development as well.</p>
<p>A big thank you to all those bloggers that have linked to my blog!</p>
<h3>Newsletters</h3>
<p>Apart from blogs another important source of readers of my blog are the newsletters <a href="http://androidweekly.net/">Android Weekly</a>, <a href="http://androiddevweekly.com/">#AndroidDev Weekly</a> and the newsletter of the French site <a href="http://www.frandroid.com/">FrAndroid</a>.</p>
<p>Bounce rates with newsletter visitors is higher than those of blog referrals but those readers do visit more pages on average than those coming via social media or search.</p>
<p>Also thanks to the newsletter editors for linking to my blog.</p>
<h3>Search</h3>
<p>As mentioned, for my blog Google is the only search engine that counts. It&#8217;s responsible for 50 per cent of all visits. Since people search for a specific topic, the bounce rate is quite high.</p>
<p>The top five queries where people see my site on a results page all have to do with BroadcastReceivers. Unsurprisingly my tutorial about BroadcastReceivers is where most readers end, when coming from Google.</p>
<p>Google Analytics uses two stats for search. The first is the report about the top 1000 daily queries. The second report is about all searches where my blog showed up in the results.</p>
<p>For the 1000 top queries (do not ask me about this report, I still do not get it) my click-through-rate is 5 per cent, for all Search Impressions in total my click-through-rate is 7.5 per cent. From what I have read these are quite decent numbers. But if some fellow bloggers could shed some light on these two reports, I would be thankful.</p>
<h3>Technology used by visitors</h3>
<p>Since this is a developers blog, you probably are interested in the technology people use. So let me share some stats.</p>
<h4>Mobile usage</h4>
<p>Nearly <strong>10 per cent</strong> of all visitors use mobile devices. Of all devices the Google Nexus is the top device. It accounts for more than three times the number of visitors than the next device &#8211; which is the iPad. The Nexus 7 is the third most used device and the fourth is one of the iPhones. So, there you have it. We Android users and devs are an open-minded crowd. </p>
<p>Still, Android usage is eight times that of iOS usage. No surprises here. But since Android offers a better variety of products, individual devices carry less weight.</p>
<p>The most interested readers are those using a Nexus 7 or a Galaxy Tab 10.1. They stay longer, come back more often and visit more pages. Other than for the Nexus 7 and Galaxy Tab 10.1 the bounce rate is quite high for mobile users.</p>
<h4>OS share</h4>
<p>Windows: 60%<br />
Mac: 17%<br />
Linux: 13%<br />
Android: 8%<br />
iOS: 1%</p>
<p>All others (Windows Phone, Symbian, Chrome OS, unidentifiable) account together for only 1 per cent.</p>
<h4>Browser share</h4>
<p>Chrome: 63%<br />
Firefox: 21%<br />
Safari: 4%<br />
IE: 4%<br />
Android Browser: 4%<br />
Opera: 3%</p>
<p>I especially like the numbers for the Internet Explorer. I have suffered under this browser way too long!</p>
<h3>Top Countries</h3>
<p>United States: 15% (California alone 4%)<br />
India: 11% (the city of Bangalore alone 3%)<br />
Germany: 8%<br />
France: 5%<br />
Great Britain: 5%</p>
<p>Even though more French people read my blog than Brits, London is way ahead of Paris. But still, for a blog written in English, this is a surprising result. I guess it has to do with the <a href="http://www.frandroid.com/">FrAndroid newsletter</a> mentioning this blog regularly.</p>
<p>Germany&#8217;s numbers probably are higher than Germany&#8217;s actual developer share simply because I am German myself and have many German G+ followers.</p>
<h3>Social media</h3>
<p>Now apart from search most people come to my blog via social media. In per cent of all visitors:</p>
<p>Reddit: 8%<br />
Google plus: 6%<br />
DZone: 3%<br />
StackOverflow: 1.4%<br />
Twitter: 0.5%</p>
<p>This is for the last month. The months before Reddit has had a much higher share of about three times that of Google plus. But my experience with Reddit has been quite mixed. Some posts go wild while others are duds or, worse, get downvoted rather quickly (which causes them to vanish from the Reddit site). I simply do not get Reddit.</p>
<p>The numbers for Twitter and Facebook are that low simply because I am no user of these sites. But I plan to use Twitter in the future. Why is that? Well, many interesting developers still do not use Google plus. <a href="http://commonsware.com/blog/" title="Mark Murphy's Android development blog">Mark Murphy</a> is probably the best-known of them, but not the only one. And of course, Twitter users love to follow and reshare links. So this should open my blog to new readers.</p>
<p>I really like DZone. I have found some nice blogs via their site. But it is not the biggest traffic engine. Anyway: If anyone at <a href="http://dzone.com" title="Link sharing site dzone">DZone</a> reads this: Please offer an API. For a social media site having no API is simply unbelievable. Apps that monitor social media coverage cannot deliver anything about DZone at the moment. That&#8217;s sad! And of course I would like to see an Android app for DZone. Yours truely would love to help create one <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><a name="change_hosting"></a></p>
<h3>Why I have to move my blog</h3>
<p>Right now I am using shared hosting. This was very easy to set up, but in the end it is nevertheless a pain. The shared hosting I use is way too slow to meet my expectations. Performance is simply not sufficient. Just imagine I had an even bigger reader base. Some of you probably would walk away &#8211; not willing to wait any longer for responses of my server.</p>
<p>Furthermore the package I am currently using, doesn&#8217;t offer the chance to use gzip compression. <a href="https://developers.google.com/speed/pagespeed/insights" title="Page Speed analysis for websites">Page Speed Score</a> is still 86 (of 100), which is okay. But that&#8217;s not how it feels.</p>
<p>All in all I think I have to switch to something better. Probably Dedicated hosting. Maybe a vhost server. I am evaluating options at the moment. But I will change the provider (or the package). So expect to see a significant improvement in performance pretty soon.</p>
<p><a name="responsive_design"></a></p>
<h3>No mobile version? No responsive design? Is this gonna change?</h3>
<p>To be honest: Mobiles are getting bigger at a fast rate and screen real estate has improved a lot. Thus I have no plans to do a lot in this regard. So while I am a big proponent of <a href="http://www.androiduipatterns.com/2011/11/design-patterns-for-responsive-android.html" title="Juhani Lehtimäki on responsive Android design">responsive</a> <a href="http://www.pushing-pixels.org/2012/03/16/responsive-mobile-design-on-android-from-view-pager-to-action-bar-tabs.html" title="Kirill Grouchnikov on responsive Android design">design</a> for Android apps, I do not consider it necessary for this blog. Of course, if a lot of you would post in the comments that you miss this, I would reconsider. It&#8217;s up to you!</p>
<p>What I will change though, is how a printout looks. I often print blog posts of others if I like the content and expect to refer to the post more than once. Or for posts that look important but are pretty longish. But my blog simply doesn&#8217;t look good when printed. Which is not okay and which I plan to correct. You shouldn&#8217;t have to wait too long.</p>
<p><a name="whats_to_expect"></a></p>
<h3>What&#8217;s to expect in coming months</h3>
<p>I already started my series about libraries with my post about <a href="https://github.com/keyboardsurfer/Crouton" title="The github page of the library Crouton">Crouton</a>. I intend to make this a regular post style, appearing once a month. The next one will be about <a href="https://github.com/greenrobot/EventBus" title="Github page of the library EventBus">EventBus</a>.</p>
<p>Furthermore <strong>book reviews</strong> are in the pipeline. Probably one review per month. It depends on what books get published and how much time I have to read them. Actually a book review will be on of my next posts. Disclaimer: I will add Amazon affiliate links. Just ignore them if you don&#8217;t like this kind of stuff. But if you want to support my caffeine-level, follow these links if you intend to buy the books anyway <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>I also plan on doing some <strong>interviews</strong> with fellow developers, may be even some Googlers and &#8211; if possible &#8211; Android-savvy designers as well. This is not gonna happen this year but hopefully at the beginning of the next year.</p>
<p>I might also occasionally have a look at <strong>other blogs</strong>. Maybe coupled together with an interview of the blogger. I like this idea, but I am not sure if this adds value. If you would like to see this let me know.</p>
<p>Apart from this, I simply will continue what I did the last months. Complete with occasional bug reports, rants, tutorials, in-depth posts and short quick tips.</p>
<p>Thanks to all of you for your support so far!<br />
<img src="http://vg03.met.vgwort.de/na/620cf9452d6147199878e49f42a69a9a" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/half-a-year-of-blogging/">Half a Year of Blogging About Android Development</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/bDte0I5VkVI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/half-a-year-of-blogging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/half-a-year-of-blogging/</feedburner:origLink></item>
		<item>
		<title>iCal’s Recurrence Rule and Duration Formats</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/Tfkl7eYir70/</link>
		<comments>http://www.grokkingandroid.com/recurrence-rule-and-duration-formats/#comments</comments>
		<pubDate>Wed, 31 Oct 2012 06:45:28 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[CalendarContract]]></category>
		<category><![CDATA[Duration]]></category>
		<category><![CDATA[Recurrence Rule]]></category>
		<category><![CDATA[RFC 5545]]></category>
		<category><![CDATA[RRULE]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1900</guid>
		<description><![CDATA[<p>If you create repeating events in Android using the CalendarContract content provider, the fields for recurrence rules (RRULE) and durations (DURATION) follow the iCal format (RFC 5545). Here I cover the basics of these formats to create valid field values. This post is somewhat of an oddity on this blog as most of its content [...]</p><p>The post <a href="http://www.grokkingandroid.com/recurrence-rule-and-duration-formats/">iCal&#8217;s Recurrence Rule and Duration Formats</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">If you create repeating events in Android <a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/" title="Android’s CalendarContract Content Provider">using the CalendarContract content provider</a>, the fields for recurrence rules (RRULE) and durations (DURATION) follow the <a href="http://tools.ietf.org/html/rfc5545" title="Request for comments for the iCalendar format">iCal format</a> (RFC 5545). Here I cover the basics of these formats to create valid field values. </p>
<p>This post is somewhat of an oddity on this blog as most of its content is not Android specific.</p>
<h3>Recurrence Rule</h3>
<p>The recurrence rule is used in Android whenever you deal with events of the <a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/" title="Android’s CalendarContract Content Provider">CalendarContract content provider</a>. The event table has the column <a href="https://developer.android.com/reference/android/provider/CalendarContract.EventsColumns.html#RRULE" title="Documentation of the RRULE column of Android's event table">RRULE</a> that takes the recurrence rule as a String value.</p>
<p>This rule is made up of several components that are separated by semicolons.</p>
<p>As the first element every recurrence rule must define the frequency. It covers all intervals from seconds to years. You use the <code>FREQ</code> qualifier to do so, e.g. <code>FREQ=DAILY</code>. </p>
<p>All other elements are optional. To limit the number of events you can specify the interval, the number of occurrences or the enddate. A <code>FREQ=WEEKLY</code> and a <code>INTERVAL=2</code> would result in a biweekly event. The number of occurrences is given by the <code>COUNT=x</code> qualifier. And finally an enddate can be given using the element <code>UNTIL=yyyymmdd</code>.</p>
<p>It is also possible for you to select certain elements. E.g. a <code>BYDAY=TU</code> would select Tuesdays, a <code>BYMONTH=5</code> would select May.</p>
<p>There is another obscure but interesting element: <code>BYSETPOS</code>. This is used to denote one element in a set of elements. A <code>BYSETPOS=1</code> selects the first element &#8211; a <code>BYSETPOS=-1</code> selects the last element. You have to use it together with another <code>BYxyz</code> element.</p>
<h3>Some RRULE samples</h3>
<p>As I have already mentioned in my <a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/" title="Android’s CalendarContract Content Provider">post about the CalendarContract content provider</a> the in and outs of the recurrence rule are pretty tedious and unnecessary complex. Most often you do not need to know all the details. The following samples should help you get to grips with most of the rules.</p>
<ul style="padding-left: 1.5em">
<li><code>FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR;COUNT=15</code><br />
This rule describes an event that takes place on every weekday (BYDAY) for the next 15 weekdays (COUNT).</li>
<li><code>FREQ=YEARLY;BYDAY=-1SU;BYMONTH=3;COUNT=2</code><br />
Last Sunday (negative value for BYDAY) in March for every year. That&#8217;s the day the summer time begins in the EU.</li>
<li><code>FREQ=YEARLY;BYDAY=2SU;BYMONTH=5;COUNT=3</code><br />
Mother&#8217;s day. This rule describes a yearly that takes place on the second Sunday (BYDAY) in May (BYMONTH).</li>
<li><code>FREQ=YEARLY;INTERVAL=4;BYMONTH=11;BYDAY=TU;BYMONTHDAY=2,3,4,5,6,7,8</code><br />
US election day. Every fourth year (INTERVAL) on the first Tuesday (BYDAY) after a Monday (BYMONTHDAY ensures that) in November (BYMONTH).</li>
<li><code>FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=1;UNTIL=20131231</code><br />
All first weekdays (BYDAY in combination with BYSETPOS) of the month until the end of 2013 (UNTIL).
</ul>
<p>If you are really into this, have a look at this enormous <a href="http://recurrance.sourceforge.net/" title="Recurrance project page listing many recurrence rules">list of recurrence rules samples</a>.</p>
<h3>Duration</h3>
<p>The format of the duration element is much easier to grasp. It takes only one page of the spec compared to seven for the recurrence rule.</p>
<p>So let&#8217;s me show you one duration value and explain the format with this example as a basis:</p>
<p><code>+P5W3D</code></p>
<p>The first thing, you will notice is the plus sign. Surprisingly durations can have a positive or negative value. The positive value is the default and thus the &#8220;+&#8221; sign can be omitted. Negative durations can be used to trigger alarms before the event starts. But Android uses a fixed time for this so negative values aren&#8217;t used on Android.</p>
<p>The next element after the sign is the &#8220;P&#8221; which is a fixed constant.</p>
<p>And lastly follows a non-separated string of time quantifiers that all are added up to form the duration.</p>
<p>So the sample given above is for five weeks and three days. What&#8217;s odd with durations in the spec is that the biggest period is weeks. It&#8217;s not possible to specify months or years. </p>
<table>
<caption>Time qualifiers</caption>
<tr>
<th>Qualifier</th>
<th>Meaning</th>
</tr>
<tr>
<td>W</td>
<td>Week</td>
</tr>
<tr>
<td>D</td>
<td>Day</td>
</tr>
<tr>
<td>H</td>
<td>Hour</td>
</tr>
<tr>
<td>M</td>
<td>Minute</td>
</tr>
<tr>
<td>S</td>
<td>Second</td>
</tr>
</table>
<p>Since Android doesn&#8217;t use durations for the length of an event, durations usually consist of weeks and days only.</p>
<h3>Summary</h3>
<p>I have covered the basics of the RRULE and DURATION elements of CalendarContracts event table. Since these rules are in a somewhat obscure format I have given you some samples of how they are created. This should get you started whenever you need to create recurring events in your code.<br />
<img src="http://vg03.met.vgwort.de/na/f62e82ee0b304a3a9f52bd3a23742aa8" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/recurrence-rule-and-duration-formats/">iCal&#8217;s Recurrence Rule and Duration Formats</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/Tfkl7eYir70" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/recurrence-rule-and-duration-formats/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/recurrence-rule-and-duration-formats/</feedburner:origLink></item>
		<item>
		<title>Android’s CalendarContract Content Provider</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/b1vcTmUnMDU/</link>
		<comments>http://www.grokkingandroid.com/androids-calendarcontract-provider/#comments</comments>
		<pubDate>Thu, 18 Oct 2012 05:48:21 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Attendees]]></category>
		<category><![CDATA[Calendar]]></category>
		<category><![CDATA[CalendarContract]]></category>
		<category><![CDATA[Event Instances]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[Reminders]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1801</guid>
		<description><![CDATA[<p>Android developers have been longing for an official Calendar app and content provider since Android has been released. With the release of Ice Cream Sandwich Google has finally added this feature to our tools list. Now we developers can use the Calendar app from within our Activities using Intents or we can access the data [...]</p><p>The post <a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/">Android&#8217;s CalendarContract Content Provider</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">Android developers have been longing for an official Calendar app and content provider since Android has been released. With the release of Ice Cream Sandwich Google has finally added this feature to our tools list. Now we developers can use the Calendar app from within our Activities using Intents or we can access the data by making use of the new <a href="https://developer.android.com/reference/android/provider/CalendarContract.html" title="Documentation of Android's CalendarContract">CalendarContract</a> content provider. </p>
<h3>CalendarContracts entities</h3>
<p>Before I explain how to use the calendar I first present the calendar&#8217;s data model. It consists of calendars, events, event instances, event attendees and reminders.</p>
<p>First we obviously have <strong>calendars</strong>. The plural is no accident, because each user can manage multiple calendars on her device. For example her personal calendar, her work calendar, a calendar of her colleague and one for her sports team. Android uses colors to distinguish between different calendars in the Calendar app:</p>
<p><div id="attachment_1833" class="wp-caption alignleft" style="width: 178px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/events_of_multiple_accounts_final.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/events_of_multiple_accounts_final-168x300.png" alt="Events of multiple accounts" width="168" height="300" class="size-medium wp-image-1833" /></a><p class="wp-caption-text">Events of multiple accounts</p></div><br />
<div id="attachment_1831" class="wp-caption alignleft" style="width: 178px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/account_selection_when_adding_an_event_final.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/account_selection_when_adding_an_event_final-168x300.png" alt="Account selection when adding an event" width="168" height="300" class="size-medium wp-image-1831" /></a><p class="wp-caption-text">Account selection when adding an event</p></div></p>
<p style="clear: both">For each calendar you can have multiple <strong>events</strong>. But each event belongs to exactly one calendar only. If the event is visible twice (e.g. in the private and in the business account of the user), the event is stored twice, each belonging to their respective calendars.</p>
<p>Many events are recurring. So in addition to events there are also <strong>event instances</strong>. An instance represents the specific event that takes place at just this one point in time. For a single event Android creates one instances entry, for recurring events Android creates as many instance entries as there are occurrences of this event.</p>
<p>Events can of course have multiple <strong>attendees</strong> as well as multiple <strong>reminders</strong>. </p>
<p>Furthermore the data model contains some helper tables that are only relevant for sync adapters. I don&#8217;t deal with these in this blog post.</p>
<p>What&#8217;s weird is that attendees belong to the event and not to the event instances. What happens if users want to cancel one instance of a recurring event? What if they want to add an attendee for just one event? For example changing the speaker of a recurring User Group talk? The solution chosen here is that another entry is added to the events table with the field <code>Events.ORIGINAL_ID</code> referring to the id of the base event. This is also the case for event instances for which only the time has changed &#8211; even though this information is already part of the instances table.</p>
<h3>What are sync adapters</h3>
<p><strong>Sync adapters</strong> sync data of specific accounts to a backend. Sync adapters are usually an integral part of the app, that needs them. Thus users usually do not install them on their own.</p>
<p>In this blog post I do not deal in detail with sync adapters. But you should know that sync adapters possess more privileges and can access more tables and fields than normal apps. The most important privilege  is that only sync adapters can create calendar accounts.</p>
<p>Of course a sync adapter has these privileges only for its account type. An adapter cannot mess with the privileged data of another account.</p>
<p>Sync adapters don&#8217;t deal with calendar data alone. They also sync contact data or any data specific to your app that has to be synchronized between the device and a backend.</p>
<p>You can find a list of available sync adapters in your Settings app in the section &#8220;Accounts&#8221;:</p>
<div id="attachment_1834" class="wp-caption alignnone" style="width: 178px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/sync_adapters_in_the_settings_app_final.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/sync_adapters_in_the_settings_app_final-168x300.png" alt="Sync adapters in the settings app" width="168" height="300" class="size-medium wp-image-1834" /></a><p class="wp-caption-text">Sync adapters in the settings app</p></div>
<h3>Using your Google Calendar within the emulator</h3>
<p>To test your calendar-related code within the emulator, you first need to have a calendar. The best is to sync with an existing calendar of yours &#8211; and the easiest way to do this, is to sync with your Google calendar.</p>
<p>I have written another post that explains <a href="http://www.grokkingandroid.com/using-a-google-account-in-the-emulator/" title="Using your Google Account in the Android Emulator">how to sync with your Google Calendar</a>.</p>
<h3>The Calendar content provider</h3>
<p>To use the Calendar content provider you need to declare the necessary permissions within your manifest file first:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;uses-permission 
      android:name=&quot;android.permission.READ_CALENDAR&quot;/&gt;
&lt;uses-permission 
      android:name=&quot;android.permission.WRITE_CALENDAR&quot;/&gt;
</pre>
<p>Keep in mind that the Calendar is part of the official API only from Ice Cream Sandwich onwards. The constants, defined in <code>CalendarContract</code> and its many inner classes are not available prior to API version 14. All code samples shown here need an API-level of 14 or higher as build target and the value for the <code>android:minSdkVersion</code> attribute of the <code>&lt;uses-sdk&gt;</code> element in the manifest file.</p>
<p>The content provider itself probably is available on older versions &#8211; though you cannot rely on this. For more on this see the section <a href="#pre_ics" title="Section on using the Calendar ContentProvider with older API levels">Calendar-usage before Ice Cream Sandwich</a>.</p>
<h3>Accessing calendars</h3>
<p>If your app doesn&#8217;t act as a sync adapter chances are that you never have to deal with the calendars itself. Other than query for the correct id that is. The thing you are most likely to do is add, delete or change events. But for this you need to know to which calendar to add the event.</p>
<p>So let&#8217;s start by reading all calendars that are available on a device:</p>
<pre class="brush: java; title: ; notranslate">
String[] projection = 
      new String[]{
            Calendars._ID, 
            Calendars.NAME, 
            Calendars.ACCOUNT_NAME, 
            Calendars.ACCOUNT_TYPE};
Cursor calCursor = 
      getContentResolver().
            query(Calendars.CONTENT_URI, 
                  projection, 
                  Calendars.VISIBLE + &quot; = 1&quot;, 
                  null, 
                  Calendars._ID + &quot; ASC&quot;);
if (calCursor.moveToFirst()) {
   do {
      long id = calCursor.getLong(0);
      String displayName = calCursor.getString(1);
      // ...
   } while (calCursor.moveToNext());
}
</pre>
<p>Of course you can also change calendars using the content provider. But here it starts getting tricky. That&#8217;s because apart from reading data, the access to calendars is limited. Sync adapters can do pretty much anything with calendars they own, but normal apps cannot do much at all. Of course they cannot delete calendars, but they also cannot create calendars. They only can change some trivial values like the name of the calendar.</p>
<p>There is one exception to this rule: You can create local calendars that do not get synced. So the following code shows how to create a local calendar which you will use later on for manipulating events:</p>
<pre class="brush: java; title: ; notranslate">
ContentValues values = new ContentValues();
values.put(
      Calendars.ACCOUNT_NAME, 
      MY_ACCOUNT_NAME);
values.put(
      Calendars.ACCOUNT_TYPE, 
      CalendarContract.ACCOUNT_TYPE_LOCAL);
values.put(
      Calendars.NAME, 
      &quot;GrokkingAndroid Calendar&quot;);
values.put(
      Calendars.CALENDAR_DISPLAY_NAME, 
      &quot;GrokkingAndroid Calendar&quot;);
values.put(
      Calendars.CALENDAR_COLOR, 
      0xffff0000);
values.put(
      Calendars.CALENDAR_ACCESS_LEVEL, 
      Calendars.CAL_ACCESS_OWNER);
values.put(
      Calendars.OWNER_ACCOUNT, 
      &quot;some.account@googlemail.com&quot;);
values.put(
      Calendars.CALENDAR_TIME_ZONE, 
      &quot;Europe/Berlin&quot;);
Uri.Builder builder = 
      CalendarContract.Calendars.CONTENT_URI.buildUpon(); 
builder.appendQueryParameter(
      Calendars.ACCOUNT_NAME, 
      &quot;com.grokkingandroid&quot;);
builder.appendQueryParameter(
      Calendars.ACCOUNT_TYPE, 
      CalendarContract.ACCOUNT_TYPE_LOCAL);
builder.appendQueryParameter(
      CalendarContract.CALLER_IS_SYNCADAPTER, 
      &quot;true&quot;);
Uri uri = 
      getContentResolver().insert(builder.build(), values);
</pre>
<p>Now this code needs some explaining. First of all I create a <code>ContentValues</code> object that represents the values we want to add. <a href="http://www.grokkingandroid.com/android-tutorial-using-content-providers/" title="Android Tutorial: Using Content Providers">This is the normal way to add data to a content provider.</a> Here I add a name, the color for displaying this calendar&#8217;s data, the account it belongs to and its access rights. I also add a default time zone.</p>
<p>But what is not normal with the code shown above are the additional query parameters the calendar provider expects. These indicate to the provider that this code acts as a sync adapter and for which account type and account name it does this. Here the account type is <code>ACCOUNT_TYPE_LOCAL</code> &#8211; so this calendar will not be synced. Any other type would have to be accompanied by a full-fledged sync adapter.</p>
<h3>Adding events using the content provider</h3>
<p>While you cannot do anything without having at least one calendar first, you most likely want to create, change or delete events.</p>
<p>Since all events belong to a calendar account, I use this helper method to get the calendar id for the local calendar created in the previous section:</p>
<pre class="brush: java; title: ; notranslate">
private long getCalendarId() { 
   String[] projection = new String[]{Calendars._ID}; 
   String selection = 
         Calendars.ACCOUNT_NAME + 
         &quot; = ? &quot; + 
         Calendars.ACCOUNT_TYPE + 
         &quot; = ? &quot;; 
   // use the same values as above:
   String[] selArgs = 
         new String[]{
               MY_ACCOUNT_NAME, 
               CalendarContract.ACCOUNT_TYPE_LOCAL}; 
   Cursor cursor = 
         getContentResolver().
               query(
                  Calendars.CONTENT_URI, 
                  projection, 
                  selection, 
                  selArgs, 
                  null); 
   if (cursor.moveToFirst()) { 
      return cursor.getLong(0); 
   } 
   return -1; 
} 
</pre>
<p>In addition to this calendar id you also have to add at least the following fields in order to create events:</p>
<ul>
<li>Each event must have a time zone &#8211; even if the calendar account has a default time zone anyway</li>
<li>An event must have a start date</li>
<li>The event must either have an end date or a duration, but must not have both at the same time.</li>
</ul>
<p>Actually the last rule is very strange. Duration in this case is not the duration of a single event. Instead it is the time span used to determine the last event of recurring events. So for single events a duration makes no sense at all. Also I consider it odd that you have to include these fields even for all-day events. But well, it&#8217;s not too hard to add them. So just be warned.</p>
<p>The following snippet shows how to add an all-day event:</p>
<pre class="brush: java; title: ; notranslate">
long calId = getCalendarId();
if (calId == -1) {
   // no calendar account; react meaningfully
   return;
}
Calendar cal = new GregorianCalendar(2012, 11, 14);
cal.setTimeZone(TimeZone.getTimeZone(&quot;UTC&quot;));
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long start = cal.getTimeInMillis();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, start);
values.put(Events.DTEND, start);
values.put(Events.RRULE, 
      &quot;FREQ=DAILY;COUNT=20;BYDAY=MO,TU,WE,TH,FR;WKST=MO&quot;);
values.put(Events.TITLE, &quot;Some title&quot;);
values.put(Events.EVENT_LOCATION, &quot;Münster&quot;);
values.put(Events.CALENDAR_ID, calId);
values.put(Events.EVENT_TIMEZONE, &quot;Europe/Berlin&quot;);
values.put(Events.DESCRIPTION, 
      &quot;The agenda or some description of the event&quot;);
// reasonable defaults exist:
values.put(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE);
values.put(Events.SELF_ATTENDEE_STATUS,
      Events.STATUS_CONFIRMED);
values.put(Events.ALL_DAY, 1);
values.put(Events.ORGANIZER, &quot;some.mail@some.address.com&quot;);
values.put(Events.GUESTS_CAN_INVITE_OTHERS, 1);
values.put(Events.GUESTS_CAN_MODIFY, 1);
values.put(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);
Uri uri = 
      getContentResolver().
            insert(Events.CONTENT_URI, values);
long eventId = new Long(uri.getLastPathSegment());
</pre>
<p>If you add an event in this way, you have not yet created any alarms or set any attendes. You will have to do so in an extra step and you have to use the id of this event to do so. I will show how to add attendes and alarms later on. In preparation for this I have already extracted the id of the event. </p>
<p>For a lot of fields reasonable default would be inserted if you left them out. The code shown here uses them anyway so that you know what you can do and how to do it.</p>
<p>Since the underlying datastore doesn&#8217;t suppport boolean values, the provider uses <code>1</code> for true and <code>0</code> for false. A common practise in Android when SQLite is involved. As you can see, I&#8217;ve set the values of <code>ALL_DAY</code>, <code>GUESTS_CAN_INVITE_OTHERS</code> and <code>GUESTS_CAN_MODIFY</code> to true.</p>
<p>The value of the <code>rrule</code> field looks a bit strange. First the name: &#8220;rrule&#8221; is short for recurrence rule and defines how recurring events should be inserted. In this case the rule states that the event should be repeated on every weekday for the next twenty days. The values for the recurrence rule as well as for the duration have to be given in an <a href="http://tools.ietf.org/html/rfc5545" title="RFC 5545 document">RFC 5545</a> compliant format. </p>
<p>Alas, the RFC formats for the duration and the recurrence rule are less than obvious. Believe me: You do not want to know the detailed rules for the recurrence format. This part of the specification alone is eight pages long and <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/com/android/calendarcommon/EventRecurrence.java?av=f" title="Source code of Android's class EventRecurrence">Google&#8217;s class EventRecurrence</a>, representing and parsing those rules, is about 900 lines long. Explaining these formats is way beyond the scope of this blog post!</p>
<h3>Reading, updating and deleting events</h3>
<p>Getting more information about an event is pretty simple. You just need the <code>Events.CONTENT_URI</code> and the appropriate selection. If &#8211; for example &#8211; you know the event id you can access the event like this:</p>
<pre class="brush: java; title: ; notranslate">
long selectedEventId = // the event-id;
String[] proj = 
      new String[]{
            Events._ID, 
            Events.DTSTART, 
            Events.DTEND, 
            Events.RRULE, 
            Events.TITLE};
Cursor cursor = 
      getContentResolver().
            query(
               Events.CONTENT_URI, 
               proj, 
               Events._ID + &quot; = ? &quot;, 
               new String[]{Long.toString(selectedEventId)}, 
               null);
if (cursor.moveToFirst()) {
   // read event data
}
</pre>
<p>Sometimes you want to find out more about events of the device owner. E.g. a concert planning app could have a look at the users calendar and check that she is free that evening. That&#8217;s what the next code snippet does. It checks if any event instances exist between a starting point and an ending point in time.</p>
<pre class="brush: java; title: ; notranslate">
long begin = // starting time in milliseconds
long end = // ending time in milliseconds
String[] proj = 
      new String[]{
            Instances._ID, 
            Instances.BEGIN, 
            Instances.END, 
            Instances.EVENT_ID};
Cursor cursor = 
      Instances.query(getContentResolver(), proj, begin, end);
if (cursor.getCount() &gt; 0) {
   // deal with conflict
}
</pre>
<p>Updating and deleting events are pretty easy tasks to accomplish. To delete you simply need the id of the event you want to delete:</p>
<pre class="brush: java; title: ; notranslate">
String[] selArgs = 
      new String[]{Long.toString(selectedEventId)};
int deleted = 
      getContentResolver().
            delete(
               Events.CONTENT_URI, 
               Events._ID + &quot; =? &quot;, 
               selArgs);
</pre>
<p>For updating you need a <code>ContentValues</code> object containing those elements that you want to change:</p>
<pre class="brush: java; title: ; notranslate">
ContentValues values = new ContentValues();
values.put(Events.TITLE, &quot;Some new title&quot;);
values.put(Events.EVENT_LOCATION, &quot;A new location&quot;);
String[] selArgs = 
      new String[]{Long.toString(selectedEventId)};
int updated = 
      getContentResolver().
            update(
               Events.CONTENT_URI, 
               values, 
               Events._ID + &quot; =? &quot;, 
               selArgs);
</pre>
<h3>Adding attendees and alarms</h3>
<p>As I&#8217;ve mentioned above, inserting an event is not enough. You probably want to add attendees and alarms.</p>
<p>Both tables reference the <code>events</code> table by using the field <code>EVENT_ID</code> with the appropriate id. </p>
<p>As usual you need a <code>ContentValues</code> object to get this done:</p>
<pre class="brush: java; title: ; notranslate">
// adding an attendee:
values.clear();
values.put(Attendees.EVENT_ID, eventId);
values.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
values.put(Attendees.ATTENDEE_NAME, &quot;Douglas Adams&quot;);
values.put(Attendees.ATTENDEE_EMAIL, &quot;d.adams@zaphod-b.com&quot;);
getContentResolver().insert(Attendees.CONTENT_URI, values);
// adding a reminder:
values.clear();
values.put(Reminders.EVENT_ID, eventId);
values.put(Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(Reminders.MINUTES, 30);
getContentResolver().insert(Reminders.CONTENT_URI, values); 
</pre>
<p>As explained in another post, you probably would want to <a href="http://www.grokkingandroid.com/better-performance-with-contentprovideroperation/" title="Android: Better Performance with ContentProviderOperation">use the class ContentProviderOperation to do a batch operation</a>. But to keep the sample code as easy to read as possible, I have chosen the simpler approach shown above.</p>
<h3>Other data</h3>
<p>Reading, updating or deleting any of the other elements is pretty much like the sample code for events.  Only the <code>CONTENT_URI</code> and the possible columns are different. Those are well documented in the <a href="http://developer.android.com/reference/android/provider/CalendarContract.html" title="API documentation for the CalendarContract-class">CalendarContracts API</a>.</p>
<p>If you want to insert data into other tables you have to be careful though: Only SyncAdapters are allowed to add records to <code>Colors</code>, <code>SyncState</code> or <code>ExtendedProperties</code>. If your ignore this restriction your code will result in an <code>IllegalArgumentException</code> at runtime.</p>
<p>Furthermore <strong>you are not allowed to manipulate data of the instances table &#8211; even if you are a sync adapter</strong>. Android will take care of instances on its own whenever an event gets added, deleted or modified. The only thing you are allowed to do with instances is to query them.</p>
<p><a name="pre_ics"></a></p>
<h3>What about older Android devices?</h3>
<p>As mentioned, the Calendar app and the content provider have been introduced with Ice Cream Sandwich. Even though the market share of 4.x devices increases steadily, most devices out there are still 2.x devices. Does anything comparable exist for them as well?</p>
<p>Well, kind of. Of course nothing official existed prior to ICS and the emulator images for older devices didn&#8217;t and still don&#8217;t have a calendar app. But nearly every device has. Even the sources existed &#8211; though marked with the <code>@hide</code> annotation, so that you can&#8217;t use the classes (e.g. the final static fields for the columns) in your code. </p>
<p>This is a sign that Google regarded the code as yet not ready for prime time. Well, rightly so, since it is still buggy in places &#8211; though mostly in the app, as I will explain in my next post.</p>
<p>If you take a look at the <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.7_r1/android/provider/Calendar.java?av=f" title="Source code of the Calendar content provider of Android 2.3.7">Calendar content provider of Android 2.3.7 at grepcode</a> you can see that the data model is pretty similar to the one of the current provider. If you diff older code and newer code you will notice how close both are. Most changes deal with the new table <code>colors</code>. Obviously any code that relies on this table is doomed to fail on older devices.</p>
<p>So can you simply act as if the provider had been around for ages? Well, no. You can&#8217;t! The code used in this tutorial would result in <code>NoClassDefFoundErrors</code>.</p>
<p>But, and this is the good news, the old provider can still be used for most tasks without too much changes. For this to work you mostly have to exchange all constants with their actual values.</p>
<p>Be very careful if you do so! You have to test vigorously and you risk running into problems if the values (column names, content uris and so on) should ever change. And be prepared for content providers that do not match this data model &#8211; you simply cannot rely on it. Try to isolate the critical parts as much as possible.</p>
<p>If you want to know more about accessing calendars prior to ICS, you should read the blog <a href="http://jimblackler.net/blog/?p=151" title="Jim Blackler's post about Android's calendar provider before ICS">post of Jim Blackler about the old internal calendar database</a>.</p>
<h3>Wrapping up</h3>
<p>In this part of the tutorial I have shown you how to use Android’s CalendarContract content provider.</p>
<p>Using the content provider you can add events or get information about the user&#8217;s events and you can also check for conflicting dates.</p>
<p>To make full use of the content provider you have to be a sync adapter. But using a device local calendar account you can also deal with calendars in many ways.</p>
<p>In the next part of this tutorial I am going to cover the Intents that are provided by the Calendar app. For some use cases they might be the better choice &#8211; but of course you have much more flexibility by using the content provider.<br />
<img src="http://vg03.met.vgwort.de/na/edf714fb9ab848fca003851e11971a35" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/androids-calendarcontract-provider/">Android&#8217;s CalendarContract Content Provider</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/b1vcTmUnMDU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/androids-calendarcontract-provider/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/androids-calendarcontract-provider/</feedburner:origLink></item>
		<item>
		<title>Useful Android Libraries: Crouton</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/pxWvNRBLjEk/</link>
		<comments>http://www.grokkingandroid.com/useful-android-libraries-crouton/#comments</comments>
		<pubDate>Thu, 11 Oct 2012 13:50:39 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Crouton]]></category>
		<category><![CDATA[Libraries]]></category>
		<category><![CDATA[Style.Builder]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1760</guid>
		<description><![CDATA[<p>One way to notify users is to use Toasts. But Toasts have the problem that they might pop up in totally unrelated contexts. They are displayed for a defined duration on the screen no matter what the user does. The user might even have changed the app, with the result, that your Toast simply confuses [...]</p><p>The post <a href="http://www.grokkingandroid.com/useful-android-libraries-crouton/">Useful Android Libraries: Crouton</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">One way to notify users is to use Toasts. But Toasts have the problem that they might pop up in totally unrelated contexts. They are displayed for a defined duration on the screen no matter what the user does. The user might even have changed the app, with the result, that your Toast simply confuses the user.</p>
<p><a href="https://plus.google.com/118417777153109946393" title="Google+ profile of Cyril Mottier">Cyril Mottier</a> outlined the problems with Toasts in his blog <a href="http://android.cyrilmottier.com/?p=773" title="Cyril mottier's blog about Prixing's in-layout notifications">post about Prixing&#8217;s notification mechanism</a>. He also outlined the solution he has chosen for Prixing &#8211; and why it is better.</p>
<h3>What are Croutons?</h3>
<p>His idea is to show in-app notifications (not to be confused with Android&#8217;s persistent notifications) at a fixed place of the Activity to which the notification is relevant. This way the context of the notification is always correct. Furthermore he used different styles for different types of notifications. </p>
<p>Since he couldn&#8217;t release any source code, <a href="https://plus.google.com/117509657298845443204" title="Benjamin Weiss' profile on Google plus">Benjamin Weiss</a> took this concept and created the <a href="https://github.com/keyboardsurfer/Crouton" title="Crouton library at github">open source library Crouton</a>, hosted at Github.</p>
<p>To give you a better idea of what a Crouton looks like, let me show you these two screenshots:</p>
<p><div id="attachment_1792" class="wp-caption alignleft" style="width: 178px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/confirmation_crouton1.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/confirmation_crouton1-168x300.png" alt="A confirmation Crouton" width="168" height="300" class="size-medium wp-image-1792" /></a><p class="wp-caption-text">A confirmation Crouton</p></div><br />
<div id="attachment_1777" class="wp-caption alignleft" style="width: 178px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/alert_crouton.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/alert_crouton-168x300.png" alt="An alert Crouton" width="168" height="300" class="size-medium wp-image-1777" /></a><p class="wp-caption-text">An alert Crouton</p></div></p>
<p style="clear:both">These screenshots show a confirmation and an alert Crouton. Another style you could use would be the info style, which uses the Holo blue. As you can see a Crouton appears at the top of the screen and is displayed as an overlay atop of the current Activity. The content of the view remains exactly as it is.</p>
<h3>How to use the library</h3>
<p>Before you can use the library, you first have to get it. No binaries are available, but since the project is hosted at github, you can easily clone the project:</p>
<pre class="brush: plain; title: ; notranslate">
git clone git://github.com/keyboardsurfer/Crouton.git
</pre>
<p>If you are using maven, follow the instructions on the <a href="https://github.com/keyboardsurfer/Crouton" title="The Crouton project page on github">Crouton project page</a>.</p>
<p>If you use Eclipse you simply add the library folder as an existing Android project to your workspace. Since no Eclipse-specific files are included in the sources, you have to change the &#8220;Project Build Target&#8221; in the Android tab of the Eclipse project  to at least 4.0 (API-Level 14).</p>
<p>You also have to check the &#8220;Is Library&#8221; checkbox:</p>
<div id="attachment_1786" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/project_settings_eclipse.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/project_settings_eclipse-300x231.png" alt="Project settings in Eclipse for the Crouton library project" width="300" height="231" class="size-medium wp-image-1786" /></a><p class="wp-caption-text">Project settings in Eclipse for the Crouton library project</p></div>
<p>Next you have to include the Crouton library to the project that should use this project. You do this in the same dialog as shown above by selecting the &#8220;Add&#8221; button.</p>
<p>After these initial steps you can use <code>Croutons</code> as easily as <code>Toasts</code>. The methods to use are as close to those of Toasts as possible. You have two static <code>makeText()</code> methods as well as the <code>show()</code> method:</p>
<pre class="brush: java; title: ; notranslate">
Crouton.makeText(
         this, 
         getString(R.string.crouton_message), 
         Style.CONFIRM)
      .show();
</pre>
<p>From using <code>Toasts</code> we all now how easy it is to forget the <code>show()</code> method call. Gladly the Crouton library adds the convenience method <code>showText()</code> to skip the extra step necessary with <code>Toasts</code>:</p>
<pre class="brush: java; title: ; notranslate">
Crouton.showText(
      this, 
      getString(R.string.crouton_message2), 
      Style.CONFIRM);
</pre>
<p>The library queues Croutons and presents them subsequentially. But, please, keep the amount of notifications to a minimum. Otherwise you quickly will annoy your users.</p>
<p>You can also use custom styles. In this case you have to use the <code>Style.Builder</code> class, set the desired properties and build a style. As the next snippets shows, the <code>Builder</code> uses a fluent interface which you terminate with the use of the <code>build()</code> method.</p>
<pre class="brush: java; title: ; notranslate">
int heightInPx = getResources()
      .getDimensionPixelOffset(R.dimen.custom_crouton_height);
Style style = new Style.Builder()
      .setBackgroundColor(R.color.horribly_pink)
      .setDuration(10000)
      .setGravity(Gravity.LEFT)
      .setTextColor(android.R.color.black)
      .setHeight(heightInPx)
      .build();
Crouton.makeText(
         this, 
         getString(R.string.crouton_message), 
         style)
      .show();
</pre>
<p>There is a bug (or a misunderstanding on my side) with the <code>setHeight()</code> method. It causes the text to move right for exactly the same amount of pixels. As I see it, this happens in the <code>buildImageLayoutParams()</code> method of the project&#8217;s <code>ViewHolder</code> class. I will dig into this as soon as I can and will either file a bug report or submit a patch for this.</p>
<p>On the project site is the warning, that the project &#8220;<em>requires the Holo theme to be present on the device</em>&#8220;. Now this would limit the use of the library significantly. But the warning is overblown. </p>
<p>You can use the library and the Croutons show up fine. Only the default Styles do not work &#8211; all Croutons are displayed in grey. </p>
<p>If your app needs to work on older devices (which it probably does), you have to use custom styles as shown above. I suggest to define constants in the same way, the project itself creates them &#8211; but with your resource definitions for the colors to use. Have a look at the <a href="https://github.com/keyboardsurfer/Crouton/blob/master/library/src/de/keyboardsurfer/android/widget/crouton/Style.java" title="The source code of the Style class at github">Style</a> class for how the Crouton project does it.</p>
<p>A Crouton using the custom style definition just shown, looks like this on a 2.2 device:</p>
<div id="attachment_1770" class="wp-caption alignnone" style="width: 210px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/Crouton_on_a_P500.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/Crouton_on_a_P500-200x300.png" alt="Sample Crouton on an Android 2.2 device" width="200" height="300" class="size-medium wp-image-1770" /></a><p class="wp-caption-text">Sample Crouton on an Android 2.2 device</p></div>
<h3>The demo project</h3>
<p>When you clone the github project, you will notice that the sources include a demo project. The two screenshots shown at the beginning of this post are taken using this demo project.</p>
<p>You can either build this project using Maven or you can import it into Eclipse to have a look around and to try to change stuff. If you want to use it in Eclipse, you have to add the Crouton library. Assuming you have imported the Crouton library project, you can do this by simply opening the project properties and selecting the library:</p>
<div id="attachment_1788" class="wp-caption alignnone" style="width: 310px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/project_settings_demo_project.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/10/project_settings_demo_project-300x215.png" alt="Adding the library to the demo project" width="300" height="215" class="size-medium wp-image-1788" /></a><p class="wp-caption-text">Adding the library to the demo project</p></div>
<h3>Summary</h3>
<p>I think Cyril Mottier made a good point about the problems of Android&#8217;s Toasts. Thanks to Benjamin Weiss Croutons are here to solve these issues for us. The library is very simple to use but thanks to the <code>Style.Builder</code> flexible enough to accommodate your needs.</p>
<p>I have found two minor issues &#8211; which both should be fixable. I will keep you posted about them.</p>
<p>And on a completely unrelated note: While I was busy completing this blog post, <a href="https://plus.google.com/115374955104579332297" title="Marie Schweiz' profile at Google plus">Marie Schweiz</a> created the <a href="https://plus.google.com/115374955104579332297/posts/ECqeUL4cam8" title="Marie Schweiz' announcement of the Crouton icon">icon for the Crouton project</a>. Nice coincidence <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
<img src="http://vg03.met.vgwort.de/na/a5ba5b3c14654aadbabea874cadc30f2" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/useful-android-libraries-crouton/">Useful Android Libraries: Crouton</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/pxWvNRBLjEk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/useful-android-libraries-crouton/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/useful-android-libraries-crouton/</feedburner:origLink></item>
		<item>
		<title>Take These Steps to Make your Android App Accessible</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/s7jigfn2aus/</link>
		<comments>http://www.grokkingandroid.com/steps-to-making-android-app-accessible/#comments</comments>
		<pubDate>Thu, 04 Oct 2012 09:54:09 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Accessibility]]></category>
		<category><![CDATA[android:contentDescription]]></category>
		<category><![CDATA[Directional Navigation]]></category>
		<category><![CDATA[setContentDescription()]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1697</guid>
		<description><![CDATA[<p>Accessibility in an app helps users with disabilities to use your app with the help of the Android system. Android&#8217;s accessibility system tools as well as third-party developer&#8217;s tools provide features to help with visual impairment. In this post I outline why you should care about accessibility and what steps to take to make your [...]</p><p>The post <a href="http://www.grokkingandroid.com/steps-to-making-android-app-accessible/">Take These Steps to Make your Android App Accessible</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">Accessibility in an app helps users with disabilities to use your app with the help of the Android system. Android&#8217;s accessibility system tools as well as third-party developer&#8217;s tools provide features to help with visual impairment. </p>
<p>In this post I outline why you should care about accessibility and what steps to take to make your app accessible. I also deal with testing and why it&#8217;s useful to care about accessibility up front.</p>
<h3>Accessibility is a usability requirement</h3>
<p>When it comes to planning a project, accessibility often is neglected or just mentioned briefly &#8211; without ever detailing what it means for the project at hand. That&#8217;s odd. Why this neglect?</p>
<p>We agree that it&#8217;s useful to make users aware of the flyover menu. Or to add hints to ease the discoverability of a bezel swipe. We sometimes go to great lengths to improve the usability of an app. But not when it comes to accessibility. </p>
<p>Of the many Android development books that I know, only two cover accessibility: Reto Meier&#8217;s &#8220;<a href="http://www.amazon.com/gp/product/1118102274/ref=as_li_tf_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1118102274&amp;linkCode=as2&amp;tag=grokkandro-20">Professional Android 4 Application Development</a><img src="http://www.assoc-amazon.com/e/ir?t=grokkandro-20&amp;l=as2&amp;o=1&amp;a=1118102274" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" />&#8221; and Jasons Ostrander&#8217;s &#8220;<a href="http://www.amazon.com/gp/product/0321814584/ref=as_li_tf_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321814584&amp;linkCode=as2&amp;tag=grokkandro-20">Android UI Fundamentals</a><img src="http://www.assoc-amazon.com/e/ir?t=grokkandro-20&amp;l=as2&amp;o=1&amp;a=0321814584" width="1" height="1" border="0" alt="" style="border:none !important;margin:0px !important" />&#8220;. That&#8217;s a sorry state, in my opinion.</p>
<p><a name="accessibility_is_no_afterthought"></a></p>
<h3>Accessibility is no after-thought</h3>
<p>It is up to the designers and usability experts to work out the concept of the app &#8211; including everything that has to do with accessibility. Even though, as you have seen, it is pretty easy to implement, it is probably not so easy to get the concept right.</p>
<p>For example, users can change the font-size of their device. This can have a big influence of which design works and which doesn&#8217;t.</p>
<p>With this in mind, you also have to decide what text shouldn&#8217;t get scaled when this setting changes. And if there is a good reason for this. What would an unscaled text mean for people that need big text? </p>
<p>For example the stock email app does scale the text of the message list, but not of the folders. You have to decide thoroughly &#8211; and if possible test thoroughly &#8211; if and where this is appropriate.</p>
<p>Furthermore the size of clickable areas should be designed to be big enough for all kind of fingers and hit-precisions. Think of kids, of elder people, people with tremors and so on.</p>
<p>Think of people with color blindness. Do use clear contrasts and do not use colors only to signal the state of something. I am currently writing an app for a server monitoring service. Obviously red signals a critical situation whereas green is used for a properly functioning server. But we do not rely on color alone, but add text to distinguish both furthermore.</p>
<p>Then the order in which controls should be focusable has to be agreed upon right from the beginning. This is a minor change, but it&#8217;s probably better not up to the developer&#8217;s imagination.</p>
<p>Also you should plan on the labels for textual descriptions early on. You think thoroughly about any text displayed on the screen, so do the same for these descriptions. Otherwise you have to quickly come up with descriptions when you want to go live. Or &#8211; even worse &#8211; you might end up with the placeholders the developers used <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Finally do not forget to add feedback mechanisms beyond audio. No matter if people have hearing disabilities or not, you should always provide additional means to notify users. All users turn off audio in certain situations. So if you use a signal sound to alert a user of something, consider to also use haptic and visual feedback as well.</p>
<h3>How to make your apps accessible</h3>
<p>Gladly it is easy for most apps to make them accessible. Most often all you need to do is:</p>
<ul>
<li>Support directional navigation</li>
<li>Add descriptions to UI elements</li>
</ul>
<p>If you need controls not provided by the Android platform, you have to care about accessibility as well. Since I plan a mini-series about writing custom controls anyway, I will explain this as one part of this mini-series. </p>
<h3>Support directional navigation</h3>
<p>Users might find it easier to use the D-pad to navigate around your app. This is not only true for users with disabilities but might be more comfortable if users are distracted in some way or simply prefer this to touching depending on circumstances. </p>
<p>Without fine-tuning the navigational flow of controls, though, D-pad navigation might be cumbersome at some places.</p>
<p>Most often Android provides a reasonable navigational order. But if not or if you want to tweak it to improve upon this, you can do so by stating which element  to focus next &#8211; for all four directions supported:</p>
<ul>
<li>android:nextFocusUp</li>
<li>android:nextFocusDown</li>
<li>android:nextFocusLeft</li>
<li>android:nextFocusRight</li>
<li>android:nextFocusForward</li>
</ul>
<p>Of these only <code>nextFocusForward</code> might need some explaining. This denotes the element to focus when the user hits &#8220;next&#8221; on the soft keyboard or uses a <a href="https://support.google.com/nexus/galaxy/answer/2926960?hl=en&amp;ref_topic=2926458" title="Gestures for moving around when explore by touch is activated">gesture to move to the next focusable element</a>.</p>
<p>The following snippet shows an example of how to do this:</p>
<pre class="brush: xml; highlight: [6,16]; title: ; notranslate">
&lt;EditText
   android:id=&quot;@+id/title&quot;
   android:layout_width=&quot;fill_parent&quot;
   android:layout_height=&quot;wrap_content&quot;
   android:hint=&quot;@string/title&quot;
   android:nextFocusDown=&quot;@id/description&quot;
   android:singleLine=&quot;true&quot; /&gt;

&lt;!-- ... --&gt;

&lt;EditText
   android:id=&quot;@+id/description&quot;
   android:layout_width=&quot;fill_parent&quot;
   android:layout_height=&quot;wrap_content&quot;
   android:hint=&quot;@string/description&quot;
   android:nextFocusUp=&quot;@id/title&quot; /&gt;
</pre>
<p>The target view must be focusable of course. All standard controls of android are focusable by default. But if you write your own custom-controls you have to take care of this yourself.</p>
<h3>Add descriptions to UI elements</h3>
<p>For some UI elements like image buttons and so on a screen reader is at a loss of what to read, if you do not help it. But helping is very easy to do. You just need to add a content description to these elements.</p>
<p>You can do so either when adding the views to the xml layout files:</p>
<pre class="brush: xml; highlight: [5]; title: ; notranslate">
&lt;ImageButton
   android:id=&quot;@+id/btn_contact&quot;
   android:layout_width=&quot;wrap_content&quot;
   android:layout_height=&quot;wrap_content&quot;
   android:contentDescription=&quot;@string/contact&quot;
   android:src=&quot;@drawable/btn_contact&quot; 
/&gt;
</pre>
<p>Or you can add content descriptions programatically if they have to be dynamic:</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
ImageButton button = 
      (ImageButton)findViewById(R.id.btn_contact);
button.setContentDescription(getString(R.string.contact));
</pre>
<p>If a graphical element is used only to please the user visually without any further use, you should set the content description to &#8220;@null&#8221;. That way screen readers know that they should ignore this element.</p>
<h3>Test accessibility</h3>
<p>To test the accessibility features of your app you need to test whether your changes work.</p>
<p>You can test the D-pad functionality easily in the emulator. You can either use the D-pad of the emulator or the arrow keys of your keyboard.</p>
<p>For testing that users with limited vision can handle your app, you can use <a href="https://play.google.com/store/apps/details?id=com.google.android.marvin.talkback" title="Spoken feedback app by Google">TalkBack</a>. This app is included on most android devices and can also be downloaded from the play store. Alas it is not included in the emulator. So you need to test on a real device.</p>
<p>Try your app without looking at the screen. Can you navigate around? Can you identify all elements and understand what they are used for?</p>
<p>You also have to test if your app looks reasonably good, if the user changes the default font-size. Especially activities with many views and relatively small UI elements might look bad with bigger text.</p>
<p>Don&#8217;t forget to test the feedback mechanisms. Do they work without sound? </p>
<p>All in all testing accessibility should be based on the requirements outlined in the concept (see the section &#8220;<a href="#accessibility_is_no_afterthought">Accessibility is no after-thought</a>&#8220;). If the design of your app contains hints on what accessibility mechanisms to use, testing becomes straight-forward. Another reason why accessibility should be planned and described up front.</p>
<h3>More on this topic</h3>
<p>Google itself provides useful information about this topic in the training, developers and design sections of Android&#8217;s site.</p>
<p>The design section contains a <a href="http://developer.android.com/design/patterns/accessibility.html" title="Design pattern accessibility">page on accessibility</a> within its pattern section.</p>
<p>The developer section contains a very detailed article about <a href="http://developer.android.com/guide/topics/ui/accessibility/apps.html" title="Google's detailed article about writing an accessible app">implementing accessible apps</a> as well as an <a href="http://developer.android.com/guide/topics/ui/accessibility/checklist.html" title="Google's accessibility checklist">accessibility checklist</a>.</p>
<p>The training section contains the guide &#8220;<a href="http://developer.android.com/training/accessibility/accessible-app.html" title="Android's training on developing accessible applications">Developing Accessible Applications</a>&#8220;.</p>
<p>And &#8211; oddly placed &#8211; the tools section has a nice <a href="http://developer.android.com/tools/testing/testing_accessibility.html" title="Google's checklist for accessibility testing">document on accessibility testing</a>.</p>
<p><a href="https://plus.google.com/103872873250909646668/" title="Google+ profile of TV Raman">TV Raman</a>, an accessibility research scientist, blogs on <a href="http://eyes-free.blogspot.com/" title="Blog about accessibility features in Android">Eyes-Free Android</a> about accessibility features of Android. And he has uploaded many videos explaining <a href="http://www.youtube.com/user/EyesFreeAndroid" title="EyesFreeAndroid on Youtube">Android&#8217;s accessibility features to Youtube</a>. He points out that these features are not only for visually-impaired people but might be useful in certain conditions for all of us. </p>
<p>There is also the <a href="http://www.youtube.com/watch?v=BPXqsPeCneA" title="Google IO's talk about accessibility">Google IO talk on accessibility</a>.</p>
<p>Finally for Nexus devices you can find the accessibility user guide on Google&#8217;s support pages. For example, here&#8217;s the <a href="https://support.google.com/nexus/7/topic/2692466?hl=en&amp;ref_topic=2847279" title="Accessibility Guide for Google's Nexus 7">accessibility guide for the Nexus 7</a>.</p>
<h3>Not covered in this post</h3>
<p>As mentioned, I didn&#8217;t cover adding accessibility features to your custom controls. This will be the topic of a post on its own.</p>
<p>I also didn&#8217;t cover how to write accessibility services. These are tools, that give the user some kind of feedback on certain events. This could be reading out a text when the user navigates to an element using his D-pad or it might be some haptic feedback on a button press and so on. Google provides some tools as part of the Android platform, other vendors might add their own. The user can select which services to use in Android&#8217;s settings. Google has a thorough <a href="http://developer.android.com/training/accessibility/service.html" title="Google's guide on writing an accessibility service">guide on how to code an accessibility service</a>.</p>
<h3>Wrapping up</h3>
<p>In this post I have outlined why you should care about accessibility and what steps to take, to make your app accessible. </p>
<p>I also covered that you should care about accessibility already while designing and drafting your app and how to test your app later on.</p>
<p>I mentioned hints on how to test accessibility and pointed out where to find more ressources.</p>
<p>So what&#8217;s holding you back? Anything you miss to make your app accessible?</p>
<p>Note: I am no native speaker. So if anyone feels offended by any expression used here, please leave a comment on why this is and what other expression to use.</p>
<p><em>Disclaimer: Some of the links contained within this site have my Amazon referral ID, which provides me with a small commission for each sale. Thank you for your support.</em><br />
<img src="http://vg03.met.vgwort.de/na/68c093e2935b46f78f1182e1131caeb2" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/steps-to-making-android-app-accessible/">Take These Steps to Make your Android App Accessible</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/s7jigfn2aus" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/steps-to-making-android-app-accessible/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/steps-to-making-android-app-accessible/</feedburner:origLink></item>
		<item>
		<title>How to Use Loaders in Android</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/ExiIATEWjME/</link>
		<comments>http://www.grokkingandroid.com/using-loaders-in-android/#comments</comments>
		<pubDate>Thu, 27 Sep 2012 05:53:51 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[AsyncTaskLoader]]></category>
		<category><![CDATA[CursorLoader]]></category>
		<category><![CDATA[initLoader()]]></category>
		<category><![CDATA[Loader]]></category>
		<category><![CDATA[LoaderManager]]></category>
		<category><![CDATA[LoaderManager.LoaderCallbacks]]></category>
		<category><![CDATA[restartLoader()]]></category>
		<category><![CDATA[SqliteCursorLoader]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1390</guid>
		<description><![CDATA[<p>With the introduction of Honeycomb Loaders became the preferred way to access data of databases or content providers. They load data asynchronously and notify listeners when the results are ready. Google did not only introduce Loaders but also deprecated the previous way to handle a Cursor within your activities. You shouldn&#8217;t use startManagingCursor() or managedQuery() [...]</p><p>The post <a href="http://www.grokkingandroid.com/using-loaders-in-android/">How to Use Loaders in Android</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">With the introduction of Honeycomb Loaders became the preferred way to access data of databases or content providers. They load data asynchronously and notify listeners when the results are ready.</p>
<p>Google did not only introduce Loaders but also deprecated the previous way to handle a Cursor within your activities. You shouldn&#8217;t use <code>startManagingCursor()</code> or <code>managedQuery()</code> in your projects anymore. </p>
<p>With managed cursors queries and requeries are executed on the UI thread. This could cause the app to feel unresponsive or to even display an ANR error message. With Loaders your queries will no longer run on the UI thread and your app remains responsive.</p>
<p>In this post I introduce the classes that form the Loader API and show you how to use them.</p>
<table>
<caption>The classes and interfaces of the Loader API</caption>
<tr>
<th>Class</th>
<th>Usage</th>
</tr>
<tr>
<td>LoaderManager</td>
<td>Manages your Loaders for you. Responsible for dealing with the Activity or Fragment lifecycle</td>
</tr>
<tr>
<td>LoaderManager.LoaderCallbacks</td>
<td>A callback interface you must implement</td>
</tr>
<tr>
<td>Loader</td>
<td>The base class for all Loaders</td>
</tr>
<tr>
<td>AsyncTaskLoader</td>
<td>An implementation that uses an <a href="https://developer.android.com/reference/android/os/AsyncTask.html" title="Documentation of Android's AsyncTask">AsyncTask</a> to do its work</td>
</tr>
<tr>
<td>CursorLoader</td>
<td>A subclass of AsyncTaskLoader for accessing ContentProvider data</td>
</tr>
</table>
<p>In the following sections I describe most of these classes and what you need to know about them &#8211; starting with the <a href="http://developer.android.com/reference/android/app/LoaderManager.html" title="Documentation of the LoaderManager class">LoaderManager</a>.</p>
<h3>LoaderManager</h3>
<p>This class keeps your Loaders in line with the lifecycle of your activities or fragments. If Android destroys your fragments or activities, the <code>LoaderManager</code> notifies the managed loaders to free up their resources. The <code>LoaderManager</code> is also responsible for retaining your data on configuration changes like a change of orientation and it calls the relevant callback methods when the data changes. In short: The <code>LoaderManager</code> is way more powerful than the old <code>startManagingCursor()</code> or <code>managedQuery()</code> methods.</p>
<p>You do not instantiate the <code>LoaderManager</code> yourself. Instead you simply call <code>getLoaderManager()</code> from within your activity or your fragment to get hold of it. </p>
<p>Most often you are only interested in two methods of the manager:</p>
<ul>
<li><code>initLoader()</code> and</li>
<li><code>restartLoader()</code></li>
</ul>
<h4>initLoader()</h4>
<p>The <code>initLoader()</code> method adds a <code>Loader</code> to the <code>LoaderManager</code>:</p>
<pre class="brush: java; title: ; notranslate">
getLoaderManager().initLoader(LIST_ID, null, this);
</pre>
<p>It takes three arguments: </p>
<ul>
<li>a unique ID for this loader,</li>
<li>an optional <code>Bundle</code> with arguments for your Loader and
<li>a <a href="https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html" title="Documentation of the LoaderCallbacks interface">LoaderCallbacks</a> interface</li>
</ul>
<p>You might need the ID for further method calls. So using a final static field for the ID makes your code more readable. The Bundle can be used to pass additional arguments to your Loader, but isn&#8217;t used by the <code>CursorLoader</code>. The third argument, the callback interface, will be covered in detail later on.</p>
<p>The <code>initLoader()</code> method creates a new Loader only if for this ID none has been created previously. Keep in mind that Android deals with configuration changes for you, thus a simple change in orientation is enough to trigger a new call to <code>initLoader()</code>. In this case the method returns the existing instance and your query is not executed again.</p>
<h4>restartLoader()</h4>
<p>Because Android doesn&#8217;t execute the query again, you need a way to re-initialize the Loader when data, that is used to build the query, changes. Typical examples are search queries.</p>
<p>You reset your Loader by using the <code>restartLoader()</code> method. It takes the same parameters as <code>initLoader()</code>. Of course you have to use the same ID you used for initializing.</p>
<pre class="brush: java; title: ; notranslate">
getLoaderManager().restartLoader(LIST_ID, null, this);
</pre>
<h3>LoaderManager.LoaderCallbacks</h3>
<p>The interface <code>LoaderCallbacks</code> defines methods you must implement to create your Loader, to deal with the results and to clean up resources. </p>
<p>Since the interface is parameterized you must specify the type of data your Loader holds. Most often the type will be <code>Cursor</code>:</p>
<pre class="brush: java; title: ; notranslate">
public class YourFragment extends Fragment 
      implements LoaderCallbacks&lt;Cursor&gt; {
   //...
}
</pre>
<p>The methods you have to implement are:</p>
<ul>
<li>onCreateLoader(),</li>
<li>onLoadFinished() and</li>
<li>onLoadReset()</li>
</ul>
<p>In the next sections I show what to do in each of these callback methods.</p>
<h4>onCreateLoader()</h4>
<p>The <code>LoaderManager</code> calls this method when you call <code>initLoader()</code> for the first time. As mentioned, the manager only calls this method if no loader for the given ID exists. </p>
<p>The method gets an int value and a Bundle passed in. These are the same values you used for your initLoader() call.</p>
<p>A typical example creating a <code>CursorLoader</code> looks like this:</p>
<pre class="brush: java; title: ; notranslate">
public Loader&lt;Cursor&gt; onCreateLoader(int id, Bundle args) {
   CursorLoader loader = new CursorLoader(
         this.getActivity(),
         SOME_CONTENT_URI, 
         projection, 
         selection, 
         selectionArgs, 
         sortOrder);
   return loader;
}
</pre>
<p>As you can see the parameters are a <code>Context</code> object plus those of the ContentResolver&#8217;s <code>query()</code> method. If you&#8217;re not familiar with these arguments, I recommend you read my <a href="http://www.grokkingandroid.com/android-tutorial-using-content-providers/" title="Android Tutorial: Using Content Providers">post about accessing content providers</a>.</p>
<p>If you need to track multiple queries and thus use different IDs for your Loaders, all you need to add is a simple case- or if-else-branch.</p>
<h4>onLoadFinished()</h4>
<p>This method is the most interesting one. Here you update the UI based on the results of your query. </p>
<p>For <code>ListAdapters</code> you simply swap the cursor of the adapter as described in the section &#8220;<a href="#how_to_deal_with_cursoradapters" title="Jump to the Section 'Changes needed for CursorAdapters'">Changes needed for CursorAdapters</a>&#8220;. </p>
<p>For all other cases you have to get references to the view elements and set their value according to the result.</p>
<p>This is how it looks in the sample project:</p>
<pre class="brush: java; title: ; notranslate">
public void onLoadFinished(
      Loader&lt;Cursor&gt; loader, 
      Cursor cursor) {
   if (cursor != null &amp;&amp; cursor.getCount() &gt; 0) {
      cursor.moveToFirst();
      int idIndex = 
            cursor.getColumnIndex(LentItems._ID);
      int nameIndex = 
            cursor.getColumnIndex(LentItems.NAME);
      int borrowerIndex = 
            cursor.getColumnIndex(LentItems.BORROWER);
      this.itemId = cursor.getLong(idIndex);
      String name = cursor.getString(nameIndex);
      String borrower = cursor.getString(borrowerIndex);
      ((EditText)findViewById(R.id.name)).
            setText(name);
      ((EditText)findViewById(R.id.person)).
            setText(borrower);
   }
}
</pre>
<h4>onLoadReset()</h4>
<p>This method allows you to release any resources you hold, so that the Loader can free them. You can set any references to the cursor object you hold to null.<br />
<strong>But do not close the cursor</strong> &#8211; the Loader does this for you. </p>
<p>See also the section about <a href="#how_to_deal_with_cursoradapters" title="Jump to the Section 'Changes needed for CursorAdapters'">how to deal with CursorAdapters</a>.</p>
<h3>Loader, AsyncTaskLoader and CursorLoader</h3>
<p>The Loader interface and its implementations are not very interesting &#8211; unless you write your own custom Loaders. You have to create a <code>Loader</code> of course. But other than using the constructor of <code>CursorLoader</code>, you normally do not interact with these objects yourself.</p>
<p>If you use multiple Loaders you need to access the ID in the callback methods. You can do so by calling <code>getId()</code> on the loader passed in to the callbacks.</p>
<p>If you want to write a custom Loader yourself, please have a look at Alex Lockwood&#8217;s <a href="http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html" title="post by Alex Lockwood about implementing loaders">tutorial on implementing loaders</a>.<a name="how_to_deal_with_cursoradapters"></a></p>
<h3>Changes needed for CursorAdapters</h3>
<p>An important use of cursors in Android is to use a <code>CursorAdapter</code> as data source for <code>ListViews</code>, <code>AutoCompleteTextViews</code> and so on. When working with Loaders you have to adapt the old way slightly.</p>
<p>First of all: You do not have a Cursor object before the <code>onLoadFinished()</code> method of your callback has been called. In other words: The cursor is not ready when you create the adapter. Thus you create the adapter using <code>null</code> for the cursor argument:</p>
<pre class="brush: java; title: ; notranslate">
SimpleCursorAdapter adapter = 
      new SimpleCursorAdapter(
            getApplicationContext(), 
            android.R.layout.simple_list_item_1, 
            null, 
            columns, 
            layoutIds, 
            0);
</pre>
<p>When the cursor is finally available you have to add it. You do this by calling <code>swapCursor()</code> on your adapter and passing in the cursor object of your callback method:</p>
<pre class="brush: java; title: ; notranslate">
public void onLoadFinished(
      Loader&lt;Cursor&gt; loader, 
      Cursor cursor) {
   ((SimpleCursorAdapter)this.getListAdapter()).
         swapCursor(cursor);
}
</pre>
<p>And to clean up resources in the <code>onLoadReset()</code> method you also use <code>swapCursor()</code>, this time passing in a <code>null</code> value:</p>
<pre class="brush: java; title: ; notranslate">
public void onLoaderReset(Loader&lt;Cursor&gt; loader) {
   ((SimpleCursorAdapter)this.getListAdapter()).
         swapCursor(cursor);
}
</pre>
<h3>Use the Support Library for older Android versions</h3>
<p>To support newer features on older Android versions, Google provides the <a href="http://developer.android.com/tools/extras/support-library.html" title="Android's Support Library">Support Library</a>. The two main components this library contains are Fragments and Loaders. </p>
<p>You can and should use this library for projects that must support older versions. All reasons for using the Loader-API are valid for pre-Honeycomb devices as well.</p>
<p>But you have to keep an eye on the import statements. All import statements for classes of the Support Library begin with <code>android.support.v4</code>:</p>
<pre class="brush: java; title: ; notranslate">
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
</pre>
<p>Don&#8217;t mix classes of the support library with normal classes. The compiler will spot most problems for you and then there is also <a href="http://tools.android.com/tips/lint" title="Documentation of the Lint toolt">Lint</a> to help you. But if you ever wonder why some code is marked as invalid, this most likely is the reason.</p>
<p>To use Loaders for older Android versions, you need to use activities or fragments of the Support Library. The normal ones do not have the <code>getLoaderManager()</code> method before Honeycomb. You project would still compile (if your build target is at least SDK 11) but at runtime you would get a <code>NoSuchMethodError</code> on older devices.</p>
<h3>Using Loaders to access your SQLiteDatabase</h3>
<p>Since Android&#8217;s <code>CursorLoader</code> is only for Cursors returned by content providers we need another Loader implementation if we want to use SQLite directly.</p>
<p>Thankfully <a href="http://commonsware.com/blog/">Mark Murphy</a> has written a library that offers <a href="https://github.com/commonsguy/cwac-loaderex" title="Mark Murphy's loaderex library">enhancements to the Loader framework</a>. This library also contains a <code>SQLiteCursorLoader</code>.</p>
<p>To use Mark Murphy&#8217;s <code>SQLiteCursorLoader</code> you have to create an SQL <code>select</code> statement and pass it to the constructor.The constructor also expects an <code>SQLiteOpenHelper</code> object. An example of the onCreateLoader() method could look like this:</p>
<pre class="brush: java; title: ; notranslate">
public Loader&lt;Cursor&gt; onCreateLoader(int id, Bundle args) {
   String rawQuery = &quot;SELECT ...&quot;;
   String[] queryParams = // to substitute placeholders
   SQLiteCursorLoader loader = 
   new SQLiteCursorLoader(
         getActivity().getApplicationContext(), 
         yourSqliteOpenHelper, 
         rawQuery, 
         queryParams);
   return loader;
}

</pre>
<p>But there is more to it. You have to use this loader also for deleting, updating or inserting rows as well. Only by doing so, the loader knows about a data change and can call the correct callback methods.</p>
<p>I won&#8217;t go into these details here. See the <a href="https://github.com/commonsguy/cwac-loaderex" title="CommonsWare's loader library">project&#8217;s github page</a> or have a look at Mark Murphy&#8217;s sample project.</p>
<p>If you intend to use this library, don&#8217;t use the jar-file offered on the project page. It is outdated. Instead clone the git repository and add the project to your IDE directly.</p>
<h3>When not to use Loaders</h3>
<p>On <a href="http://www.reddit.com/r/androiddev/comments/10jwcr/how_to_use_loaders_in_android/" title="Reddits thread about this blog post">reddit</a>, <a href="http://www.reddit.com/user/cokacokacoh" title="cokacokacoh's profile on reddit">cokacokacoh</a> noted that my post missed a section on when not to use Loaders. He was right of course. So I added the following paragraph to this post.</p>
<p>As cokacokacoh points out, you shouldn&#8217;t use Loaders if you need the background tasks to complete. Android destroys Loaders together with the Activities/Fragments they belong to. If you want to do some tasks, that have to run until completion, do not use Loaders. You should use services for this kind of stuff instead.</p>
<p>Keep in mind that Loaders are special components to help you create responsive UIs and to asynchronously load data that this UI component needs. That&#8217;s the reason why Loaders are tied to the lifecycle of their creating components. Do not try to abuse them for anything else!</p>
<h3>Lessons learned</h3>
<p>In this blog post you have seen how to use the Loader framework. And since this framework is available for older Android versions using the Support Library there is no reason not to use it.</p>
<p>The <code>CursorLoader</code> provided by Android is useful for content providers. But not all projects use these. If your project uses SQLite directly you can use Mark Murphys <code>SQLiteCursorLoader</code> as shown above.</p>
<p>I didn&#8217;t cover how to write Loaders on your own. If you need to do so, <a href="https://plus.google.com/100751609891157863386" title="Google+ profile of Alex Lockwood">+Alex Lockwood</a> has a nice <a href="http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html" title="post by Alex Lockwood about implementing loaders">tutorial on implementing loaders</a>.</p>
<p>Please let me know in the comments if this post was helpful or if you have any questions left. And don&#8217;t forget to plus one or tweet this post, if you liked it <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /><br />
<img src="http://vg03.met.vgwort.de/na/c39ea5d287dc478299114eca5ed78237" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/using-loaders-in-android/">How to Use Loaders in Android</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/ExiIATEWjME" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/using-loaders-in-android/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/using-loaders-in-android/</feedburner:origLink></item>
		<item>
		<title>Android Quick Tip: Enabling and Disabling BroadcastReceivers at Runtime</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/X83MTcsRI4E/</link>
		<comments>http://www.grokkingandroid.com/enabling-and-disabling-broadcastreceivers/#comments</comments>
		<pubDate>Wed, 19 Sep 2012 05:47:06 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[BroadcastReceiver]]></category>
		<category><![CDATA[PackageManager]]></category>
		<category><![CDATA[setComponentEnabledSetting()]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1303</guid>
		<description><![CDATA[<p>BroadcastReceivers are good when you want to be notified about system events. But sometimes you do need to know about an event only once or for a short period of time. A dynamically registered receiver doesn&#8217;t cut it because the Activity and it&#8217;s dynamically registered broadcast receiver might long be dead when the event occurs. [...]</p><p>The post <a href="http://www.grokkingandroid.com/enabling-and-disabling-broadcastreceivers/">Android Quick Tip: Enabling and Disabling BroadcastReceivers at Runtime</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">BroadcastReceivers are good when you want to be notified about system events. But sometimes you do need to know about an event only once or for a short period of time. </p>
<p>A <a href="http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/" title="Android Tutorial: BroadcastReceiver">dynamically registered receiver</a> doesn&#8217;t cut it because the Activity and it&#8217;s dynamically registered broadcast receiver might long be dead when the event occurs. The only way to achieve this is by enabling and disabling broadcast receivers in your code.</p>
<h3>Enabling or Disabling BroadcastReceivers</h3>
<p>You enable or disable receivers by using methods of the <a href="https://developer.android.com/reference/android/content/pm/PackageManager.html" title="Documentation of Android's PackageManager class">PackageManager</a> class. With this class you can enable and disable app components at runtime:</p>
<pre class="brush: java; title: ; notranslate">
PackageManager pm = getPackageManager();
ComponentName compName = 
      new ComponentName(getApplicationContext(), 
            YourReceiver.class);
pm.setComponentEnabledSetting(
      compName,
      PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
      PackageManager.DONT_KILL_APP);
</pre>
<p>There are three states the PackageManager offers for this:</p>
<table>
<caption>Supported states of setComponentEnabledSetting()</caption>
<tr>
<td>COMPONENT_ENABLED_STATE_DEFAULT</td>
<td>Sets the state to the manifest file value</td>
</tr>
<tr>
<td>COMPONENT_ENABLED_STATE_DISABLED</td>
<td>Sets the state to disabled</td>
</tr>
<tr>
<td>COMPONENT_ENABLED_STATE_ENABLED</td>
<td>Sets the state to enabled</td>
</tr>
</table>
<p>By default the <code>PackageManager</code> kills your app immediately, since a component state change could lead to unpredictable situations. The flag <code>DONT_KILL_APP</code> prevents this from happening and is safe to use for BroadcastReceivers. Of course if you do not use the <code>DONT_KILL_APP</code>-flag, you will spot your mistake even with the most cursory of testings <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Disabling BroadcastReceivers by default</h3>
<p>If you want to enable your receiver at runtime, you can set the state to disabled initially. You can do so in the manifest file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;receiver
   android:name=&quot;.YourReceiver&quot;
   android:enabled=&quot;false&quot; &gt;
   &lt;!-- your intent filter --&gt;
&lt;/receiver&gt;
</pre>
<h3>When to use this</h3>
<p>The basic reason why you should do this, is that you want to preserve valuable resources on your user&#8217;s devices. You do not want to drain the battery by running code that is not relevant to your user. Most often you can achieve this by <a href="http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/" title="Android Tutorial: BroadcastReceiver">using a dynamically registered receiver</a>. But this does not always work.</p>
<p>Three examples where you should explicitly use the PackageManager-solution presented above:</p>
<p>1. You might need to know about the next boot, but only the next one. In this case you cannot use a dynamically registered receiver. You have to use a statically registered one. But you do not want to run it on every boot completion. Which means that you have to disable the receiver after it&#8217;s first run.</p>
<p>2. If one or more receivers depend on the state of a specific system service you can disable all of them for as long as the necessary service is not in the desired state. This could be true for <a href="http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/" title="Android: Getting Notified of Connectivity Changes">network connectivity</a>, while waiting for a GPS fix, for missing Bluetooth availabilty and such.</p>
<p>3. You intend to use notifications &#8211; but only if the app is not currently active. In this case your <code>BroadcastReceiver</code> has to be enabled by default. But you would disable it in your Activities&#8217; <code>onResume()</code> method and re-enable it in the <code>onPause()</code> method.</p>
<p>See also Reto Meier&#8217;s <a href="http://android-developers.blogspot.de/2011/06/deep-dive-into-location.html" title="Reto Meier's ProTips Blog Post">blog post about location-based apps</a> and have a thorough look at the <a href="http://code.google.com/p/android-protips-location/" title="Google Code project about location project's protips">accompanying source code</a>. He covered these topics initially in <a href="http://www.google.com/events/io/2011/sessions/android-protips-advanced-topics-for-expert-android-app-developers.html" title="Reto Meier's Google IO talk of 2011">his talk at Google&#8217;s IO 2011</a>. I highly recommend to watch the video of this talk. It&#8217;s definitely a good watch!<br />
<img src="http://vg03.met.vgwort.de/na/41de0f0710f341c5b97a6a455995d912" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/enabling-and-disabling-broadcastreceivers/">Android Quick Tip: Enabling and Disabling BroadcastReceivers at Runtime</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/X83MTcsRI4E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/enabling-and-disabling-broadcastreceivers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/enabling-and-disabling-broadcastreceivers/</feedburner:origLink></item>
		<item>
		<title>Recording Audio using Android’s MediaRecorder Framework</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/yvOLqwvAYjk/</link>
		<comments>http://www.grokkingandroid.com/recording-audio-using-androids-mediarecorder-framework/#comments</comments>
		<pubDate>Tue, 11 Sep 2012 09:33:40 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[MediaRecorder]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1478</guid>
		<description><![CDATA[<p>Sometimes your app needs the ability to record and store audio files. As most devices come with a microphone it&#8217;s no surprise that Android offers app developers the possibility to do so. This post deals with the two most common ways to record audio on Android. Recording audio using an Intent As usual that&#8217;s by [...]</p><p>The post <a href="http://www.grokkingandroid.com/recording-audio-using-androids-mediarecorder-framework/">Recording Audio using Android&#8217;s MediaRecorder Framework</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">Sometimes your app needs the ability to record and store audio files. As most devices come with a microphone it&#8217;s no surprise that Android offers app developers the possibility to do so. This post deals with the two most common ways to record audio on Android.</p>
<h3>Recording audio using an Intent</h3>
<p>As usual that&#8217;s by far the easiest option. You simply create the <code>Intent</code> object and <a href="http://www.grokkingandroid.com/checking-intent-availability/" title="Checking Intent Availability in Android">check for its availability</a>. When you have done so, start the Activity:</p>
<pre class="brush: java; title: ; notranslate">
Intent intent = 
      new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (isAvailable(getApplicationContext(), intent)) {
   startActivityForResult(intent, 
         REQUESTCODE_RECORDING);
}
</pre>
<p>You have to use <code>startActivityForResult()</code> since you want to know which file has been created in your <code>onActivityResult()</code> method. <code>REQUESTCODE_RECORDING</code> is a final static int variable that you have to create. You can give it any name you like. The value of this field must be unique among all <code>startActivityForResult()</code> calls that you might want to use.</p>
<p>You need this int field again when checking for the result:</p>
<pre class="brush: java; title: ; notranslate">
protected void onActivityResult(int requestCode, 
      int resultCode, Intent intent) {
   if (requestCode == REQUESTCODE_RECORDING) {
      if (resultCode == RESULT_OK) {
         Uri audioUri = intent.getData();
         // make use of this MediaStore uri 
         // e.g. store it somewhere
      }
      else {
         // react meaningful to problems
      }
   }
   else {
      super.onActivityResult(requestCode, 
            resultCode, intent);
   }
}
</pre>
<p>The standard activity to record audio looks like this:<br />
<div id="attachment_1557" class="wp-caption alignnone" style="width: 178px"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/09/recording_audio_with_intent.png"><img src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2012/09/recording_audio_with_intent-168x300.png" alt="Standard activity for audio recording" width="168" height="300" class="size-medium wp-image-1557" /></a><p class="wp-caption-text">Standard activity for audio recording</p></div></p>
<p>Alas using an intent has the usual drawback: The intent might not be available. And, indeed, on my old LG Optimus One (P500) it doesn&#8217;t work <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<p>So be sure to at least <a href="http://www.grokkingandroid.com/checking-intent-availability/" title="Checking Intent Availability in Android">check for intent availability</a> before trying to use it.</p>
<p>A problem with this solution is the location, that Android uses to store the recorded file. Android puts the file directly to the root of the SD card &#8211; <a href="http://www.grokkingandroid.com/how-to-correctly-store-app-specific-files-in-android/" title="How to Correctly Store App-Specific Files in Android">something that often annoys users</a>.</p>
<h3>Doing it yourself</h3>
<p>If you want to have more control over audio recording you could use the <a href="https://developer.android.com/reference/android/media/MediaRecorder.html" title="Documentation of Android's MediaRecorder class">MediaRecorder</a>.</p>
<p>But first you have to cover the basics &#8211; permissions. As usual you have to state that your app wants to record audio in the mainfest file. Add these lines to your <code>AndroidManifest.xml</code>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;uses-permission 
      android:name=&quot;android.permission.RECORD_AUDIO&quot; /&gt;
</pre>
<p>For the intent-based solution above you do not need this permission. But for using the <code>MediaRecorder</code> framework, you do. Without the correct permission you get an exception that is very misleading:</p>
<p><code>java.lang.RuntimeException: setAudioSource failed.</code></p>
<p>This is Android&#8217;s strange way to tell us, that we forgot to ask for this permission <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Using the MediaRecorder</h3>
<p>Recording audio with the <code>MediaRecorder</code> requires you to adhere to the <code>MediaRecorder's </code> state transitions, so you have to be strict with the ordering of your operations. To start a recording you have to do the following steps:</p>
<ol>
<li>Create a MediaRecorder object</li>
<li>State the source to use</li>
<li>Set the file format</li>
<li>Set the Encoding</li>
<li>Prepare a file</li>
<li>Start recording</li>
</ol>
<p>And here it is in code:</p>
<pre class="brush: java; title: ; notranslate">
MediaRecorder recorder = null;

private void startRecording(File file) {
   if (recorder != null) {
      recorder.release();
   }
   recorder = new MediaRecorder();
   recorder.setAudioSource(AudioSource.MIC);
   recorder.setOutputFormat(OutputFormat.THREE_GPP);
   recorder.setAudioEncoder(AudioEncoder.AMR_WB);
   recorder.setOutputFile(file.getAbsolutePath());
   try {
      recorder.prepare();
      recorder.start();
   } catch (IOException e) {
      Log.e(&quot;giftlist&quot;, &quot;io problems while preparing [&quot; +
            file.getAbsolutePath() + &quot;]: &quot; + e.getMessage());
   }
}
</pre>
<p>You need the <code>MediaRecorder</code> object later on to stop the recording and to clean up, so you have to use an instance variable for it.</p>
<p>Please follow Android&#8217;s <a href="http://www.grokkingandroid.com/how-to-correctly-store-app-specific-files-in-android/" title="How to Correctly Store App-Specific Files in Android">best practices about storing files</a>. In most cases your app-specific folder is the best choice for recorded files.</p>
<h3>What could go wrong?</h3>
<p>Now the order in which you call the methods of the <code>MediaRecorder</code> object is very important.  If you stick with the order of the code snippet above, all is fine. If not you will see one of the following exceptions or messages in your log file:</p>
<ul>
<li><strong>java.lang.IllegalStateException</strong><br />
Happens when you do not follow the order above, miss some important steps or when <code>prepare()</code> failed, but you continue anyway. The latter is where it is most likely to go wrong. You should only call <code>start()</code> when <code>prepare()</code> did exit without exceptions. Otherwise you will get an <code>IllegalStateException</code>. Since it is a <code>RuntimeException</code> you might not catch it and your app will force close. That&#8217;s where the <a href="https://developer.android.com/guide/topics/media/audio-capture.html" title="Android's documentation on audio capture">documentation sample code</a> is misleading.
</li>
<li><strong>mediarecorder went away with unhandled events</strong><br />
Happens when you release the Mediarecorder object while events were still being processed or queued. No need to worry, though. Everything went fine anyway &#8211; this message is just to notify you about this.
</li>
<li><strong>Fatal signal 11 (SIGSEGV)</strong><br />
That&#8217;s a really bad one. Not a Force close, but your app simply vanishes and then restarts. This segmentation fault can occur when you call <code>release()</code> and still use the object afterwards.<br />
Can also happen if you call <code>reset()</code> on a <code>MediaRecorder</code> object that hasn&#8217;t even been prepared. The next method call on the <code>MediaRecorder</code> object will cause the segmentation fault to occur.
</li>
</ul>
<p>An example of what could go wrong: I tried to optimize above code by just calling <code>reset()</code> at the start of the method when the recorder object already exists. All nice and dandy if never ever anything goes wrong. But if for example the prepare stage goes wrong, this optimization fails miserably (segmentation fault again). That&#8217;s why I got rid of it and now simply call <code>release()</code> before creating a new <code>MediaRecorder</code> object.</p>
<h3>Stopping the recording</h3>
<p>With stopping you have to follow the ordering of the state chart in <a href="https://developer.android.com/reference/android/media/MediaRecorder.html" title="Documentation of MediaRecorder containing a state chart">MediaRecorder&#8217;s documentation</a> again. But since there are only two steps, this is easy:</p>
<pre class="brush: java; title: ; notranslate">
private void stopRecording() {
   if (recorder != null) {
      recorder.stop();
      recorder.release();
      recorder = null;
   }
}
</pre>
<h3>Releasing resources</h3>
<p>When everything is done, you have to release resources. You should do so in the <code>onPause()</code> method of your activity, as you can see in the next snippet:</p>
<pre class="brush: java; title: ; notranslate">
protected void onPause() {
   super.onPause();
   if (recorder != null) {
      recorder.release();
      recorder = null;
   }
}
</pre>
<h3>Summary</h3>
<p>You have seen how to leverage the <code>RECORD_SOUND_ACTION</code> action to use an intent for recording. Since this intent is not always available, or because you might want to present another UI, you can also use the <code>MediaRecorder</code> framework directly.</p>
<p>There is an even more fine-grained way to record audio in Android by using <a href="https://developer.android.com/reference/android/media/AudioRecord.html" title="Documentation of Android's AudioRecord class">AudioRecord</a>. This class allows you to deal with raw audio data. I will not go into this since it should be of interest only to few developers.<br />
<img src="http://vg03.met.vgwort.de/na/9372ccad23994978ade7648216d0331e" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/recording-audio-using-androids-mediarecorder-framework/">Recording Audio using Android&#8217;s MediaRecorder Framework</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/yvOLqwvAYjk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/recording-audio-using-androids-mediarecorder-framework/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/recording-audio-using-androids-mediarecorder-framework/</feedburner:origLink></item>
		<item>
		<title>Adding Files to Android’s Media Library Using the MediaScanner</title>
		<link>http://feedproxy.google.com/~r/GrokkingAndroid/~3/w3q8MIiGUA0/</link>
		<comments>http://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/#comments</comments>
		<pubDate>Thu, 06 Sep 2012 10:02:20 +0000</pubDate>
		<dc:creator>Wolfram Rittmeyer</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[MediaScanner]]></category>
		<category><![CDATA[MediaScannerConnection]]></category>
		<category><![CDATA[MediaScannerConnectionClient]]></category>
		<category><![CDATA[onMediaScannerConnected()]]></category>
		<category><![CDATA[onScanCompleted()]]></category>
		<category><![CDATA[OnScanCompletedListener]]></category>
		<category><![CDATA[scanFile()]]></category>

		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=1473</guid>
		<description><![CDATA[<p>When you add files to Android&#8217;s filesystem these files are not picked up by the MedaScanner automatically. But often they should be. As far as I can tell from a cursory search through Android&#8217;s codebase, Android runs a full media scan only on reboot and when (re)mounting the sd card. This might sound bad at [...]</p><p>The post <a href="http://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/">Adding Files to Android&#8217;s Media Library Using the MediaScanner</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p>]]></description>
				<content:encoded><![CDATA[<p itemprop="description" class="first">When you add files to Android&#8217;s filesystem these files are not picked up by the MedaScanner automatically. But often they should be. </p>
<p>As far as I can tell from a cursory search through Android&#8217;s codebase, Android runs a full media scan only on reboot and when (re)mounting the sd card. This might sound bad at first &#8211; but think about it. A full scan is taking quite some time and you do not want this to happen arbitrarily, maybe even while the user is using his device heavily. </p>
<p>This means, any file, that must be available in the media library instantaneously, has to be added by you. You have the responsibility to get this right. Even more so, as new devices might support MTP, which means that all files &#8211; not only media files &#8211; have to made known. Read more about this in the section <a href="#mtp_section" title="Paragraph on MTP and what it means for making files known">&#8220;Not only relevant for media files&#8221;</a>.</p>
<p>If you want your files to be added to the media library, you can do so either by using the <a href="https://developer.android.com/reference/android/provider/MediaStore.html" title="Documentation of Android's MediaStore content provider">MediaStore</a> content provider, or by using the MediaScanner. In this post I deal with the MediaScanner only. In a later post I will cover how to use the MediaStore provider for making your files known.</p>
<h3>Adding the files using a broadcast</h3>
<p>The simplest way to do so is by sending a broadcast:</p>
<pre class="brush: java; title: ; notranslate">
Intent intent = 
      new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
</pre>
<p>This works perfectly well and you should be fine with this solution most of the time.</p>
<p>But if you want to be more in control of what is happening, you could use one of the following two methods.</p>
<h3>Using the static scanFile() method</h3>
<p>If you simply need to know when the files have been added, you could use <a href="http://developer.android.com/reference/android/media/MediaScannerConnection.html" title="Documentation of Android's MediaScannerConnection">MediaScannerConnection&#8217;s</a> static method <code>scanFile()</code> together with a <a href="https://developer.android.com/reference/android/media/MediaScannerConnection.OnScanCompletedListener.html" title="Documentation of MediaScannerConnection.OnScanCompletedListener">MediaScannerConnection.OnScanCompletedListener</a>. </p>
<p>The static method <code>scanFile()</code> is badly named, as it actually takes an array of paths and thus can be used to add multiple files at once and not just one &#8211; but it nevertheless does what we want <img src='http://www.grokkingandroid.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Here&#8217;s how to use this method:</p>
<pre class="brush: java; title: ; notranslate">
MediaScannerConnection.scanFile(
      getApplicationContext(), 
      new String[]{file.getAbsolutePath()}, 
      null, 
      new OnScanCompletedListener() {
         @Override
         public void onScanCompleted(String path, Uri uri) {
            Log.v(&quot;grokkingandroid&quot;, 
                  &quot;file &quot; + path + &quot; was scanned seccessfully: &quot; + uri);
         }
      });
</pre>
<table>
<caption>Parameters for the static scanFile() method</caption>
<tr>
<th>Parameter</th>
<th>Use</th>
</tr>
<tr>
<td>context</td>
<td>The application context</td>
</tr>
<tr>
<td>paths</td>
<td>A <code>String</code> array containing the paths of the files you want to add</td>
</tr>
<tr>
<td>mimeTypes</td>
<td>A <code>String</code> array containing the mime types of the files</td>
</tr>
<tr>
<td>callback</td>
<td>A <code>MediaScannerConnection.OnScanCompletedListener</code> to be notified when the scan is completed</td>
</tr>
</table>
<p>The <code>OnScanCompletedListener</code> itself must implement the <code>onScanCompleted()</code> method. This method gets the filename and the URI for the <a href="https://developer.android.com/reference/android/provider/MediaStore.Files.html" title="Android's documentation of MediaStore.Files">MediaStore.Files</a> provider passed in as parameters.</p>
<h3>Creating an instance of MediaScannerConnection</h3>
<p>This is the most complex way to make your files known. But it gives you even more control. You need to implement the <a href="https://developer.android.com/reference/android/media/MediaScannerConnection.MediaScannerConnectionClient.html" title="Documentation of https://developer.android.com/reference/android/media/MediaScannerConnection.MediaScannerConnectionClient.html">MediaScannerConnection.MediaScannerConnectionClient</a> for callbacks.  </p>
<p>Your <code>MediaScannerConnectionClient's</code> implementation is not only called whenever a scan has been completed, but also as soon as the connection has been established. Since this might take a little while, as described in the next section, you might be interested in this callback. The way the API is constructed, you actually need to use this callback method to start the scan. </p>
<p>The following snippet shows you a sample implementation of the <code>MediaScannerConnectionClient</code> interface.</p>
<pre class="brush: java; title: ; notranslate">
final class MyMediaScannerConnectionClient 
      implements MediaScannerConnectionClient {

   private String mFilename;
   private String mMimetype;
   private MediaScannerConnection mConn;
   
   public MyMediaScannerConnectionClient
         (Context ctx, File file, String mimetype) {
      this.mFilename = file.getAbsolutePath();
      mConn = new MediaScannerConnection(ctx, this);
      mConn.connect();
   }
   @Override
   public void onMediaScannerConnected() {
      mConn.scanFile(mFilename, mMimetype);
   }
   
   @Override
   public void onScanCompleted(String path, Uri uri) {
      mConn.disconnect();
   }    	
}
</pre>
<p>In this implementation I create the <code>MediaScannerConnection</code> within the constructor and here I also call its <code>connect()</code> method. </p>
<p>Note also that I start the scan within the <code>onMediaScannerConnected()</code> callback method.</p>
<p>This way the usage of this interface is as simple as it can get:</p>
<pre class="brush: java; title: ; notranslate">
MediaScannerConnectionClient client = 
      new MyMediaScannerConnectionClient(
            getApplicationContext(), file, null);
</pre>
<h3>Establishing a connection might take a while</h3>
<p>Be aware that the connection is not established right away. That&#8217;s why the following snippet would cause trouble (that&#8217;s the first time I noticed problematic code in <a href="http://commonsware.com/Android/" title="Mark Murphy's excellent tome 'The Busy Coder's Guide to Android Development'">Mark Murphy&#8217;s otherwise highly recommended book</a>):</p>
<pre class="brush: java; title: ; notranslate">
/////// Do not do this ! ///////
MediaScannerConnection c = 
      new MediaScannerConnection(
            getApplicationContext(), null);
c.connect();
c.scanFile(file.getAbsolutePath(), null);
c.disconnect();
/////// Do not do this ! ///////
</pre>
<p>This snippet would fail with an <code>IllegalStateException</code>:</p>
<p><code>java.lang.IllegalStateException: not connected to MediaScannerService</code></p>
<p>When doing some tests it took on my Optimus One (with an sd card) and on my Galaxy Nexus (with an extra partition) about 20 to 40 milliseconds to establish the connection &#8211; on my Archos tablet (also extra partition) about 100 milliseconds. </p>
<p>The scan itself takes even longer &#8211; which took me by surprise. On my Archos and Optimus One about 200 milliseconds &#8211; on my Nexus even up to 900 (!) milliseconds on its worst run.<br />
<a name="mtp_section"></a></p>
<h3>Not only relevant for media files</h3>
<p>With devices that use <a href="http://en.wikipedia.org/wiki/Media_Transfer_Protocol" title="Wikipedia's description of MTP">MTP</a> instead of the traditional USB storage protocol, the MediaScanner is also used to make arbitrary files accessible via MTP. Thus any files and folders that you do not add to the MediaScanner are invisible between full scans if you plug in your device to your computer!</p>
<p>With the introduction of Honeycomb Google has started to push for MTP. Even if not all handset makers follow Google&#8217;s decision, some might &#8211; and Google&#8217;s own Nexus line definitely does so.</p>
<p>This means that you should use the MediaScanner also for any files that the user might want to download to his computer. It could be anything, e.g. CSV backup files, PDF files and so on. If the user might want to use them on a traditional computer, you have to make these files known using the methods described above. </p>
<p>Happy coding!<br />
<img src="http://vg03.met.vgwort.de/na/96745308bb7a444c83698feec0d744c3" width="1" height="1" alt=""></p>
<p>The post <a href="http://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/">Adding Files to Android&#8217;s Media Library Using the MediaScanner</a> appeared first on <a href="http://www.grokkingandroid.com">Grokking Android</a>.</p><img src="http://feeds.feedburner.com/~r/GrokkingAndroid/~4/w3q8MIiGUA0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.grokkingandroid.com/adding-files-to-androids-media-library-using-the-mediascanner/</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Object Caching 2150/2315 objects using disk: basic

 Served from: grokkingandroid.com @ 2013-05-16 02:57:55 by W3 Total Cache -->
