Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

December 20 2013

20:21

Il fallimento del progetto Android: quando nel 2007 Google dovette ricominciare tutto da capo

La storia è comparsa oggi sul magazine The Atlantic a firma di Fred Volgestein. Riguarda un retroscena curioso della guerra segreta tra i giganti della tecnologia d’oltre oceano. I protagonisti sono Google e Apple.

Nel 2005 Google aveva iniziato a lavorare a un’iniziativa segreta chiamata Progetto Android. Nascosti in un’ala al primo piano dell’edificio 44 del quartier generale di Google, un team di quattro dozzine di ingegneri pensavano di essere sulla buona strada per offrire al mercato un dispositivo rivoluzionario che avrebbe cambiato l’industria della telefonia mobile per sempre.

Il prototipo del primo dispositivo Android era senza touch screen e molto simile ai cellulari dell'epoca.

Il prototipo del primo dispositivo Android era senza touch screen e molto simile ai cellulari dell’epoca.

Nei due anni successivi gli ingegneri di Google coinvolti nel progetto avevano lavorato dalle sessanta alle ottanta ore a settimana alla scrittura del codice e al test. Si erano occupati della negoziazione delle licenze software necessarie, avevano volato in lungo e largo in tutto il mondo per trovare i giusti partner per il progetto tra fornitori e produttori di hardware. Negli ultimi sei mesi del 2006 avevano lavorato al prototipo, pianificando la presentazione del dispositivo entro la fine dell’anno. Sarebbe andato tutto bene se non fosse stato che il 9 gennaio 2007, quando ormai il progetto Android era in dirittura d’arrivo, Steve Jobs salì sul palco e svelò l’iPhone.

La reazione di Chris DeSalvo (ex ingegnere del Team Android) davanti l’iPhone fu immediata e viscerale. «Come consumatore sono rimasto senza parole. Ne volevo immediatamente uno. Ma come ingegnere di Google, ho pensato: “dobbiamo ricominciare tutto da capo”».

Steve Jobs presenta il primo iPhone, era il 9 gennaio 2007.

Steve Jobs presenta il primo iPhone, era il 9 gennaio 2007.

Per la maggior parte della Silicon Valley – tra cui la maggior parte di quelli che lavoravano in Google – la presentazione dell’iPhone è stata un grande evento. Steve Jobs aveva ancora una volta fatto l’impossibile. Quattro anni prima aveva convinto un settore intransigente come quello dell’industria musicale nel pubblicare le canzoni sul catalogo di iTunes per novantanove centesimi a pezzo. Ora aveva convinto un carrier wireless per collaborare alla realizzazione di uno smartphone rivoluzionario. Peccato che non tutti avessero accolto la novità con lo stesso entusiasmo. Per il team del progetto Android, l’iPhone fu un vero e proprio calcio nello stomaco.

Dice DeSalvo:

«Quello a cui avevamo lavorato per anni e che ora ci ritrovavamo tra le mani, confrontato all’iPhone, sembrava improvvisamente così troppo… anni novanta. Non ce ne saremmo mai resi conto se non l’avessimo visto».

Il pezzo completo è disponibile su The Atlantic. Leggetelo perché vi da il senso del “terremoto” che causò l’iPhone nell’industria di allora. E di quanto, quel prodotto che oggi tutti ben conosciamo, che sembra così ovvio e scontato, avesse segnato una vera e propria rivoluzione epocale.

December 11 2013

14:19

9 Essential Apps For Your Android Tablets

In the last few months, we have seen so many new and latest iPads, tablets and smartphones that were introduced in the market. All these latest iPads and tablets offer so many amazing features and awesome applications. These days Windows 8 tablets, Android tablets and iPads are very famous and popular in the market. Android tablets are so much popular these days that various companies are producing different types of Android tablets. An android tablet offers some really cool and superb applications.

If you are searching for some essential and cool apps for your Android tablet; then have a look at this collection. In this collection, you will see some awesome and essential applications for your Android tablets. These entire apps are easy to use and when you use these apps it will be the fun. So check this out and get to pick one. And do let us know what you feel about this round up.

Evernote

Evernote is an easy-to-use, free app that helps you remember everything across all of the devices you use. Stay organized, save your ideas and improve productivity. Evernote lets you take notes, capture photos, create to-do lists, record voice reminders–and makes these notes completely searchable, whether you are at home, at work, or on the go.

Flipboard: Your News Magazine

Flipboard brings together world news and social news in a beautiful magazine designed for your Android phone and tablet. Once you pick a few topics, your Flipboard is built and you can instantly start flipping through the pages of news you care about and stories and photos friends are sharing. And with Flipboard 2.0, when you find things that you want to save for later or collect into your own ‘magazine’ on Flipboard, just tap the “plus” + button on any item.

ASTRO File Manager with Clouds

ASTRO Cloud & File Manager has over 70 million downloads worldwide! Organize, view and retrieve all of your pictures, music, videos, documents or other files regardless of where they are located.

Google Drive

With Google Drive, you can store all your files in one place, so you can access them from anywhere and share them with others.

CamCard – Business Card Reader

CamCard reads business cards and save instantly to phone Contacts. It syncs all your cards across smartphones, tablets, computers and the web app.

Cloud Print

With Cloud Print for Android you can: Print from any compatible Android device to any Google Cloud Print connected printer, Share a picture or a document from apps like Gallery directly to Cloud Print, Track the status of your print jobs.

Kindle

Sync Your eBooks—The Kindle app lets you read the same book across devices and automatically syncs where you left off so you can start reading on one device and pick up where you left off on another device. The app syncs your furthest page read, bookmarks, notes, and highlights between Android, PC, Mac, iPad, iPhone, iPod touch, BlackBerry, Windows Phone 8, and any of our Kindle devices using our Whispersync technology.

DoubleTwist Music Player

New update brings Android KitKat support and a beautiful new UI for tablets & phones! Are you tired of using multiple apps for syncing and listening to music, radio & podcasts? With over 80 thousand 5 star ratings, doubleTwist Music Player is the best all-in-one podcast, radio, sync and music player app.

Kingsoft Office

Kingsoft Office is the only mobile Office with full-features FREE. Support for running on Android 2.1 and above system. User-friendly & nice UI interface! Users from over 200 countries and regions around the world are using it. The Average Rating of Kingsoft Office is up to 4.6 stars! Whether in a small cell phone screen or on a large screen on the Tablet, Kingsoft Office has a superior performance!

June 04 2013

14:40

Android Stencil Kit: il kit indispensabile per disegnare su carta le vostre App Android

Si chiama Android Stencil Kit ed è prodotto da UI Stencil. E’ una griglia di metallo con tanto di matita e block notes dedicati per poter rappresentare su carta il prototipo delle vostre App Android. Se sviluppate sulla piattaforma di Google non potete farne a meno. Per gli affezionati di Apple invece c’è anche la versione per iOS.Costa 28,95 $ e potete acquistarlo sul negozio ufficiale.
DETTAGLIO
La griglia in metallo
BOX
La confezione con matita e griglia

May 30 2013

15:52

Fries: Free Framework for Developing Android Apps Using HTML, CSS and JavaScript


  
fries-homepage-w550

Fries by Jaune Sarmiento just reached version number 1.0. The project offers a framework for the development of web apps in the look and feel of native Android apps. If you are familiar with Android’s UI from version 4 on, you will definitely know your ways around, once you get a hold of Fries. In its current iteration, Fries is optimized to cooperate with PhoneGap, thus letting you build native Android experiences.

May 13 2013

20:17

Facebook Home: un flop annunciato

Le premesse sembravano grandiose. Le voci circolavano da mesi. Mark Zuckerberg avrebbe dovuto presentare uno smartphone nuovo di zecca targato Facebook. Pochi giorni prima dell’evento dello scorso 4 aprile, i rumors si erano però ridimensionati di brutto. Così tanto che quando abbiamo visto Zuckerberg che giocherellava con Facebook Home, in tanti ci siamo chiesti se non fosse una specie di scherzo di cattivo gusto.

L’idea poteva anche suscitare un pizzico d’interesse. L’entusiasmo si è però spento subito. Giusto il tempo d’istallarlo, provarlo per un paio di minuti e non vedere l’ora di liberarsene. La realizzazione di Home è pessima. Secondo le statistiche del Play Store di Google è stato scaricato più di un milione di volte. Se vi sembrano tante, Mark Zuckerberg qualche tempo fa aveva dichiarato:

«Mettiamo anche che realizziamo un telefono e otteniamo come risultato che 10 milioni di persone lo usino, per noi non sposterebbe l’ago della bilancia. Facebook ha un miliardo di utenti».

Figuriamoci con un software che fatica a raggiungere appena il milione di download. Che figuraccia.

L'HTC First presentato il 4 aprile 2013, ha venduto appena 15.000 unità.

L’HTC First presentato il 4 aprile 2013, ha venduto appena 15.000 unità.

Su una scala da 1 a 5 il punteggio medio con cui il launcher di Facebook è stato valutato dagli utenti è 2,2. Imbarazzante. Ma il peggio è che l’HTC First, lo smartphone con Facebook Home preinstallato, che HTC ha presentato il 4 aprile, sarà ritirato dal mercato in tempi record. Le vendite sono vergognosamente basse. Appena 15,000 unità vendute nonostante gli sforzi dell’operatore AT&T che, pur di liberarsene, lo ha piazzato ad appena 0,99$. Si avete letto bene. Meno di un dollaro. Niente da fare. E vi ripropongo quello che avevo scritto all’epoca sull’HTC First:
«Verso la fine ha fatto la sua comparsa lampo sul palco Peter Chou, CEO di HTC. Teneva in mano l’HTC first, il primo smartphone Android che monterà nativa l’interfaccia “Home” di Facebook. Ha parlato sì e no per trenta secondi. Non pareva granché contento. Magari si stava chiedendo cosa ci facesse lì e se di quel terminale ci fosse poi un così gran bisogno».

May 03 2013

11:58

No Matter of Luck: What To Consider In Mobile App Development [Infographic]


  
MobileAppDevIG_teaserl

There are gazillions of mobile apps out there. If you are looking for a specific use case or - not - you won't see any shortage in what you will be able to find. Thus, releasing a mobile app is not without risks. You need to create something outstanding to attract the users. But how do you know? How can you improve? Sure, you can always wait for shit storms to wipe away your Facebook page or you can rely on these nice one-star-ratings in app stores. Did you know, that 60 % of all apps in Apple's App Store have not once been downloaded. If I were you, I'd try to find alternatives to hoping and waiting (and failing) ;-)

March 20 2013

21:42

Google lancia Google Keep e sfida Evernote

Google ha appena lanciato Google Keep un servizio che permette di creare to-do list, salvare note testuali, audio e video e sincronizzarle attraverso Google Drive su tutti i dispositivi in modo tale da tenerle sempre a portata di mano. Sul blog ufficiale viene presentato con “Save what’s on your mind”.

L'interfaccia di Google Keep sul Nexus 4

L’interfaccia di Google Keep sul Nexus 4

Il nuovo arrivato in casa Google è una specie di clone di Evernote che qualche settimana, a causa di un attacco hacker, ha richiesto un password reset forzato per 50 milioni di utenti.

L’interfaccia di Google Keep è semplice e piacevole, in linea con il nuovo stile adottato da Google sia a livello desktop che su smartphone. Il servizio aggiunge una funzionalità interessante alla galassia dei servizi Google di cui al momento si sentiva la mancanza. Google Keep è attualmente disponibile solo per dispositivi Android ma non tarderà ad arrivare su iOS.

June 22 2012

02:57

Upcoming: Google IO

At Google IO June 27-29 the Android platform will be on display. Direct from a recent slamdown legal court grudge win against Java steward Oracle, the Android crew will be able to tell you  about what is new and what is upcoming in Android, how you can monetize Google apps, multiversioning and more. Much will be available in webcast streaming format. Be square or be there or be there virtually.

April 19 2012

08:01

Design on the Go: Designer Apps for Android


  

As smartphones have advanced, and the display and photo capture technologies have improved, many have desired the ability to design and to edit images on their mobile phones. In fact, today hundreds of design applications exist on Google Play (previously known as Android Market). So in order to help you sift through the noise to find the ideal one for your needs, we decided to take a look at our top twenty designer apps for Android.

1. Adobe Photoshop Express

Photoshop express is an application based around the hugely successful computer program of the same name, but now adapted to mobile phone use. Though the app doesn’t have all the functions available on the PC version, it remains extremely popular for a wide range of photo editing functions.

2. WordPress Mobile

WordPress Mobile is a simplified version of the popular website blog managing software, which enables users to update, edit and create new websites straight from their smartphones. Ideal for any person who requires round the clock updates for their websites.

3. Color Dictionary

This useful application enables users to search and discover a variety of colors that can then be used in different design purposes. The Color Dictionary app can identify a color, or allow the user to select a color on a slider, and it will then apply a name to that color. Handy for all sorts of uses, whether choosing a website background or what color paint to buy for decorating your house!

4. ColorSnap

Similar to the Color Dictionary app, ColorSnap can capture colors from photos taken by your Android phone’s camera or pics from your library and identify them by matching to Sherwin-Williams‘ paint colors. The app is optimized for MDPI and HDPI phones and has never been tested on LDPI devices. It’s said to work well on old devices like the HTC Droid Incredible or the LG Ally, however, according to users’ reports, it doesn’t work well on Samsung’s Galaxy Nexus.

5. Color Mood Designer

In case you don’t like Color Dictionary and ColorSnap, Color Mood Designer is another app you can use to find the right color combination for your design project.

6. Finger Colors

The title of this app can make you think it’s another color-choosing app, but no, it’s actually used for painting and drawing with a user-friendly interface that won’t distract or interrupt you. The Finger Colors app enables you to set the width, transparency and color of your strokes, so you can draw or paint almost anything you want, including oil and watercolor paintings (well, digital ones).

7. Autodesk SketchBook Express

Similar to the previous apps, Autodesk SketchBook Express is a painting and drawing application with a huge range of useful tools. It works on smartphones that support multi-touch and run Android 2.1 or above; a powerful processor with a good amount of RAM will make the app run faster, but you can use it on mid-range devices like the Samsung Galaxy Ace, too.

8. Fotolab

Fotolab is an application that specializes in enabling users to alter the effects and colors of an already taken photo. Selective color draining, blurring and effect creating are all available, plus more. The app is easy to use, and even allows the user to set an initial effect and then add patches for alternative effects with just the press of a finger.

9. Photo Effects

Photo Effects provides the ability to apply numerous effects to your photos. Whether it be thermal, fisheye, hazed or pixelated, this application can provide the edit that you require. Normal edits can be made to improve photos, or they can be made entirely wacky! Easy to use and control.

10. Reduce Photo Size

Reduce Photo Size does exactly what it says on the tin. It can be used for editing image sizes, but its main use is to compress the actual file size. Many find that storing multiple images on their phone can deplete their memory rapidly, and so this app could be a useful solution to such a problem.

11. Photaf Panorama

This application enables easy arranging of panorama-style shots. While Android 4.0 is likely to provide this function itself, anyone who requires panorama creation without the new operating system will want to use this easily controlled app.

12. BeFunky Photo Editor

BeFunky is one of the most popular online photo editing programs, and now it’s available on Android, too. You can use the app to edit photos, apply different effects or add frames from the big collection it offers.

13. PicsArt – Photo Studio

PicsArt is one of the best and most complete photo editing apps that can be found on Google Play for free. You can use it not only for editing pics and applying effects to them, but also for drawing and sharing the works and the edited pics via Facebook, Flickr, Tumblr and a number of other social networking sites. It also adds new features to your smartphone’s camera and gives you the opportunity to take photos with effects the standard features don’t include.

14. Photo Enhance

Photo Enhance is another good photo editor to easily adjust brightness, contrast, balance and colors of your photos and make them look more detailed, as if they were taken with a very cool camera.

15. Dash of Color

Many users look for apps that turn usual pics into black-and-white ones. But if you’re looking for just the opposite, Dash of Color will help you add colors to any kind of black-and-white photo. You can also use this app to convert any image to a black-and-white one and then add some selective colors of your own choosing.

16. Fontroid

Most designers have to deal with fonts, and Fontroid is an app that can be useful in that arena. It enables you to draw and create your own fonts, upload them and share with your friends/colleagues. The best fonts become available for download from the official website in TrueType format.

17. Photo Grid

With Photo Grid by RoidApp you can turn your photo galleries into collages and easily add thumbnail photos for them. This is one of the most popular apps on Google Play with a huge number of positive user reviews, so you might find it worth trying.

18. Gallery+

Gallery+ is an application that provides greater flexibility for gallery organization for the images on your phone. Android has been criticized in the past for not enabling this on the operating system supplied gallery, and so Gallery+ has attempted to rectify this in order to make the organization of photos more convenient. Features that brighten up the backgrounds and style of the albums also exist.

19. PicWorld

PicWorld is a highly rated application that enables easy search of images across the Internet, using a variety of filters. Whatever photo you’re searching for on your mobile, PicWorld is likely to produce great results compared to manually searching through an Internet browser search engine.

20. HP e-print

This app, brought to you by the computing giant Hewlett Packard, enables easy printing of documents that are stored on your Android phone. Rather than needing to transfer the file from phone to computer and then to printer, the app enables the user to print straight from the mobile. Saving time and headaches.

That’s a Wrap

So what are your favorite design related and image editing apps for Android, either ones that made the list or those that didn’t? Feel free to leave us your thoughts in the comment section below. We look forward to hearing your two cents.

(rb)

March 17 2012

10:00

16 Android Applications to Help You Manage Your Day Better

Freelancers are always working. There is usually something that needs to be done, be it an email that needs sending or research for a project that you should be working on. If you are a freelancer with an Android phone, you can easily manage your day and some of your work flow while you are away from your desk.

Below are a bunch of free or low-cost Android applications to better help you manage your daily to-dos. While these applications are a few of hundreds of thousands available, the applications in this list have been chosen for their ease of use and/or integration with programs and web services you may already be using.

Calendar apps

1. Business Calendar

Business Calendar is my Android calendar of choice. Some of the features that won me over are the easily adjustable calendar views. To get from month view to week view, just swipe your finger over that week.

Want to expand or shrink the number of days in week view, use the slider at the bottom of the screen. Also at the bottom of the screen, you can see all of the calendars synced to your phone. The calendars can be hidden by touching the calendar name.

The free version offers 75% of the functionality of the paid app. The paid app offers different widget options and (the reason I bought it) drag and drop appointment changes.

2. Calengoo

Calengoo is a very popular calendar among business folks. While there is no free or lite version, you get many super cool features. Drag and drop appointment management, widgets, icons to better differentiate events. Calengoo lets you send an event or a whole calendar as an ICS file so others can easily import events to their calendar application.
Syncing your Google Tasks is unique to most calendar applications. In most cases you will need a separate task application like the task apps listed next.

Managing Tasks

3. Tasks n Todos

Tasks n Todos is a very easy to use to-do list application for Android. You can drag and drop to rearrange lists. There is a backup function so you can save your tasks to your SD card. There is voice input for the tasks easily accessible from the bottom of the tasks screen. There is a handy option to add pictures or even maps to a task.

4. Astrid Free

Astrid is a wildly popular task management application for Android devices and also iPhones. Astrid is a little different because you can access Astrid from the web as well as through your mobile app. A cool feature is being able to forward emails from your synced Gmail address and turn them into a task.
For a fee, you can get add-ons for Local and what they call the Astrid Power Pack. The power pack gives you different widget choices and adds voice input.

Storage

5. Box

Box is an application that is growing on me. I have to admit I only downloaded it initially because they are giving Android users 50gb free. I am liking the way it fits my basic mobile backup and sharing.

6. Dropbox

Dropbox is the go-to cloud storage for many people, myself included. There are a ton of add-on applications when you use the Windows desktop program. Aside from the potential additions, Dropbox just added instant upload of camera pictures and videos.

Social networking

7. Hootsuite

Hootsuite is used by a lot of companies and individuals alike. The main feature that separates Hootsuite for Android over most of the others is scheduling updates. You can set an update to Tweet and post to Facebook and other networks hours, days or months down the road. You can also set up what would be columns in the web version to track a hashtag while on your phone.

8. Tweetcaster

If you just want to use an app for Twitter, Tweetcaster is great. Accessing multiple Twitter accounts, the strong search function and having access to manipulate your Twitter lists are all advantages over many other Twitter only apps. The paid version lets you access Facebook features too.

On the phone

9. Google Voice

Google Voice is basically a Gmail inbox for your phone. You can SMS and receive your voicemail from a separate Google Voice number right on your Android phone. Having a separate “office”number is handy to have. Then you aren’t giving your mobile out to all of your clients.
Google voice will transcribe your voicemails and also offers a send to SPAM feature for those people who just wont stop calling.

10. Call Reminder Notes

Call Reminder Notes is an app for the forgetful. If you have ever called someone and forgot why you called them, this Android application is for you. Set reminders to call someone in your contact list at a specific time or set a reminder note to pop up on the screen next time you talk to them. Either way, your phone usage will be more productive.

SMS Add-ons

11. Txt Msg Away Message

Many people are so accustomed to sending a quick text message if they need a quick simple response. When you have a few people texting you every hour, it is a big distraction. Txt Msg Away Message will auto reply to the sender with a canned response letting them know you are working. You can have several canned replies, all for different occasions.

12. SMS Backup +

SMS Backup + is a great way to back up your text messages. In the settings, you can choose to have all of your messages back up automatically as often as every 30 minutes and incoming messages as quickly as 1 minute after they arrive.

The coolest part is, the messages and call log back up to your Gmail account. They are added to a label for easy access later. All of the times and attachments will show up, so will the duration of the calls.

Note taking

13. Evernote

Evernote is a fantastic note taking application with a ton of options. It is more like an information catch-all. You can upload files and images and be able to access them later. One of the coolest features, in my opinion, is the ability to search for text within an image. This means, you can take a picture of a business card and use Evernote to search for any bit of information on that card.

14. ColorNote Notepad

Starting to use ColorNote is a smooth transition for people who are Post it note addicts. The application works pretty much how you would use a paper sticky note. There are widgets you can paste you your screen. The widgets let you add a note fast.

Changing the color of the notes makes it easier to separate the notes by topics or information on the note.

Financial

15. Expensify

Expensify lets you handle items that would normally be a pain in the neck to manage… your expense report and receipts. When you buy something, instead of carrying that receipt trying to remember to log it in your financials for 3 days before you lose it, you can snap a picture of it. Uploading the receipt image and associating the receipt with a particular project.

Another good feature is the mileage tracker. Tracking your travel mileage is one place where most people fail to keep good records. There are 3 options, the easiest is to let the GPS track your route.

16. Square

Square is one of the most popular payment taking applications out there. Plug in a card reader into the headphone jack of your Android phone and swipe their credit card. The funds will take a couple of days to land in your bank account. If you do on-site work for clients, accepting payment on the spot is a must have.

Final thoughts

In the end, a tool is only useful if you use it. While you may have an Android phone for other reasons, you can sure make your life easier by adding a few applications to better manage your activities during the day.
What applications do you have on your Android to better manage your busy day?

February 19 2012

16:33

Android 5 è in arrivo: ma Android 4 che fine ha fatto?

Potrebbe arrivare in estate o addirittura prima. La versione 5 del sistema operativo mobile di casa Google, nome in codice Jelly Bean, potrebbe spiazzare tutti quanti e relegare il suo predecessore, Ice Cream Sandwich, ad una sfortunata comparsata. Peggio di quanto abbia fatto Microsoft a suo tempo con Windows Me o Windows Vista con l’unica differenza che Android 4 merita, eccome.

Reso disponibile a novembre 2011, Ice Cream Sandwich è passato più o meno inosservato: a quattro mesi dal lancio gira su meno dell’1% delle device Android attualmente in circolazione.

Molti smartphone delle maggiori case produttrici non lo supportano. L’aggiornamento sui prodotti di punta tarda ad arrivare. Per alcuni dispositivi, come il Galaxy Note e il Galaxy SII di Samsung si parla (forse) a marzo. Per i più sfortunati possessori di LG addirittura settembre 2012.

E questo è un norme peccato, perché lo provo da mesi sul nuovissimo Galaxy Nexus ed è davvero un salto epocale rispetto ai suoi predecessori che vi fa dimenticare l’iPhone e iOS.

Il ritardo nell’adozione di Ice Cream Sandwich è intollerabile in un mercato in così rapida evoluzione. Google dovrebbe costringere i produttori a forzare le loro tabelle di marcia e favorire la diffusione dell’innovazione del software con tempi compatibili a quelli di mercato.

Spesso i produttori spendono inutili energie a snaturare l’esperienza d’uso originaria di Android, adattandoci sopra una UI proprietaria, per distinguersi in qualche modo dagli altri concorrenti. I tempi così si allungano e gli aggiornamenti tardano arrivare.

Tant’è che Andy Rubin presenterà Android 5.0 durante la Google I/O conference 2012 prevista per fine giugno. Per allora i numeri della diffusione di Android 4 non saranno molto più grandi degli attuali.

Peccato per Ice Cream Sandwich. Un’occasione sprecata. Spero solo che per Jelly Bean non sia lo stesso.

February 07 2012

20:33

Google Chrome sbarca in beta sugli smartphone Android

Dopo una lunghissima attesa, Google ha finalmente rilasciato una versione beta del suo popolarissimo browser per i computer destkop sui dispositivi mobile che supportano Android. E così, oltre al nuovo Android 4 Ice Cream Sandwich, Google aggiunge un nuovo importante tassello all’insieme di prodotti dedicati agli smartphone che portano il marchio di Mountain View.

Una volta installato il browser sullo smartphone, Chrome permette di sincronizzare automaticamente, tramite l’accesso al profilo Google dell’utente, i segnalibri e la cronologia di navigazione già presenti nella versione desktop. Nonostante questa prima release sia ancora una beta, Chrome non delude le aspettative e si mantiene all’altezza delle prestazioni del fratello maggiore in termini di prestazioni e velocità.

Installato su un Galaxy Nexus e su un Galaxy Note l’app rende superflue tutte le altre applicazioni utilizzate fino a questo momento per navigare su internet. Al momento la versione beta è disponibile sul Market Android solo per gli utenti localizzati negli Stati Uniti e pertanto non è ancora accessibile dallo store italiano.

Tuttavia, senza alcuna fatica, è già possibile trovare decine di siti che mettono a disposizione il file .apk per scaricare il software e installarlo liberamente sul proprio smartphone Android. E visto che immagino non vedete l’ora di provarlo, eccovi il link: http://www.mirrorcreator.com/files/Q43VYNAK/.

December 23 2011

09:41

An Inspired Collection of Free Live Wallpapers for Android


  

Since we have been compiling wallpapers for our readers, we wanted to turn our decorating eye towards the Android series of devices as we have not had a dedicated wallpaper post for those users. Today we address this with a collection of wonderful live wallpapers specifically targeted at the Android line. These animated backgrounds have been a big draw for users since Android introduced them with version 2.1.

The problem many Android users run into is that there are so many of the live wallpapers out there and loads that are not very stable, or worse, just do not work. Then there are those which are somewhat uninspired. So we decided to sort through the hordes and bring our readers some of the cream of the crop. Below is a selection of backgrounds that we hope you will get some use out of. Or at least a little inspiration.

Get Live

White Christmas

Get it here!

Steampunk Skull

Get it here!

Captain America

Get it here!

Rotating Live Wallpaper

Get it here!

Nicky Bubbles Lite

Get it here!

Digital Wall

Get it here!

Butterfly Dream-Cool Free

Get it here!

Blooming Night

Get it here!

Biomechanical Bog Free

Get it here!

Christmas Tree

Get it here!

Melody

Get it here!

Biomechanical Skull

Get it here!

Summer Time Scene Lite

Get it here!

Lake View Scene Lite

Get it here!

Aquarium

Get it here!

Night Shadow Lite

Get it here!

Analogy Clock

Get it here!

Fractal Clock

Get it here!

Dandelion Field

Get it here!

Feng Shui Yinyang

Get it here!

Mystical Life Basic

Get it here!

WP Clock Light

Get it here!

NeonGears Basic

Get it here!

Mystic Halo

Get it here!

Musical Note

Get it here!

Sweet Tree Free

Get it here!

Love Creatures Lite

Get it here!

Celtic Garden Free

Get it here!

Pixel Rain

Get it here!

Ladybug

Get it here!

(rb)

December 20 2011

10:00

The Grim Future of Web Browsers

Nothing new appearing today in the IT world is labelled as a surprise, because everything moves so fast and at some point in time you start to know when the big news hit the market. With the technology advancing so fast, especially all the mobile devices we call smartphones today part of the mainstream and are, maybe, the most important thing in our lives. So by sending a message from your QWERTY Android device or by playing Fruit Ninja on your latest iPhone, have you ever thought that you yourself are changing the IT world?

Well if you haven’t, I can tell you for sure that you do. By using portable devices more often and desktop computers less the latest gadgets quickly become out of date. Without realizing we have become unplugged and do not need computers anymore – which also means we do not need browsers anymore. And why would we? At the end of the day we have our smartphones filled with apps that can keep us busy for a long time. Sometimes I don’t even check my Facebook from my computer, even if I am close to it, because it is much easier to do it from the phone. Ever since the IT world made it possible to connect to the internet wirelessly, nobody has looked back. People invest much more money today in phones and portable devices like tablets or eBook Readers than in computers.

Image by ~jeroen-tje

Internet without a Browser


It is easy to see how we’ve become unplugged. Apple’s iOS and Android do it; Adobe Flash Player 10.2 and AIR technologies as well. HTML5 starts becoming more popular and supported on many portable platforms and other companies like Blackberry or Nokia follow in close. There are over 400,000 applications in the App Store, an incredible growth from 500 in the beginning. Android has around 400,000 applications and the numbers are increasing. The year started with around 300,000 apps for both platforms and ends with, very possibly, close to 1 million of them. Android included Flash from the 2.2 Froyo version and this made the portable devices running on the open-source platform even more popular. And you know what the good part of this is? That you don’t need anything besides a WiFi or 3G/4G connection to access them from all over the World.

Why do we talk about apps when we’re talking about browsers? Because if you think about it, the applications are nothing less than websites which are accessed without a browser. And more than 10 million of them were downloaded in 2011. That’s a huge amount of users who accessed this information from a portable device, avoiding using a browser. And it should be a clear sign about the future of the web. The apps are more intuitive, faster and easier to use, therefore they are preferred to Chrome, Mozilla, Safari or any other application. Another advantage is that the apps can be accessed from everywhere, while for a browser you not only need internet, but also a computer.

Smartphone and the Internet


A smartphone will also always allow you access to the internet, so why have a big laptop when you can have a pocket device that can do the same? A study made two years ago concluded that by 2013 mobile browsing will be more popular than desktop browsing. With the usage of smartphones growing by 110% in the US in 2009 and by 148% all over the world, this seems quite possible. Also, the younger internet users get educated in the world of smartphones, meaning that the computer will mean even less for them than it does for us.

source: BettyArmado via Chrome Store

This could be great news for designers – up til now everybody had to have a webpage, soon everybody will have to have a mobile device version as well. More work, more money for the design industry. China for example is a huge industry with tremendous potential. Not many people there have tablets or smartphones, but many say in 3-4 years everyone there will own one. With a market of almost 1 billion mobile subscribers, there will be a huge need for mobile websites for the companies and business individuals. So, bottom line, the fact that web browsers are on a downhill is not that bad for us – we will still have a lot of work anyway.

Right now there are more than 300 million mobile internet users in China and this is around 60% of all mobile and desktop internet users all over Europe – we’re talking huge numbers here. We’re talking about the Chinese equivalent of eBay, Taobao on which the transactions for the last year totaled roughly $60 billion; and this is while eBay was delighted with a total of only $2 billion. All of these things happen while the major internet providers already update the speeds to 4G. You see where I’m heading? As designers, we might be concerned that our jobs will disappear in 15 years but really, who knows how many other challenges will appear for us by then?

However, the truth is that it always takes up to five years after a new web technology appears until people get a hold of it and learn how it really works. Smartphones are huge today, but I don’t think they reached their maximum potential yet. There is still a lot yet to come and just because we think we know everything, it doesn’t mean we actually do. Web browsers are still popular and widely used, but they will be a thing of the past at some point in time, because nothing lives forever on the web. There is no such thing as a technology which didn’t improve since it was released (unless it was released recently).

Conclusion


The bottom line of this article is that even if the browsers disappear in several years (or at least their use will decrease), there will still be a lot of work for designers and developers. The internet is almost fed up with designs and experts, in five years time it will all move on portable devices. This means, as stated before, much more work for us, both for desktop and portable devices. All the technologies will be available on portable devices as well at some point in time and designing for them will be maybe even more challenging than designing for desktop use.

The beginners of today are the experts of tomorrow. We all know what’s coming in the short term, so why not try to become better at this while letting the current experts do their work? Who knows, in five years it might be you who earns the big bucks from all kind of clients and, as its normal, there will be others taking your place in the “follower seat”. The increasing use of smartphones and tablets bring a new taste in the design industry, with many new challenges yet to come. Get ready to take on all of them!

December 09 2011

20:29

Perché Android uccide la concorrenza

Il titolo è provocatorio. Non me ne vogliate. Soprattutto ora che mi sono convertito da iOS al sistema operativo mobile di Google e finalmente, dopo tanto tempo, ho fatto pace con una fetta consistente di lettori di questo blog che smaniano per Android.

Niente di personale, intendiamoci. Le solite scaramucce da Apple fan contro tutto il resto del mondo. Io che vengo da Apple, io che solo iPhone, io che tutto il resto è noia.

Android mi piace, lo ammetto. Uso Gingerbread sul mio nuovo Samsung Galaxy Note e già smanio per Ice Cream Sandwich. L’ho provato su un Samsung Galaxy S2 e va che è una bellezza. Che poi il nome faccia schifo e suoni ridicolo è un altro discorso. Ma se guardate i dati aggiornati al terzo trimestre del 2011, circolano complessivamente 60,5 milioni di device mobile che supportano Android. Circa il 52% della quota di mercato complessiva. Un +23% rispetto allo stesso periodo del 2010.

Questa è la parte bella della storia. Poi però c’è il lato oscuro che ogni utente Android dovrebbe valutare. Quello che cogli all’improvviso quando entri da Mediaworld e ti aggiri tra i vari modelli di smartphone di ogni marca, indeciso su quale sarà il tuo prossimo smartphone o tablet dal cuore Android.

Da Samsung a Motorola, a Sony, a LG, a HTC, a Acer e tanti altri. Cambia il design, il colore, le dimensioni dello schermo, il logo del produttore. Ma ne provi uno, li hai provati tutti.

La stessa esperienza d’uso replicata identica, tale e quale su tutte queste device. È un po’ come se esistesse un unico produttore che commercializza tante device alternative con caratteristiche differenti per tante fasce di mercato ma, nell’anima, tutte uguali. E questo grazie ad Android o forse per colpa di Android.

Non basta l’hardware e il guscio esterno per differenziarsi e posizionarsi sulle vette del mercato. Apple ha fondato su questo principio tutta la sua filosofia e ha fornito all’utente il valore aggiunto di un’esperienza d’uso unica, integrata all’interno dei propri prodotti che è ben altra cosa dal mero circuito elettronico che li compone.

Android sta anestetizzando il mercato. I produttori non sborsano più un centesimo in ricerca e sviluppo per compilare un sistema operativo mobile fatto in casa. È un approccio ragionevole e in larghissima parte condivisibile. Resiste giusto RIM (BlackBerry) e poco altro, è caduta anche Nokia.

Un sistema operativo mobile non è una sfida da poco. Ci vogliono le competenze, le persone, i geni, gli smanettoni e nessuno di questi si trova così facilmente sul mercato. I tempi di realizzazione poi potrebbero essere proibitivi.

Allora è meglio adottare quello che già c’è e soprattuto funziona.
Si chiama Android.
Su tante device di tanti produttori differenti.
Tutte così diverse.
Tutte così uguali.

November 04 2011

13:52

Getting The Best Out Of Eclipse For Android Development





 



 


Getting into Android development can be quite a challenge, particularly if you’re new to Java or Eclipse or both. Whatever your past experience, you might feel tempted to start working away without checking that you’re making the best use of the IDE. In this article, we’ll go over a few tips, tools and resources that can maximize Eclipse’s usefulness and hopefully save you a few headaches. You might of course already be familiar with some (or all) of them and even be aware of others that we haven’t covered. If so, please do feel free to mention them.

I’ve used Eclipse for Java development on and off for a few years, having recently started learning Android casually. I’m surprised at the lack of easily digestible material online about basic aspects of Android development, such as the topic of this article. I’ve found some useful information out there in disparate locations that are not particularly easy to come across. Most of the online content is still in the official Android Developer Guide, but it has to be said that it is pretty limited in practical material.

The aim here, then, is to provide a concise overview of Android development tools specifically in Eclipse. If you’ve already started developing for Android, you will almost certainly have come across some of them, but a few might be new to you, especially if you’re learning Android casually or part time. If you’re approaching Android as a Java developer and are already accustomed to Eclipse, you’ll likely grasp this material well.

Get To Know Eclipse

Going over some features of Eclipse itself that would be useful for developing Android projects would be worthwhile. If you already know your way around Eclipse, you can probably skip these first few sections, because they’re really aimed at people who are learning to use the IDE purely for Android development. Later sections include tips on using Eclipse specifically for Android, so you might find a bit or two in there that you haven’t explored yet.

screenshot
The Eclipse IDE, with the “Hello Android” project open.

Eclipse has a huge amount of flexibility for creating a working environment for your development projects. Many display options, tools and shortcuts in Eclipse enable you to interact with your projects in a way that will make sense to you directly. Having been an Eclipse user for a reasonable amount of time now, I still discover features in it that I had no idea existed and that could have saved me a lot of hassle in past projects.

Explore Perspectives

The Eclipse user interface provides a variety of ways to view the elements in any project. When you open Eclipse, depending on which “perspective” is open, you will typically see the screen divided into a number of distinct sections. In addition to the code editing area, you should see various aspects of the project represented in particular “views.”

A perspective in Eclipse is a group of views arranged to present a project in a particular way. If you open the “Window” menu, then select “Open Perspective,” you will usually see at least two options: “Debug” and “Java.” The Java perspective will likely form the basis of your Android development process; but for debugging, there is an Android-specific perspective called DDMS. Once you have set a perspective, you can still make alterations to the visible views, as well as adjust the layout by dragging the view areas around to suit yourself.

In general, when developing Android projects, some variation of the Java perspective is likely to be open, with the option of a few additional views, such as “LogCat,” where you can send and read the runtime output of your app. The Dalvik Debug Monitor Server (DDMS) perspective will likely be useful when the time comes to debug your Android applications. The tools in this perspective come as part of the Android software development kit (SDK), with Eclipse integration courtesy of the Android Developer Tools (ADT) plugin. The DDMS perspective provides a wide range of debugging tools, which we’ll cover in brief later on.

Make Use Of Views

By default, the Java perspective contains the main area to edit code and a handful of views with varying levels of usefulness for Android projects:

  • Package Explorer
    This provides a hierarchical way to explore your projects, allowing you to browse and control the various elements in them through a directory structure.
  • Outline
    Displays an interactive representation of the file currently open in the editor, arranged as logical code units, which can be useful for quickly jumping to a particular point in a big file.
  • Problems
    Lists errors and warnings generated at the system level during the development process.
  • Javadoc
    Useful if you’re creating your own documentation using Javadoc or using other language resources that have this documentation.
  • Declaration
    Particularly useful if your Android projects have a lot of classes and methods. You can click on a variable or method in your code to see its outline here, and then click within the view to jump to the point where the item is declared.

You can open new views in Eclipse by selecting “Show View” in the Window menu and clicking from there. Many of the available views won’t likely be of any use to your Android project, but it is worth experimenting with them. If you open a view and decide that you don’t want to display it after all, simply close it. Adjust or move open views to different locations in Eclipse by clicking and dragging their edges or the tabbed areas at the top.

Java Views Relevant to Android Development

The ADT plugin for Eclipse includes a variety of resources for Android development within the IDE, some of which we’ll cover in the sections below. Eclipse has additional views for general Java programming, some of which naturally have a greater potential for usefulness in Android development but don’t appear by default in the Java perspective. In my experience, views that are useful for Android development include “Call Hierarchy,” “Type Hierarchy” and “Tasks.”

The Call Hierarchy view displays an interactive list of the calls for any particular method, class or variable, so you can keep track of where your code excerpts are being called from. This is particularly useful if you’re altering existing code and need a sense of what will be affected.

screenshot
The Call Hierarchy view for a method in one of my projects.

The Type Hierarchy view is relevant to Java projects that involve inheritance, which basically means that it’s relevant to all Android projects. Whenever you have a class that extends another class, this is inheritance and, thus, an instance when the Type Hierarchy view can be informative. If you’re not yet familiar with inheritance in Java, taking the time to at least read up on the basics is well worth it, because the technique is key to Android programming.

screenshot
The Type Hierarchy for a user interface element in an Android project.

The Tasks view is one I personally find helpful, but it really depends on how you choose to organize your projects. Think of the Tasks view as an interactive to-do list. For example, to add a task when you haven’t quite finished a particular bit of implementation but need to address something else right away, write a code comment, then right-click in the border area just to the left of the editor section, choose “Add Task,” and set your options from there. Once tasks are in a project, you can read them in the Tasks view, jumping to an individual task in your code by selecting it here. Tasks are also highlighted in the right-hand border of the editor.

screenshot
The Tasks view, with a random comment in the “Hello Android” project.

Android Debugging Views

The DDMS perspective contains several views for Android development and debugging. When you first open the perspective, you might feel a little overwhelmed, particularly because the views are all presented side by side in a rather convoluted arrangement. Chances are that once you learn the purpose of one, you’ll decide whether it’s relevant to your project; for a basic project, many of them will not be.

If you feel that closing some views would make the interface an easier environment to work in, then go ahead and close them; you can always open them again later. Starting simple is sometimes best, and then adding elements over time as they become relevant. In the early stages, your Android project is not likely to be complex anyway.

Let’s go through each DDMS view in Eclipse, with a brief note on its purpose and use. The information is tailored to each view and so is pretty varied, but includes device, memory and process management.

The Devices view provides an overview of your running AVD emulators together with processes in operation, and it is the starting point for exploring your projects for the purpose of debugging. This view presents shortcuts to some debugging operations, so you can select your app’s processes from here to see the other debugging operations in action. In most cases, you can view information in the other DDMS views by selecting a running process in the Devices view while your app is running in an emulator, then using the buttons at the top of the view to capture debugging information. When you do this, you’ll see some of the other views being populated with data.

screenshot
The Devices view, with a process selected for debugging.

The Allocation Tracker view is particularly useful for apps that have significant demands on performance. This view provides insight into how the Dalvik Garbage Collector is managing memory for your app. If you’re not familiar with garbage collection in Java, you might want to read up on it, as well as familiarize yourself with basic principles of efficiency in Java programming, such as variable scope.

screenshot
The Allocation Tracker view in the DDMS perspective.

The Emulator Control view enables you to emulate specific network contexts when testing your apps, allowing you to see how they function with varying constraints on speed, latency and network connectivity. A vital tool if your app depends on such external connections.

screenshot
The Emulator Control view with telephony settings.

The File Explorer view enables you to access and control the device’s file system (not the file system in your application’s structure as with the Package Explorer view). Using this, you can copy files to and from the device’s storage system; for example, in the case of an app storing data on the user’s SD card.

screenshot
Looking at the SD card directory on a virtual device using the File Explorer view.

The Heap view is another tool for analyzing and improving memory management in your app. You can manually control the Garbage Collector from this view. If you are unclear on how the constructs of your Java code relate to heap memory, this is another area you might want to read up on.

screenshot
The Heap view for a running app.

The Threads view enables you to access information about the threads running in your application. If you are unfamiliar with the concept of threads, then this view won’t likely be of use to you. Typically, an Android application runs in a single process on a device, but if you implement a deeper level of control over your app’s processing at the level of threads, then this view will be relevant.

screenshot
The Threads view for a particular running process.

The LogCat view is useful for most Android apps, regardless of their complexity. A variety of messages are automatically outputted here when you run your app, but you can optionally use the view as your own custom log. You can create log messages in various categories, including “Debug,” “Info,” “Warning,” “Error” and “Verbose,” which is typically used for low-priority information such as development trace statements. In the LogCat view, you can then filter the messages in order to quickly scroll to those you’re interested in. The messages are also color-coded, making them a little easier to absorb.

screenshot
The LogCat view as a virtual Android device starts up.

A DDMS perspective view can optionally be added individually to the Java perspective if you find it useful for development as well as debugging. Eclipse is designed to enable you to interact with the project’s elements any way you like, so don’t be afraid to experiment with the interface.

Exploit The Design Tools

The design tools in the ADT have undergone major improvements in recent releases, so if you’ve been disappointed by them in the past and perhaps opted for other tools to design your Android apps, having another look at them now is well worth it.

In the Graphical Layout view, you can view your designs with various settings for device software, hardware as well as orientation. The current version generally gives a greatly improved level of control over widgets, views and rendering than most previous versions. You can manage user-interface elements here using the graphical interface, rather than having to implement every aspect of your design in XML code.

screenshot
The graphical view of an app’s XML layout.

Design and Graphical Utilities

The ADT plugin update of June 2011 introduced a variety of visual refactoring utilities. While your XML layout files are open in the editor, you can browse the options in Eclipse’s Refactoring menu for Android, choosing from various labor-saving tools such as “Extract Style,” which provides a shorthand method of copying style attributes for reuse.

The Resource Explorer is a handy interactive way to explore your application’s resources without the hassle of searching the file structure in the “res” folder via the Package Explorer. Although not exclusively for design purposes, the tool is useful for checking what design resources are in your application’s structure. Depending on the app, your Resources directory might also contain menu, array, string and value items.

screenshot
The Resources Explorer showing the Resources directory for an app.

On the subject of resources, the Resources interface for any XML files in your app enables you to manage such data graphically, if you prefer not to handle the XML code manually. This can be an effective way to manage both elements and attributes for your application’s XML data.

screenshot
A graphical view of the XML file for arrays in an app.

Various visual interaction tools for XML resources have gradually been added and improved in the ADT plugin. For example, the Manifest file can also be viewed graphically when you want to control the tags in it, including “Permissions,” “Application” and “Instrumentation.”

screenshot
An application’s Manifest file, presented graphically.

Set Your Android Preferences

The “Eclipse Window” menu provides access to the Preferences settings for the environment as a whole, with a dedicated section for Android. You may have used this when you first installed the SDK but might not have been in there since then. It’s worth having a look through the options and experimenting with them to create the environment you want.

In the Android section, the “Build” settings include your saved edits to the project’s files, and they also point Eclipse to your keystore for signing the application. The LogCat section lets you set properties for appearance and behavior in the LogCat view. Other options include choosing properties for the DDMS, the code editors and the launch process for the emulator.

Use The Android Run Configuration Options

When you launch your Android project using the Run Configurations menu, you can choose from a range of additional options to suit the functionality of your app. With your Android project selected, choose the “Target” tab to see these options. The first section covers the more general launch parameters for the emulator, including control over speed and latency on the device. This feature is useful if your app depends on a network connection and you want to see how it functions with limited connectivity.

Emulator Command-Line Options

The “Target” tab also allows you to enter command-line options for the emulator that launches your app. Using these, you can tailor the appearance, properties and behavior of the emulator as it launches your app. A lot of options are here for various aspects of the device, including the following properties:

  • UI
    Includes scaling the display window and setting the DPI.
  • Disk image
    Includes the device’s SD card and cache memory.
  • Media
    Covers audio and radio properties.
  • Debugging
    Enables and disables specific debug tags.
  • Network
    In addition to network speed and latency, you can specify DNS and proxy servers.
  • System
    Includes slowing down the device CPU and setting the time zone.

For a full list, see the Developer Guide.

Choose Useful AVD Configurations

When you create virtual devices in Eclipse using the Android SDK and AVD Manager, through the “Window” menu you can choose various settings, including API versions and hardware configurations, such as the size of the SD card and screen, plus optional hardware components. The sheer range of options can leave you wondering where to start, but the feature at least gives you some idea of how your apps will look and function on various devices.

screenshot
Entering the details for a new AVD.

To create a virtual device, select “New,” enter a name and choose “Options.” You can edit your devices later if necessary. To start an AVD running, select it in the SDK and AVD Manager and click “Start.”

screenshot
Choosing from a variety of AVDs to start running.

Some developers prefer configuration options that match the range of Android devices currently in use, which obviously vary widely, with multiple phone sizes and types, not to mention tablets. There is no dedicated resource for finding this data, but a number of websites list these configuration details periodically, so you can do a quick Web search when testing an app for release to find the most current information.

It must be said that there is a real limit in value to using actual device settings, because the emulator is merely a guide: it doesn’t replicate the look and feel of different devices with any authenticity. These limitations are especially pertinent when you consider the third parties involved, such as HTC’s Sense interface, which will substantially alter your application’s UI. This is why testing on actual devices is also important, but that’s another topic. The range of devices running Android will obviously continue to expand, so the feasibility of covering a significant chunk of them becomes more and more remote.

Rather than focusing on actual devices in use, another way to approach the AVD configuration settings while you’re in Eclipse (i.e. when you’re still developing rather than testing) is to simply try to cover a range of settings and to explore particular hardware and software configurations that could affect your app’s functionality. Visually speaking, it goes without saying that a relative rather than fixed design will cope better with various screen sizes.

Get And Keep Yourself Acquainted With Developer Resources

As you’re by now aware, if you weren’t already, the Android Developer Tools plugin is what allows you to develop, run, test and debug Android applications in Eclipse, together with the software development kit. Like Eclipse itself, both the SDK and ADT plugins offer many tools, many of which you could very easily remain unaware of and only a few of which we have touched on in this article.

The Android development resources undergo regular updates. You might be one of those people who are always on the ball, but if you’re anything like me, you’ll rarely find the time to keep abreast of these developments, especially if (like me) Android development is not your full-time job.

The Android Developer Guide lists the various tools in the SDK, many of which you will not need to access directly, because the ADT plugin and Eclipse will handle interaction with them. But it’s worth browsing the list fairly regularly, just to be aware of the tools available. Even if you’re only getting into Android casually, these utilities can make an enormous difference to how productive and enjoyable your app’s experience is. The Android Developers Blog is another good source to keep abreast of developments.

The ADT plugin itself comes with a wealth of features and is regularly updated. The Android SDK Guide also has a page on the plugin, outlining versions and features; again, well worth checking out regularly, because there may be significant updates. Checking for updates in Eclipse through the “Help” menu is another good habit.

Android apps are, of course, extremely varied, so the utility of any given development tool is necessarily relative. Keeping a eye on updates to resources needn’t take up much time, because in many cases the updates will be irrelevant to you. But discovering the ones that are relevant could seriously improve your Android development efforts.

Following Best Practices

If you’re interested in developing a best-practices approach to managing and documenting your apps, check out Apache Maven, which uses the project object model (POM). If you’ve already used Maven for Java development in Eclipse, the Android plugin and Integration tools will enable you to adopt the same development practices for your Android app. You can learn more about Maven on the Apache website, and you can learn about getting started with it for Android on the Sonatype website.

Other Resources

Related Articles

(al)


© Sue Smith for Smashing Magazine, 2011.

July 11 2011

00:09

The power of intent tag discussed

Google developer advocate Paul Kinlan has detailed his recent work on a lightweight sharing facility using a very simple intent share protocol. Web Intents began life in 2010. Now, Kinlan and company are looking for feedback. Basically, his intent tag is intended to allow users to more easily mix and match favorite plug-in capabilities, freeing up developer effort in the meantime.

Resembling in some ways intent attributes in the Android framework, the Intent tag works by signaling to a browser the intent to handle a number of URIs. The tag is meant for spidering.

A user chooses a favored service – say, a ”red-eye remover” for photo editing. The service loads; Intent data gets passed. The system takes care of service resources.

While somewhat reserved in promoting the power of the intent tag, Kinlan still readily suggests that the Google project could ”fundamentally change and improve the way we build applications on the Web today…”

Behind the effort has been a determined push to keep the API very simple. Kinlan describes the effort in a recent blog entitled ”Web Intents: A Fresh Look” and points you to a prototype API on Github. Further details are on http://webintents.org/share.

June 30 2011

13:39

Designing For Android

Advertisement in Designing For Android
 in Designing For Android  in Designing For Android  in Designing For Android

For designers, Android is the elephant in the room when it comes to app design. As much as designers would like to think it’s an iOS world in which all anyones cares about are iPhones, iPads and the App Store, nobody can ignore that Android currently has the majority of smartphone market share and that it is being used on everything from tablets to e-readers. In short, the Google Android platform is quickly becoming ubiquitous, and brands are starting to notice.

But let’s face it. Android’s multiple devices and form factors make it feel like designing for it is an uphill battle. And its cryptic documentation is hardly a starting point for designing and producing great apps. Surf the Web for resources on Android design and you’ll find little there to guide you.

If all this feels discouraging (and if it’s the reason you’re not designing apps for Android), you’re not alone. Fortunately, Android is beginning to address the issues with multiple devices and screen sizes, and device makers are slowly arriving at standards that will eventually reduce complexity.

This article will help designers become familiar with what they need to know to get started with Android and to deliver the right assets to the development team. The topics we’ll cover are:

  • Demystifying Android screen densities,
  • Learning the fundamentals of Android design via design patterns,
  • Design assets your developer needs,
  • How to get screenshots,
  • What Android 3 is about, and what’s on the horizon.

Android Smartphones And Display Sizes

When starting any digital design project, understanding the hardware first is a good idea. For iOS apps, that would be the iPhone and iPod Touch. Android, meanwhile, spans dozens of devices and makers. Where to begin?

The baseline for screens supported by Android smartphone devices is the T-Mobile G1, the first commercially available Android-powered device, which has an HVGA screen measuring 320 × 480 pixels.

HVGA stands for “half-size video graphics array” (or half-size VGA) and is the standard display size for today’s smartphones. The iPhone 3GS, 3G and 2G use the same configuration.

T-mobile-g1-e1307550246584 in Designing For Android
T-Mobile G1, the first commercially available Android device and the baseline for Android screen specifications.

To keep things simple, Android breaks down physical screen sizes (measured as the screen’s diagonal length from the top-left corner to bottom-right corner) into four general sizes: small, normal, large and xlarge.

Two-mobiles in Designing For Android
Two common Android screen sizes. (Image from Google I/O 2010)

320 × 480 is considered a “normal” screen size by Android. As for “xlarge,” think tablets. However, the most popular Android smartphones today have WVGA (i.e. wide VGA) 800+ × 480-pixel HD displays. So, what’s “normal” is quickly changing.

Table in Designing For Android
Diagram of various screen configurations available from emulator skins in the Android SDK. (Image: Android Developers website)

For testing, I use a Motorola Droid X, which has a WVGA screen. Again, this is considered “large” by Android’s standards.

The variety of display sizes can be challenging for designers who are trying to create one-size-fits-all layouts. I’ve found that the best approach is to design one set of layouts for 320 × 480 (your baseline) and another set for 320 × 533 (which would be considered a “large” physical screen size).

While this creates more work for both the designer and developer, the larger physical screen size on bigger devices such as the Motorola Droid and HTC Evo might require changes to the baseline layouts that make better use of the extra real estate.

What You Need to Know About Screen Densities

Screen sizes are only half the picture! Developers don’t refer to a screen’s resolution, but rather its density. Here’s how Android defines the terms in its Developers Guide:

  • Resolution
    The total number of physical pixels on a screen.
  • Screen density
    The quantity of pixels within a physical area of the screen, usually referred to as DPI (dots per inch).
  • Density-independent pixel (DP)
    This is a virtual pixel unit that you would use when defining a layout’s UI in order to express the layout’s dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 DPI screen, which is the baseline density assumed by the system of a “medium”-density screen. At runtime, the system transparently handles any scaling of the DP units as necessary, based on the actual density of the screen in use. The conversion of DP units to screen pixels is simple: pixels = DP * (DPI / 160). For example, on a 240 DPI screen, 1 DP equals 1.5 physical pixels. Always use DP units when defining your application’s UI to ensure that the UI displays properly on screens with different densities.

It’s a bit confusing, but here’s what you need to know. As with screen sizes, Android breaks down screen densities into four basic densities: lDPI (low), mDPI (medium), hDPI (high), and xhDPI (extra high). This is important because you’ll need to deliver all graphical assets (i.e. the bitmaps) in sets of lDPI, mDPI and hDPI densities. For now, let’s assume that xhDPI is for tablets only.

What this means is that all non-drawable graphics (i.e. graphics that can’t be scaled automatically by Android at runtime) need to be scaled from your “medium” (i.e. 320 × 480) baseline screen layouts.

The bitmap requirement is similar to preparing graphics for print vs. the Web. If you have any experience with print production, you’ll know that a 72 PPI image will look very pixelated and blurry when scaled up and printed. Instead, you would need to redo the image as a vector image or use a high-resolution photo and then set the file’s resolution at around 300 PPI in order to print it without any loss of image quality. Screen density for Android works similar, except that we’re not changing the file’s resolution, only the image’s size (i.e. standard 72 PPI is fine).

Let’s say you took a bitmap icon measuring 100 × 100 pixels from one of the screens of your baseline designs (remember the “baseline” is a layout set at 320 × 480). Placing this same 100 × 100 icon on a device with an lDPI screen would make the icon appear big and blurry. Likewise, placing it on a device with an hDPI screen would make it appear too small (due to the device having more dots per inch than the mDPI screen).

Density-test-bad in Designing For Android
An application without density support. (Image: Android Developers website)

To adjust for the different device screen densities, we need to follow a 3:4:6:8 scaling ratio between the four density sizes. (For the iPhone, it’s easy: it’s just a 2:1 ratio between the iPhone 4 and 3GS.) Using our ratios and some simple math, we can create four different versions of our bitmap to hand off to our developer for production:

  • 75 × 75 for low-density screens (i.e. ×0.75);
  • 100 × 100 for medium-density screens (our baseline);
  • 150 × 150 for high-density screens (×1.5);
  • 200 × 200 for extra high-density screens (×2.0). (We’re concerned with only lDPI, mDPI and hDPI for Android smartphone apps.)

Icon-sizes in Designing For Android
The final graphic assets would appear like this using the four different screen densities.

After you’ve produced all of your graphics, you could organize your graphics library as follows:

Folders in Designing For Android
The suggested organization and labeling of asset folders and files. In preparing our star graphic, all file prefixes could be preceded by the name ic_star, without changing the names of the respective densities.

You might be confused about what PPI (pixels per inch) to set your deliverables at. Just leave them at the standard 72 PPI, and scale the images accordingly.

Using Android Design Patterns

Clients often ask whether they can use their iPhone app design for Android. If you’re looking for shortcuts, building an app for mobile Web browsers using something like Webkit and HTML5 is perhaps a better choice. But to produce a native Android app, the answer is no. Why? Because Android’s UI conventions are different from iPhone’s.

The big difference is the “Back” key, for navigating to previous pages. The Back key on Android devices is fixed and always available to the user, regardless of the app. It’s either a physical part of the device or digitally fixed to the bottom of the screen, independent of any app, as in the recently released Android 3.0 for tablets (more on this later).

Back-key in Designing For Android
The hard “Back” key on a smartphone running Android 2.0.

The presence of a Back key outside of the app itself leaves space for other elements at the top of the screen, such as a logo, title or menu. While this navigational convention differs greatly from that of iOS, there are still other differentiators that Android calls “design patterns.” According to Android, a design pattern is a “general solution to a recurring problem.” Below are the main Android design patterns that were introduced with version 2.0.

Dashboard

This pattern solves the problem of having to navigate to several layers within an app. It provides a launch pad solution for rich apps such as Facebook, LinkedIn and Evernote.

Pattern-dashboard in Designing For Android
The dashboard design pattern, as used by Facebook and LinkedIn.

Action Bar

The action bar is one of Android’s most important design patterns and differentiators. It works very similar to a conventional website’s banner, with the logo or title typically on the left and the navigation items on the right. The action bar’s design is flexible and allows for hovering menus and expanding search boxes. It’s generally used as a global feature rather than a contextual one.

Pattern-action-bar in Designing For Android
The action bar design pattern as used by Twitter.

Search Bar

This gives the user a simple way to search by category, and it provides search suggestions.

Pattern-search-bar in Designing For Android
The search bar design pattern as used in the Google Search app.

Quick Actions

This design pattern is similar to iOS’ pop-up behavior that gives the user additional contextual actions. For example, tapping a photo in an app might trigger a quick action bar that allows the user to share the photo.

Pattern-quick-actions in Designing For Android
The quick action design pattern as used by Twitter.

Companion Widget

Widgets allow an app to display notifications on the user’s launch screen. Unlike push notifications in iOS, which behave as temporary modal dialogs, companion widgets remain on the launch screen. (Tip: to select a widget for your Android device, simply tap and hold any empty space on one of the launch screens.)

Pattern-widgets in Designing For Android
The companion widget by Engadget, New York Times and Pandora.

Using established design patterns is important for keeping the experience intuitive and familiar for your users. Users don’t want an iPhone experience on their Android device any more than a Mac user wants a Microsoft experience in their Mac OS environment. Understanding design patterns is the first step to learning to speak Android and designing an optimal experience for its users. Your developers will also thank you!

Android Design Deliverables

OK, so you’ve designed your Android app and are ready to make it a reality. What do you need to hand off to the developer? Here’s a quick list of deliverables:

  1. Annotated wireframes of the user experience based on the baseline “medium” size of 320 × 480 DPI. Include additional screens for instances when a “large” screen size requires a modified layout or when a landscape version is required.
  2. Two sets of visual design mock-ups of key screens for both medium-sized HVGA 320 × 480 screens and large-sized 320 × 533 screens (based on a WVGA 800 × 480 hDPI physical pixel screen size).
  3. Specifications for spacing, font sizes and colors, and an indication of any bitmaps.
  4. A graphics library with lDPI, mDPI and hDPI versions of all bitmaps saved as transparent PNG files. If you’re planning on developing one version of your app for smaller devices and another version for larger devices, then you’ll need lDPI and mDPI sets for your “medium” baseline design and one hDPI set for your “large” version.
  5. Density-specific app icons, including the app’s launch icon, as transparent PNG files. Android already provides excellent tips for designers on this topic, along with some downloads, including graphic PSD templates.

How To Take Screenshots

Your product manager has just asked for screenshots of the developer’s build. The developer is busy and can’t get them to you until tomorrow. What do you do?! As of this writing, Android has no built-in way to take screenshots (bummer, I know). The only way is to just deal with it, and that means pretending to be a developer for a while and downloading some really scary software. Let’s get started!

The following software must be downloaded in a Windows environment (I use Windows via Parallels Desktop on my Mac).

  1. All USB drivers for your Android device,
  2. Android software development kit (SDK),
  3. Java SE SDK

Then, on your computer:

  1. Extract the USB drivers to a folder on your desktop,
  2. Extract the Android SDK to a folder on your desktop,
  3. Install the Java SE SDK.

On your Android device:

  1. Open “Settings” (you’ll find it in the apps menu),
  2. Tap on “Applications,”
  3. Tap on “Development,”
  4. Check the box for “USB debugging.”

Settings in Designing For Android

Now, for the fun part:

  1. Connect your Android device to your computer via USB, and allow Windows to install all drivers. One of the drivers may not be found and will require you to go to the Window’s Device Manager in the Control Panel. There, locate the device (the one with the yellow warning icon beside it), and right-click on it.
  2. Choose to “update/install” the driver for your device.
  3. Go to your desktop. Open the Android SDK folder and select SDK Setup.exe.
  4. Allow it to automatically refresh its list of the operating system SDKs that are available, and select to install all packages.
  5. Once finished, exit the application.
  6. Go back to the opened Android SDK folder on your desktop, and open the “Tools” folder.
  7. Click on the file ddms to open the Dalvik Debug Monitor.
  8. Select your device from the “Name” pane.
  9. In the application’s top menu, open the “Device” menu, and choose “Screen capture…” A Device Screen Capture window will open, and you should see the launch screen of your Android device.

Dalvik-screen in Designing For Android
The Dalvik Debut Monitor.

To navigate:

  1. Grab your Android device and navigate to any page. Go back to your computer and select “Refresh” in the Device Screen Capture window. The current screen from your Android device should appear.
  2. If you’re on a Mac, you can just do the old Shift + Command + 4 trick to take a screenshot. In Windows, you can copy and paste it into one of the Windows media applications.

About Android Tablets

Android tablets differ greatly from smartphones in physical size and screen density. For screen density, assume that all tablets are high-def and use the extra-large “xDPI” size for bitmap graphics.

At CES 2011, companies rained down Android tablets, with an array of screen sizes. However, after a quick review of the most popular ones, we can conclude that the two important screen sizes to focus on in terms of physical pixels are 1280 × 800 and 800 × 480.

With the Android 3.0 Honeycomb release, Google provided device makers with an Android UI made for tablets. Gone is the hard “Back” button, replaced by an anchored software-generated navigation and system status bar at the bottom of the screen.

System-bar in Designing For Android
The anchored navigation and system bar in Android 3.0.

Android 3.0 got a visual refresh, while incorporating all of the design patterns introduced in Android 2.0. The only difference is that the action bar has been updated to include tabs, drop-down menus or breadcrumbs. The action bar can also change its appearance to show contextual actions when the user selects single or multiple elements on a screen.

New-action-bar in Designing For Android
The new action bar with tabs, introduced in Android 3.0.

Another new feature added to the Android framework with 3.0 is a mechanism called “fragments.” A fragment is a self-contained component in a layout that can change size and position depending on the screen’s orientation and size. This further addresses the problem of designing for multiple form factors by giving designers and developers a way to make their screen layout components elastic and stackable, depending on the screen limitations of the app. Screen components can be stretched, stacked, expanded and collapsed, and revealed and hidden.

Diagrams-green in Designing For Android
Diagram showing examples of how fragments can be used.

The next Android release, scrumptiously dubbed Ice Cream Sandwich, promises to bring this functionality to Android smartphones as well, giving designers and developers the option to build an app using a one-size-fits-all strategy. This could be a paradigm shift for designers and developers, who will need to learn to think of app design in terms of puzzle pieces that can be stretched, stacked, expanded or hidden to fit the form factor. In short, this will allow one Android OS to run anywhere (with infinite possibilities!).

A Word of Advice

Do get your hands on an Android phone and tablet, and spend some time downloading apps and exploring their interfaces. In order to design for Android, you have to immerse yourself in the environment and know it intimately. This might sound obvious, but it’s always surprising to hear when even the product manager doesn’t have an Android device.

Android-ice-cream-sandwich in Designing For Android

Online Resources

Here are some links to online resources I’ve found especially useful:

Presentations

Videos

Documents

Blogs

Product Reviews

Android Developers

(al) (il) (kw)


© Dan McKenzie for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: Android

Tags: Coding Android

March 28 2011

11:14

Get Started Developing For Android With Eclipse, Reloaded

Advertisement in Get Started Developing For Android With Eclipse, Reloaded
 in Get Started Developing For Android With Eclipse, Reloaded  in Get Started Developing For Android With Eclipse, Reloaded  in Get Started Developing For Android With Eclipse, Reloaded

In the first part of this tutorial series, we built a simple brew timer application using Android and Eclipse. In this second part, we’ll continue developing the application by adding extra functionality. In doing this, you’ll be introduced to some important and powerful features of the Android SDK, including Persistent data storage, Activities and Intent as well as Shared user preferences.

To follow this tutorial, you’ll need the code from the previous article. If you want to get started right away, grab the code from GitHub and check out the tutorial_part_1 tag using this:

1 Starting Point in Get Started Developing For Android With Eclipse, Reloaded

$ git clone git://github.com/cblunt/BrewClock.git
$ cd BrewClock
$ git checkout tutorial_part_1

Once you’ve checked out the code on GitHub, you’ll need to import the project into Eclipse:

  1. Launch Eclipse and choose File → Import…
  2. In the Import window, select “Existing Projects into Workspace” and click “Next.”
  3. On the next screen, click “Browse,” and select the project folder that you cloned from GitHub.
  4. Click “Finish” to import your project into Eclipse.

After importing the project into Eclipse, you might receive a warning message:

Android required .class compatibility set to 5.0.
Please fix project properties.

If this is the case, right-click on the newly imported “BrewClock” project in the “Project Explorer,” choose “Fix Project Properties,” and then restart Eclipse.

Getting Started With Data Storage

Currently, BrewClock lets users set a specific time for brewing their favorite cups of tea. This is great, but what if they regularly drink a variety of teas, each with their own different brewing times? At the moment, users have to remember brewing times for all their favorite teas! This doesn’t make for a great user experience. So, in this tutorial we’ll develop functionality to let users store brewing times for their favorite teas and then choose from that list of teas when they make a brew.

To do this, we’ll take advantage of Android’s rich data-storage API. Android offers several ways to store data, two of which we’ll cover in this article. The first, more powerful option, uses the SQLite database engine to store data for our application.

SQLite is a popular and lightweight SQL database engine that saves data in a single file. It is often used in desktop and embedded applications, where running a client-server SQL engine (such as MySQL or PostgreSQL) isn’t feasible.

Every application installed on an Android device can save and use any number of SQLite database files (subject to storage capacity), which the system will manage automatically. An application’s databases are private and so cannot be accessed by any other applications. (Data can be shared through the ContentProvider class, but we won’t cover content providers in this tutorial.) Database files persist when the application is upgraded and are deleted when the application is uninstalled.

We’ll use a simple SQLite database in BrewClock to maintain a list of teas and their appropriate brewing times. Here’s an overview of how our database schema will look:

+-------------------------------------+
| Table: teas                         |
+------------+------------------------+
| Column     | Description            |
+------------+------------------------+
| _ID        | integer, autoincrement |
| name       | text, not null         |
| brew_time  | integer, not null      |
+------------+------------------------+

If you’ve worked with SQL before, this should look fairly familiar. The database table has three columns: a unique identifier (_ID), name and brewing time. We’ll use the APIs provided by Android to create the database table in our code. The system will take care of creating the database file in the right location for our application.

Abstracting the Database

To ensure the database code is easy to maintain, we’ll abstract all the code for handling database creation, inserts and queries into a separate class, TeaData. This should be fairly familiar if you’re used to the model-view-controller approach. All the database code is kept in a separate class from our BrewClockActivity. The Activity can then just instantiate a new TeaData instance (which will connect to the database) and do what it needs to do. Working in this way enables us to easily change the database in one place without having to change anything in any other parts of our application that deal with the database.

Create a new class called TeaData in the BrewClock project by going to File → New → Class. Ensure that TeaData extends the android.database.sqlite.SQLiteOpenHelper class and that you check the box for “Constructors from superclass.”

2 Create Teadata Class1 in Get Started Developing For Android With Eclipse, Reloaded

The TeaData class will automatically handle the creation and versioning of a SQLite database for your application. We’ll also add methods to give other parts of our code an interface to the database.

Add two constants to TeaData to store the name and version of the database, the table’s name and the names of columns in that table. We’ll use the Android-provided constant BaseColumns._ID for the table’s unique id column:

// src/com/example/brewclock/TeaData.java
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.provider.BaseColumns;

public class TeaData extends SQLiteOpenHelper {
  private static final String DATABASE_NAME = "teas.db";
  private static final int DATABASE_VERSION = 1;

  public static final String TABLE_NAME = "teas";

  public static final String _ID = BaseColumns._ID;
  public static final String NAME = "name";
  public static final String BREW_TIME = "brew_time";

  // …
}

Add a constructor to TeaData that calls its parent method, supplying our database name and version. Android will automatically handle opening the database (and creating it if it does not exist).

// src/com/example/brewclock/TeaData.java
public TeaData(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

We’ll need to override the onCreate method to execute a string of SQL commands that create the database table for our tea. Android will handle this method for us, calling onCreate when the database file is first created.

On subsequent launches, Android checks the version of the database against the DATABASE_VERSION number we supplied to the constructor. If the version has changed, Android will call the onUpgrade method, which is where you would write any code to modify the database structure. In this tutorial, we’ll just ask Android to drop and recreate the database.

So, add the following code to onCreate:

// src/com/example/brewclock/TeaData.java
@Override
public void onCreate(SQLiteDatabase db) {
  // CREATE TABLE teas (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, brew_time INTEGER);
  String sql =
    "CREATE TABLE " + TABLE_NAME + " ("
      + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
      + NAME + " TEXT NOT NULL, "
      + BREW_TIME + " INTEGER"
      + ");";

  db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
  onCreate(db);
}

Next, we’ll add a new method to TeaData that lets us easily add new tea records to the database. We’ll supply the method with a name and brewing time for the tea to be added. Rather than forcing us to write out the raw SQL to do this, Android supplies a set of classes for inserting records into the database. First, we create a set of ContentValues, pushing the relevant values into that set.

With an instance of ContentValues, we simply supply the column name and the value to insert. Android takes care of creating and running the appropriate SQL. Using Android’s database classes ensures that the writes are safe, and if the data storage mechanism changes in a future Android release, our code will still work.

Add a new method, insert(), to the TeaData class:

// src/com/example/brewclock/TeaData.java
public void insert(String name, int brewTime) {
  SQLiteDatabase db = getWritableDatabase();

  ContentValues values = new ContentValues();
  values.put(NAME, name);
  values.put(BREW_TIME, brewTime);

  db.insertOrThrow(TABLE_NAME, null, values);
}

Retrieving Data

With the ability to save data into the database, we’ll also need a way to get it back out. Android provides the Cursor interface for doing just this. A Cursor represents the results of running a SQL query against the database, and it maintains a pointer to one row within that result set. This pointer can be moved forwards and backwards through the results, returning the values from each column. It can help to visualize this:


SQL Query: SELECT * from teas LIMIT 3;

+-----------------------------------+
|  _ID  |  name       |  brew_time  |
+-----------------------------------+
|    1  |  Earl Grey  |          3  |
|    2  |  Green      |          1  | <= Cursor
|    3  |  Assam      |          5  |
+-------+-------------+-------------+

In this example, the Cursor is pointing at the second row in the result set (Green tea). We could move the Cursor back a row to represent the first row (Earl Grey) by calling cursor.moveToPrevious(), or move forward to the Assam row with moveToNext(). To fetch the name of the tea that the Cursor is pointing out, we would call cursor.getString(1), where 1 is the column index of the column we wish to retrieve (note that the index is zero-based, so column 0 is the first column, 1 the second column and so on).

Now that you know about Cursors, add a method that creates a Cursor object that returns all the teas in our database. Add an all method to TeaData:

// src/com/example/brewclock/TeaData.java
public Cursor all(Activity activity) {
  String[] from = { _ID, NAME, BREW_TIME };
  String order = NAME;

  SQLiteDatabase db = getReadableDatabase();
  Cursor cursor = db.query(TABLE_NAME, from, null, null, null, null, order);
  activity.startManagingCursor(cursor);

  return cursor;
}

Let’s go over this method in detail, because it looks a little strange at first. Again, rather than writing raw SQL to query the database, we make use of Android’s database interface methods.

First, we need to tell Android which columns from our database we’re interested in. To do this, we create an array of strings—each one of the column identifiers that we defined at the top of TeaData. We’ll also set the column that we want to order the results by and store it in the order string.

Next, we create a read-only connection to the database using getReadableDatabase(), and with that connection, we tell Android to run a query using the query() method. The query() method takes a set of parameters that Android internally converts into a SQL query. Again, Android’s abstraction layer ensures that our application code will likely continue to work, even if the underlying data storage changes in a future version of Android.

Because we just want to return every tea in the database, we don’t apply any joins, filters or groups (i.e. WHERE, JOIN, and GROUP BY clauses in SQL) to the method. The from and order variables tell the query what columns to return on the database and the order in which they are retrieved. We use the SQLiteDatabase.query() method as an interface to the database.

Last, we ask the supplied Activity (in this case, our BrewClockActivity) to manage the Cursor. Usually, a Cursor must be manually refreshed to reload any new data, so if we added a new tea to our database, we would have to remember to refresh our Cursor. Instead, Android can take care of this for us, recreating the results whenever the Activity is suspended and resumed, by calling startManagingCursor().

Finally, we’ll add another utility method to return the number of records in the table. Once again, Android provides a handy utility to do this for us in the DatabaseUtils class:

Add the following method, count, to your TeaData class:

// src/com/example/brewclock/TeaData.java
  public long count() {
    SQLiteDatabase db = getReadableDatabase();
    return DatabaseUtils.queryNumEntries(db, TABLE_NAME);
  }

Save the TeaData class, and fix any missing imports using Eclipse (Source → Organize Imports). With our data class finished, it’s time to change BrewClock’s interface to make use of the database!

Modify BrewClock’s Interface to Allow Tea Selection

The purpose of storing preset teas and brew times is to let the user quickly select their favorite tea from the presets. To facilitate this, we’ll add a Spinner (analogous to a pop-up menu in desktop interfaces) to the main BrewClock interface, populated with the list of teas from TeaData.

As in the previous tutorial, use Eclipse’s layout editor to add the Spinner to BrewClock’s main interface layout XML file. Add the following code just below the LinearLayout for the brew count label (around line 24). Remember, you can switch to the “Code View” tab along the bottom of the window if Eclipse opens the visual layout editor.

<!-- /res/layout/main.xml -->

<!-- Tea Selection -->
<LinearLayout
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">

  <Spinner
    android:id="@+id/tea_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

In the BrewClockActivity class, add a member variable to reference the Spinner, and connect it to the interface using findViewById:

// src/com/example/brewclock/BrewClockActivity.java
protected Spinner teaSpinner;
protected TeaData teaData;

// …

public void onCreate(Bundle savedInstanceState) {
  // …
  teaData = new TeaData(this);
  teaSpinner = (Spinner) findViewById(R.id.tea_spinner);
}

Try running your application to make sure the new interface works correctly. You should see a blank pop-up menu (or Spinner) just below the brew count. If you tap the spinner, Android handles displaying a pop-up menu so that you can choose an option for the spinner. At the moment, the menu is empty, so we’ll remedy that by binding the Spinner to our tea database.

3 Blank Spinner in Get Started Developing For Android With Eclipse, Reloaded

Data Binding

When Android retrieves data from a database, it returns a Cursor object. The Cursor represents a set of results from the database and can be moved through the results to retrieve values. We can easily bind these results to a view (in this case, the Spinner) using a set of classes provided by Android called “Adapters.” Adapters do all the hard work of fetching database results from a Cursor and displaying them in the interface.

Remember that our TeaData.all() method already returns a Cursor populated with the contents of our teas table. Using that Cursor, all we need to do is create a SimpleCursorAdapter to bind its data to our teaSpinner, and Android will take care of populating the spinner’s options.

Connect the Cursor returned by teaData.all() to the Spinner by creating a SimpleCursorAdapter:

// com/example/brewclock/BrewClockActivity.java

public void onCreate(Bundle savedInstanceState) {
  // …
  Cursor cursor = teaData.all(this);

  SimpleCursorAdapter teaCursorAdapter = new SimpleCursorAdapter(
    this,
    android.R.layout.simple_spinner_item,
    cursor,
    new String[] { TeaData.NAME },
    new int[] { android.R.id.text1 }
  );

  teaSpinner.setAdapter(teaCursorAdapter);
  teaCursorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}

Notice that we’ve made use of Android’s built-in android.R object. This provides some generic default resources for your application, such as simple views and layouts. In this case, we’ve used android.R.layout.simple_spinner_item, which is a simple text label layout.

If you run the application again, you’ll see that the spinner is still empty! Even though we’ve connected the spinner to our database, there are no records in the database to display.

Let’s give the user a choice of teas by adding some default records to the database in BrewClock’s constructor. To avoid duplicate entries, we’ll add only the default teas if the database is empty. We can make use of TeaData’s count() method to check if this is the case.

Add code to create a default set of teas if the database is empty. Add this line just above the code to fetch the teas from teaData:

// com/example/brewclock/BrewClockActivity.java
public void onCreate(Bundle savedInstanceState) {
  // …

  // Add some default tea data! (Adjust to your preference :)
  if(teaData.count() == 0) {
    teaData.insert("Earl Grey", 3);
    teaData.insert("Assam", 3);
    teaData.insert("Jasmine Green", 1);
    teaData.insert("Darjeeling", 2);
  }

  // Code from the previous step:
  Cursor cursor = teaData.all(this);

  // …
}

Now run the application again. You’ll now see that your tea Spinner has the first tea selected. Tapping on the Spinner lets you select one of the teas from your database!

4 Populated Spinner in Get Started Developing For Android With Eclipse, Reloaded

Congratulations! You’ve successfully connected your interface to a data source. This is one of the most important aspects of any software application. As you’ve seen, Android makes this task fairly easy, but it is extremely powerful. Using cursors and adapters, you can take virtually any data source (from a simple array of strings to a complex relational database query) and bind it to any type of view: a spinner, a list view or even an iTunes-like cover-flow gallery!

Although now would be a good time for a brew, our work isn’t over yet. While you can choose different teas from the Spinner, making a selection doesn’t do anything. We need to find out which tea the user has selected and update the brew time accordingly.

Read Selected Tea, and Update Brew Time

To determine which tea the user has selected from our database, BrewClockActivity needs to listen for an event. Similar to the OnClickListener event that is triggered by button presses, we’ll implement the OnItemSelectedListener. Events in this listener are triggered when the user makes a selection from a view, such as our Spinner.

Enable the onItemSelectedListener in BrewClockActivity by adding it to the class declaration. Remember to implement the interface methods onItemSelected() and onNothingSelected():

// src/com/example/brewclock/BrewClockActivity.java
public class BrewClockActivity extends Activity implements OnClickListener, OnItemSelectedListener {
  // …
  public void onItemSelected(AdapterView<?> spinner, View view, int position, long id) {
    if(spinner == teaSpinner) {
      // Update the brew time with the selected tea’s brewtime
      Cursor cursor = (Cursor) spinner.getSelectedItem();
      setBrewTime(cursor.getInt(2));
    }
  }

  public void onNothingSelected(AdapterView<?> adapterView) {
    // Do nothing
  }
}

Here we check whether the spinner that triggered the onItemSelected event was BrewClock’s teaSpinner. If so, we retrieve a Cursor object that represents the selected record. This is all handled for us by the SimpleCursorAdapter that connects teaData to the Spinner. Android knows which query populates the Spinner and which item the user has selected. It uses these to return the single row from the database, representing the user’s selected tea.

Cursor’s getInt() method takes the index of the column we want to retrieve. Remember that when we built our Cursor in teaData.all(), the columns we read were _ID, NAME and BREW_TIME. Assuming we chose Jasmine tea in teaSpinner, the Cursor returned by our selection would be pointing at that record in the database.

We then ask the Cursor to retrieve the value from column 2 (using getInt(2)), which in this query is our BREW_TIME column. This value is supplied to our existing setBrewTime() method, which updates the interface to show the selected tea’s brewing time.

Finally, we need to tell the teaSpinner that BrewClockActivity is listening for OnItemSelected events. Add the following line to BrewClockActivity’s onCreate method:

// src/com/example/brewclock/BrewClockActivity.java
public void onCreate() {
  // …
  teaSpinner.setOnItemSelectedListener(this);
}

That should do it! Run your application again, and try selecting different teas from the Spinner. Each time you select a tea, its brew time will be shown on the countdown clock. The rest of our code already handles counting down from the current brew time, so we now have a fully working brew timer, with a list of preset teas.

You can, of course, go back into the code and add more preset teas to the database to suit your tastes. But what if we released BrewClock to the market? Every time someone wanted to add a new tea to the database, we’d need to manually update the database, and republish the application; everyone would need to update, and everybody would have the same list of teas. That sounds pretty inflexible, and a lot of work for us!

5 Default Teas in Get Started Developing For Android With Eclipse, Reloaded

It would be much better if the user had some way to add their own teas and preferences to the database. We’ll tackle that next…

Introducing Activities

Each screen in your application and its associated code is an Activity. Every time you go from one screen to another, Android creates a new Activity. In reality, although an application may comprise any number of screens/activities, Android treats them as separate entities. Activities work together to form a cohesive experience because Android lets you easily pass data between them.

In this final section, you’ll add a new Activity (AddTeaActivity) to your application and register it with the Android system. You’ll then pass data from the original BrewClockActivity to this new Activity.

First, though, we need to give the user a way to switch to the new Activity. We’ll do this using an options menu.

Options Menus

Options menus are the pop-up menus that appear when the user hits the “Menu” key on their device. Android handles the creation and display of options menus automatically; you just need to tell it what options to display and what to do when an option is chosen by the user.

However, rather than hard-coding our labels into the menu itself, we’ll make use of Android string resources. String resources let you maintain all the human-readable strings and labels for your application in one file, calling them within your code. This means there’s only one place in your code where you need to change strings in the future.

In the project explorer, navigate to “res/values” and you will see that a strings.xml file already exists. This was created by Eclipse when we first created the project, and it is used to store any strings of text that we want to use throughout the application.

Open strings.xml by double clicking on it, and switch to the XML view by clicking the strings.xml tab along the bottom of the window.

Add the following line within the <resources>…</resources> element:

<!-- res/values/strings.xml -->
  <resources>
    <!-- … -->
    <string name="add_tea_label">Add Tea</string>
  </resources>

Here you’ve defined a string, add_tea_label, and its associated text. We can use add_tea_label to reference the string throughout the application’s code. If the label needs to change for some reason in the future, you’ll need to change it only once in this file.

Next, let’s create a new file to define our options menu. Just like strings and layouts, menus are defined in an XML file, so we’ll start by creating a new XML file in Eclipse:

Create a new Android XML file in Eclipse by choosing File → New → Other, and then select “Android XML File.”

Select a resource type of “Menu,” and save the file as main.xml. Eclipse will automatically create a folder, res/menu, where your menu XML files will be stored.

7 New Menu Xml in Get Started Developing For Android With Eclipse, Reloaded

Open the res/menus/main.xml file, and switch to XML view by clicking the “main.xml” tab along the bottom of the window.

Add a new menu item, add_tea.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/add_tea" android:title="@string/add_tea_label" />
</menu>

Notice the android:title attribute is set to @string/add_tea_label. This tells Android to look up add_tea_label in our strings.xml file and return the associated label. In this case, our menu item will have a label “Add Tea.”

Next, we’ll tell our Activity to display the options menu when the user hits the “Menu” key on their device.

Back in BrewClockActivity.java, override the onCreateOptionsMenu method to tell Android to load our menu when the user presses the “Menu” button:

// src/com/example/brewclock/BrewClockActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.main, menu);

  return true;
}

When the user presses the “Menu” button on their device, Android will now call onCreateOptionsMenu. In this method, we create a MenuInflater, which loads a menu resource from your application’s package. Just like the buttons and text fields that make up your application’s layout, the main.xml resource is available via the global R object, so we use that to supply the MenuInflater with our menu resource.

To test the menu, save and run the application in the Android emulator. While it’s running, press the “Menu” button, and you’ll see the options menu pop up with an “Add Tea” option.

8 Add Teas Options Menu in Get Started Developing For Android With Eclipse, Reloaded

If you tap the “Add Tea” option, Android automatically detects the tap and closes the menu. In the background, Android will notify the application that the option was tapped.

Handling Menu Taps

When the user taps the “Add Tea” menu option, we want to display a new Activity so that they can enter the details of the tea to be added. Start by creating that new Activity by selecting File → New → Class.

9 New Activity Settings in Get Started Developing For Android With Eclipse, Reloaded

Name the new class AddTeaActivity, and make sure it inherits from the android.app.Activity class. It should also be in the com.example.brewclock package:

// src/com/example/brewclock/AddTeaActivity.java
package com.example.brewclock;

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

public class AddTeaActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }
}

This simple, blank Activity won’t do anything yet, but it gives us enough to finish our options menu.

Add the onOptionsItemSelected override method to BrewClockActivity. This is the method that Android calls when you tap on a MenuItem (notice it receives the tapped MenuItem in the item parameter):

// src/com/example/brewclock/BrewClockActivity.java
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch(item.getItemId()) {
    case R.id.add_tea:
      Intent intent = new Intent(this, AddTeaActivity.class);
      startActivity(intent);
      return true;

    default:
      return super.onOptionsItemSelected(item);
  }
}

With this code, we’ve told Android that when the “Add Tea” menu item is tapped, we want to start a new Activity; in this case, AddTeaActivity. However, rather than directly creating an instance of AddTeaActivity, notice that we’ve used an Intent. Intents are a powerful feature of the Android framework: they bind Activities together to make up an application and allow data to be passed between them.

Intents even let your application take advantage of any Activities within other applications that the user has installed. For example, when the user asks to display a picture from a gallery, Android automatically displays a dialogue to the user allowing them to pick the application that displays the image. Any applications that are registered to handle image display will be shown in the dialogue.

Intents are a powerful and complex topic, so it’s worth reading about them in detail in the official Android SDK documentation.

Let’s try running our application to test out the new “Add Tea” screen.

Run your project, tap the “Menu” button and then tap “Add Tea.”

Instead of seeing your “Add Tea” Activity as expected, you’ll be presented with a dialogue that is all too common for Android developers:

10 Crash in Get Started Developing For Android With Eclipse, Reloaded

Although we created the Intent and told it to start our AddTeaActivity Activity, the application crashed because we haven’t yet registered it within Android. The system doesn’t know where to find the Activity we’re trying to run (remember that Intents can start Activities from any application installed on the device). Let’s remedy this by registering our Activity within the application manifest file.

Open your application’s manifest file, AndroidManifest.xml in Eclipse, and switch to the code view by selecting the “AndroidManifest.xml” tab along the bottom of the window.

The application’s manifest file is where you define global settings and information about your application. You’ll see that it already declares .BrewClockActivity as the Activity to run when the application is launched.

Within <application>, add a new <activity> node to describe the “Add Tea” Activity. Use the same add_tea_label string that we declared earlier in strings.xml for the Activity’s title:

<!-- AndroidManifest.xml -->
<application …>
  …
  <activity android:name=".AddTeaActivity" android:label="@string/add_tea_label" />
</application>

Save the manifest file before running BrewClock again. This time, when you open the menu and tap “Add Tea,” Android will start the AddTeaActivity. Hit the “Back” button to go back to the main screen.

With the Activities hooked together, it’s time to build an interface for adding tea!

Building The Tea Editor Interface

Building the interface to add a tea is very similar to how we built the main BrewClock interface in the previous tutorial. Start by creating a new layout file, and then add the appropriate XML, as below.

Alternatively, you could use Android’s recently improved layout editor in Eclipse to build a suitable interface. Create a new XML file in which to define the layout. Go to File → New, then select “Android XML File,” and select a “Layout” type. Name the file add_tea.xml.

11 New Layout Xml in Get Started Developing For Android With Eclipse, Reloaded

Replace the contents of add_tea.xml with the following layout:

<!-- res/layouts/add_tea.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:padding="10dip">

  <TextView
    android:text="@string/tea_name_label"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

  <EditText
    android:id="@+id/tea_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

  <TextView
    android:text="@string/brew_time_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

  <SeekBar
    android:id="@+id/brew_time_seekbar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:progress="2"
    android:max="9" />

  <TextView
    android:id="@+id/brew_time_value"
    android:text="3 m"
    android:textSize="20dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal" />
</LinearLayout>

We’ll also need to add some new strings to strings.xml for the labels used in this interface:

<!-- res/values/strings.xml -->
<resources>
  <!-- … -->
  <string name="tea_name_label">Tea Name</string>

  <string name="brew_time_label">Brew Time</string>
</resources>

In this layout, we’ve added a new type of interface widget, the SeekBar. This lets the user easily specify a brew time by dragging a thumb from left to right. The range of values that the SeekBar produces always runs from zero (0) to the value of android:max.

In this interface, we’ve used a scale of 0 to 9, which we will map to brew times of 1 to 10 minutes (brewing for 0 minutes would be a waste of good tea!). First, though, we need to make sure that AddTeaActivity loads our new interface:

Add the following line of code to the Activity’s onCreate() method that loads and displays the add_tea layout file:

// src/com/example/brewclock/AddTeaActivity.java
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.add_tea);
}

Now test your application by running it, pressing the “Menu” button and tapping “Add Tea” from the menu.

12 Add Tea Interface in Get Started Developing For Android With Eclipse, Reloaded

You’ll see your new interface on the “Add Tea” screen. You can enter text and slide the SeekBar left and right. But as you’d expect, nothing works yet because we haven’t hooked up any code.

Declare some properties in AddTeaActivity to reference our interface elements:

// src/com/example/brewclock/AddTeaActivity.java
public class AddTeaActivity {
  // …

  /** Properties **/
  protected EditText teaName;
  protected SeekBar brewTimeSeekBar;
  protected TextView brewTimeLabel;

  // …

Next, connect those properties to your interface:

public void onCreate(Bundle savedInstanceState) {
  // …
  // Connect interface elements to properties
  teaName = (EditText) findViewById(R.id.tea_name);
  brewTimeSeekBar = (SeekBar) findViewById(R.id.brew_time_seekbar);
  brewTimeLabel = (TextView) findViewById(R.id.brew_time_value);
}

The interface is fairly simple, and the only events we need to listen for are changes to the SeekBar. When the user moves the SeekBar thumb left or right, our application will need to read the new value and update the label below with the selected brew time. We’ll use a Listener to detect when the SeekBar is changed:

Add an onSeekBarChangedListener interface to the AddTeaActivity class declaration, and add the required methods:

// src/com/example/brewclock/AddTeaActivity.java
public class AddTeaActivity
extends Activity
implements OnSeekBarChangeListener {
  // …

  public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    // TODO Detect change in progress
  }

  public void onStartTrackingTouch(SeekBar seekBar) {}

  public void onStopTrackingTouch(SeekBar seekBar) {}
}

The only event we’re interested in is onProgressChanged, so we need to add the code below to that method to update the brew time label with the selected value. Remember that our SeekBar values range from 0 to 9, so we’ll add 1 to the supplied value so that it makes more sense to the user:

Add the following code to onProgressChanged() in AddTeaActivity.java:

// src/com/example/brewclock/AddTeaActivity.java
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  if(seekBar == brewTimeSeekBar) {
    // Update the brew time label with the chosen value.
    brewTimeLabel.setText((progress + 1) + " m");
  }
}

Set the SeekBar’s listener to be our AddTeaActivity in onCreate:

// src/com/example/brewclock/AddTeaActivity.java
public void onCreate(Bundle savedInstanceState) {
  // …

  // Setup Listeners
  brewTimeSeekBar.setOnSeekBarChangeListener(this);
}

Now when run the application and slide the SeekBar left to right, the brew time label will be updated with the correct value:

13 Seekbar in Get Started Developing For Android With Eclipse, Reloaded

Saving Tea

With a working interface for adding teas, all that’s left is to give the user the option to save their new tea to the database. We’ll also add a little validation to the interface so that the user cannot save an empty tea to the database!

Start by opening strings.xml in the editor and adding some new labels for our application:

<!-- res/values/strings.xml -->
<string name="save_tea_label">Save Tea</string>
<string name="invalid_tea_title">Tea could not be saved.</string>

<string name="invalid_tea_no_name">Enter a name for your tea.</string>

Just like before, we’ll need to create a new options menu for AddTeaActivity so that the user can save their favorite tea:

Create a new XML file, add_tea.xml, in the res/menus folder by choosing File → New and then Other → Android XML File. Remember to select “Menu” as the resource type.

Add an item to the new menu for saving the tea:

<!-- res/menus/add_tea.xml -->
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:title="@string/save_tea_label" android:id="@+id/save_tea" />
</menu>

Back in AddTeaActivity, add the override methods for onCreateOptionsMenu and onOptionsItemSelected, just like you did in BrewClockActivity. However, this time, you’ll supply the add_tea.xml resource file to the MenuInflater:

// src/com/example/brewclock/AddTeaActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.add_tea, menu);

  return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch(item.getItemId()) {
    case R.id.save_tea:
      saveTea();

    default:
      return super.onOptionsItemSelected(item);
  }
}

Next, we’ll add a new method, saveTea(), to handle saving the tea. The saveTea method first reads the name and brew time values chosen by the user, validates them and (if all is well) saves them to the database:

// src/com/example/brewclock/AddTeaActivity.java
public boolean saveTea() {
  // Read values from the interface
  String teaNameText = teaName.getText().toString();
  int brewTimeValue = brewTimeSeekBar.getProgress() + 1;

  // Validate a name has been entered for the tea
  if(teaNameText.length() < 2) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle(R.string.invalid_tea_title);
    dialog.setMessage(R.string.invalid_tea_no_name);
    dialog.show();

    return false;
  }

  // The tea is valid, so connect to the tea database and insert the tea
  TeaData teaData = new TeaData(this);
  teaData.insert(teaNameText, brewTimeValue);
  teaData.close();

  return true;
}

This is quite a hefty chunk of code, so let’s go over the logic.

First, we read the values of the EditText teaName and the SeekBar brewTimeSeekBar (remembering to add 1 to the value to ensure a brew time of between 1 and 10 minutes). Next, we validate that a name has been entered that is two or more characters (this is really simple validation; you might want to experiment doing something more elaborate, such as using regular expressions).

If the tea name is not valid, we need to let the user know. We make use of one of Android’s helper classes, AlertDialog.Builder, which gives us a handy shortcut for creating and displaying a modal dialog window. After setting the title and error message (using our string resources), the dialogue is displayed by calling its show() method. This dialogue is modal, so the user will have to dismiss it by pressing the “Back” key. At this point, we don’t want to save any data, so just return false out of the method.

If the tea is valid, we create a new temporary connection to our tea database using the TeaData class. This demonstrates the advantage of abstracting your database access to a separate class: you can access it from anywhere in the application!

After calling teaData.insert() to add our tea to the database, we no longer need this database connection, so we close it before returning true to indicate that the save was successful.

Try this out by running the application in the emulator, pressing “Menu” and tapping “Add Tea.” Once on the “Add Tea” screen, try saving an empty tea by pressing “Menu” again and tapping “Save Tea.” With your validation in place, you’ll be presented with an error message:

14 Invalid Tea in Get Started Developing For Android With Eclipse, Reloaded

Next, try entering a name for your tea, choosing a suitable brew time, and choosing “Save Tea” from the menu again. This time, you won’t see an error message. In fact, you’ll see nothing at all.

Improving the User Experience

While functional, this isn’t a great user experience. The user doesn’t know that their tea has been successfully saved. In fact, the only way to check is to go back from the “Add Tea” Activity and check the list of teas. Not great. Letting the user know that their tea was successfully saved would be much better. Let’s show a message on the screen when a tea has been added successfully.

We want the message to be passive, or non-modal, so using an AlertDialog like before won’t help. Instead, we’ll make use of another popular Android feature, the Toast.

Toasts display a short message near the bottom of the screen but do not interrupt the user. They’re often used for non-critical notifications and status updates.

Start by adding a new string to the strings.xml resource file. Notice the %s in the string? We’ll use this in the next step to interpolate the name of the saved tea into the message!

<!-- res/values/strings.xml -->
<string name="save_tea_success">%s tea has been saved.</string>

Modify the code in onOptionsItemSelected to create and show a Toast pop-up if the result of saveTea() is true. The second parameter uses of getString() interpolate the name of our tea into the Toast message. Finally, we clear the “Tea Name” text so that the user can quickly add more teas!

// src/com/example/brewclock/AddTeaActivity.java
// …
switch(item.getItemId()) {
 case R.id.save_tea:
   if(saveTea()) {
     Toast.makeText(this, getString(R.string.save_tea_success, teaName.getText().toString()), Toast.LENGTH_SHORT).show();
     teaName.setText("");
   }
// …

Now re-run your application and try adding and saving a new tea. You’ll see a nice Toast pop up to let you know the tea has been saved. The getString() method interpolates the name of the tea that was saved into the XML string, where we placed the %s.

16 Valid Save in Get Started Developing For Android With Eclipse, Reloaded

Click the “Back” button to return to the application’s main screen, and tap the tea spinner. The new teas you added in the database now show up as options in the spinner!

User Preferences

BrewClock is now fully functional. Users can add their favorite teas and the respective brewing times to the database, and they can quickly select them to start a new brew. Any teas added to BrewClock are saved in the database, so even if we quit the application and come back to it later, our list of teas is still available.

One thing you might notice when restarting BrewClock, though, is that the brew counter is reset to 0. This makes keeping track of our daily tea intake (a vital statistic!) difficult. As a final exercise, let’s save the total brew count to the device.

Rather than adding another table to our teas database, we’ll make use of Android’s “Shared Preferences,” a simple database that Android provides to your application for storing simple data (strings, numbers, etc.), such as high scores in games and user preferences.

Start by adding a couple of constants to the top of BrewClockActivity.java. These will store the name of your shared preferences file and the name of the key we’ll use to access the brew count. Android takes care of saving and persisting our shared preferences file.

// src/com/example/brewclock/BrewClockActivity.java
protected static final String SHARED_PREFS_NAME = "brew_count_preferences";
protected static final String BREW_COUNT_SHARED_PREF = "brew_count";

Next, we’ll need to make some changes to the code so that we can read and write the brew count to the user preferences, rather than relying on an initial value in our code. In BrewClockActivity’s onCreate method, change the lines around setBrewCount(0) to the following:

// src/com/example/brewclock/BrewClockActivity.java
public void onCreate() {
  // … 

  // Set the initial brew values
  SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
  brewCount = sharedPreferences.getInt(BREW_COUNT_SHARED_PREF, 0);
  setBrewCount(brewCount);

  // …
}

Here we’re retrieving an instance of the application’s shared preferences using SharedPreferences, and asking for the value of the brew_count key (identified by the BREW_COUNT_SHARED_PREF constant that was declared earlier). If a value is found, it will be returned; if not, we’ll use the default value in the second parameter of getInt (in this case, 0).

Now that we can retrieve the stored value of brew count, we need to ensure its value is saved to SharedPreferences whenever the count is updated.

Add the following code to setBrewCount in BrewClockActivity:

// src/com/example/brewclock/BrewClockActivity.java
 public void setBrewCount(int count) {
   brewCount = count;
   brewCountLabel.setText(String.valueOf(brewCount));

   // Update the brewCount and write the value to the shared preferences.
   SharedPreferences.Editor editor = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE).edit();
   editor.putInt(BREW_COUNT_SHARED_PREF, brewCount);
   editor.commit();
 }

Shared preferences are never saved directly. Instead, we make use of Android’s SharedPreferences.Editor class. Calling edit() on SharedPreferences returns an editor instance, which can then be used to set values in our preferences. When the values are ready to be saved to the shared preferences file, we just call commit().

With our application’s code all wrapped up, it’s time to test everything!

Run the application on the emulator, and time a few brews (this is the perfect excuse to go and make a well-deserved tea or two!), and then quit the application. Try running another application that is installed on the emulator to ensure BrewClock is terminated. Remember that Android doesn’t terminate an Activity until it starts to run out of memory.

When you next run the application, you’ll see that your previous brew count is maintained, and all your existing teas are saved!

Summary

Congratulations! You’ve built a fully working Android application that makes use of a number of core components of the Android SDK. In this tutorial, you have seen how to:

  • Create a simple SQLite database to store your application’s data;
  • Make use of Android’s database classes and write a custom class to abstract the data access;
  • Add option menus to your application;
  • Create and register new Activities within your application and bind them together into a coherent interface using Intents;
  • Store and retrieve simple user data and settings using the built-in “Shared Preferences” database.

Data storage and persistence is an important topic, no matter what type of application you’re building. From utilities and business tools to 3-D games, nearly every application will need to make use of the data tools provided by Android.

17 Brew Up in Get Started Developing For Android With Eclipse, Reloaded

Activities

BrewClock is now on its way to being a fully functional application. However, we could still implement a few more features to improve the user experience. For example, you might like to develop your skills by trying any of the following:

  • Checking for duplicate tea name entries before saving a tea,
  • Adding a menu option to reset the brew counter to 0,
  • Storing the last-chosen brew time in a shared preference so that the application defaults to that value when restarted,
  • Adding an option for the user to delete teas from the database.

Solutions for the Activities will be included in a future branch on the GitHub repository, where you’ll find the full source-code listings. You can download the working tutorial code by switching your copy of the code to the tutorial_2 branch:

# If you’ve not already cloned the repository,
# you’ll need to do that first:
# $ git clone git://github.com/cblunt/BrewClock.git
# $ cd BrewClock
$ git checkout tutorial_2

I hope you’ve enjoyed working through this tutorial and that it helps you in designing and building your great Android applications. Please let me know how you get on in the comments below, or feel free to drop me an email.

Thanks to Anselm for his suggestions and feedback!

(al)


© Chris Blunt for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: android, development, programming

January 07 2011

21:41

Android 3.0, Honeycomb

At the Consumer Electronic Show (CES) in Las Vegas, Google showed Android 3.0, Honeycomb.

It is the next version of the Android platform, designed for devices with larger screen sizes, such as tablets.  Honeycomb is said to provide a “truly virtual and holographic user interface.”

 

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
Get rid of the ads (sfw)

Don't be the product, buy the product!

Schweinderl