Skip to content

Collected code examples from the O'Reilly Android Cookbook. See README below!

License

Notifications You must be signed in to change notification settings

anndream/Android-Cookbook-Examples

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Android Cookbook Examples

This repo is among the largest collections of Android code samples anywhere; it contains around a hundred and fifty compilable source code examples from the O’Reilly Android Cookbook, a great source of tutorial material for the Android Developer. Not all recipes in the book or online have code accompanying them; this repo features code that was either linked by the contributor, or in some cases, re-constructed as a New Project by the editor for your convenience.

Further note that not all programs used in the book/online appear here; some of the examples in the book/online are only program fragments taken from other programs that can’t be included. And of course some code is drawn from existing projects that are hosted elsewhere.

Each Directory comprises its own project, and has a name that is cited at the end of the corresponding Recipe, under the "Source Code Download" section.

NOTE There are two styles of projects:

  1. Eclipse projects with the newer Eclipse Andmore;

  2. Android Studio projects (most of them complete with their extraneous "app" subdirectory).

If you have used the old Google ADT, you will need to update your Eclipse config by removing ADT, then replace it with AndMore from the Eclipse Marketplace Client.

Most of the Eclipse projects also have configuration files to allow them to be opened in Android Studio.

Many of the Eclipse projects have been Mavenized; a few have not.

Most of the Gradle projects will also build with Android Studio; there may be a few that will not.

The table List of Projects shows which projects are set up for which build tools.

TL;DR: Build Most Projects with Apache Maven

Prerequisites: Java 7 or 8 SDK, Android SDK including "Google Maven Repository" for compat stuff, git, Maven

  1. git clone https://github.com/mosabua/maven-android-sdk-deployer

  2. cd maven-android-sdk-deployer

  3. mvn install -P 6.0 # at least

  4. mvn install -P 7.0 # also needed

  5. cd ..

  6. git clone https://github.com/IanDarwin/Android-Cookbook-Examples

  7. cd Android-Cookbook-Examples

  8. mvn -fae package android:install android:run Include android:install and android:run only if you actually want to run them all, and have a device or emulator with some good free space; else just do 'package')

  9. Fix up any that didn’t work, and send pull requests!

Eclipse Issue

If you get Eclipse-Maven projects failing with this message: org.codehaus.plexus.archiver.jar.Manifest.write(java.io.PrintWriter)

then you need to update your "M2E Connector for Android" to at least 0.17.2.20060614

Maven Build: More Details

About two thirds of these projects were initially developed using Eclipse ADT, and migrated to Maven for automatic building. Obviously Google has spoken and we will eventually have to migrate kicking and screaming to Android Studio and Gradle, but for now, we are keeping those projects in "bilingual" or "either-IDE mode".

If you import the entire repo in Eclipse with eGit, be sure to check the Import all projects checkbox. If you want to keep these mini-projects separate from your "regular" work, you may want to use the Git repo as an Eclipse workspace (use File→Switch Workspace→Other→Browse). This directory is already set up to be an Eclipse workspace if you want it to (the .metadata directory exists and is already in .gitignore).

Note: As part of the move to Gradle, Google stopped pushing Android releases to Maven Central; their last version was 4.1.1.4, thus Lollipop, Marshmallow, and "N" have been left high-and-dry. And worse, their SDK license prohibits re-distribution of binaries, so nobody else can step in and upload these files to Maven Central. But of course there is a solution. To compile these projects with Maven you will need to download the amazing maven-android-sdk-deployer, which repackages files from the SDK - after you download it using the Android tools, thus nobody is redistributing it - into your local .m2/repository so that Maven can find it. This is the function of the first few steps in the numbered list above.

Note that projects using official releases use e.g. com.google.android:android:4.1.1.4 whereas projects deployed using the sdk-deployer use e.g android:android:6.0_r3.

You can download AndroidCookbookExamples as a Zip file from GitHub, but then you won’t get updates, and it will be hard to collaborate with the other contributors. If you’re not familiar with Git and Github, see the getting started page on GitHub and read up on how to collaborate. You can either send diff/patch files or send a pull request. Remember that GitHub is a free service for public projects!

Many of the projects may (depending on your version of Eclipse) give you some noise when you first open them due to bin and/or gen being missing. The Eclipse plug-in will usually create them but not notify that it’s done so, meaning you just have to do Refresh (F5), failing that, close and re-open the project. Does not happen with current Eclipse, last I tried.

There is neither a Wiki or a Tracker for this Github repository. If a project won’t open, or won’t build, we’d prefer that you fix it and sent a pull request. Bugs and suggestions about code samples can be made on the Android Cookbook web site (http://androidcookbook.com/). Bugs or suggesions on the published edition of the book should go to http://shop.oreilly.com/product/0636920038092.do; you can also purchase the book there (which helps fund my continued work on this code base).

Notes for the First Edition of the book

The current version of this repo has been reorganized in preparation for the second edition of the book. There have been quite a few projects added since the first published edition of the book, and a few renamed, so if you have the printed edition from 2012 you should rummage around here before re-typing anything that looks like a full example.

If you want this repo to correspond to the last minor revision of the first edition, use git to checkout the tag Book-1.0.

DELETED PROJECTS

JpsTrack and the ToDo applications have graduated to their own github projects, up one level from here on Github.

List of Projects

The following list is generated (periodically) from the project folders. In the Builds With column, E for Eclipse, M for Maven, S for Android Studio, G for Gradle.

Table 1. List of projects with description and build tools
Project Builds With Function Notes

AboutBoxDemo

GS

A re-usable About dialog.

-

AboutInfo

EMGS

Info about device and screen

-

ActionBarCompat

GS

Simple ActionBar demo(s)

-

AddContact

EMG

Add a contact

Shows ContactsContract, content provider

AdMobDemo

GS

Using AdMob with interstitial (inter-Activity) ads.

-

AndroidPlot

EMG

Graphing

-

AndroidRss

EMG

RSS Reader

Works under Maven; Eclipse fails w/ Maven Configuration Problem

AppDownloader

MGS

Installs another app

Downloading, package management

AppSingleton

GS

Compilable example of the Application Singleton pattern recipe.

-

AutocompleteTextViewContacts

EMG

Contact picker with autocomplete

-

AutoUpdater

EMG

App can update itself

see AppDownloader

BackupManager

EMG

Use Android Backup scheme.

-

BluetoothDemo

EMG

Bluetooth Connection

-

CalAdder

EMG

Add appointment to Calendar

Calendar via Content Provider

CallFaker

EMG

Pretend a call happened, for testing

-

CallInterceptorIncoming

EGS

Intercept an incoming phone call.

-

CallInterceptorOutgoing

EG

Intercept outgoing phone calls.

Compiles and runs, but doesn’t intercept the call.

CameraIntent

GS

CameraIntent - get the camera to take a picture, by startActivityForResult()

-

CardDemo

GS

Demonstation of Card widget.

-

CheckBoxRadioButton

EMG

GUI demo

name says it

ContentProviderBookmarks

EMG

List of bookmarks from Bookmarks Content Provider

Browser ContentProvider

ContentProviderList

EMG

List of ContentProviders

-

ContentProviderSample

EMG

Implement a ContentProvider

-

ContentProviderTest

EMG

Test it

-

CountDownTimerExample

EMG

Time-based activity

-

CurrentMoodWidget

EMG

Application Widget

-

CursorLoaderDemo

EMG

How to load data properly using CursorLoader

-

CustomMenu

EMG

Menu

-

CustomSubMenu

GS

Submenu, created programmatically

-

CustomToast

EMG

Toast

-

DatabaseFromFile

EMG

Create a database from an SQLite .db file in 'assets'.

-

DataToCursor

EMG

Fake up a Cursor from a list of files

-

DateFormatDemo

GS

Example of various DateFormat usages.

-

DialogDemos

EMG

Dialogs

-

DragDropDemo

EG

A simple Drag-and-drop example.

-

DreamsDemo

EMG

Demo of "Dreams" (4.x screensaver)

-

EmailTextView

EMG

Send contents of EditText via email

-

EmailWithAttachments

EMG

Attach file to email

-

EpochJSCalendar

EMG

Java + JavaScript Epoch Calendar

-

EventListenersDemo

M

5 Ways to Wire an Event Listener.

-

FacebookSdk

EMG

Access FB API

-

FaceFinder

EMG

Face locator API in photos

-

FileProviderDemo

GS

Demo of FileProvider.

-

FilesystemDemos

MGS

Internal and external files.

-

FindMeX

EG

Find Me X

IllegalArgumentException: Incomplete location object, missing timestamp or accuracy, Progress:334

FloatingActionButtonSnackbarDemo

GS

Demo of 'fab' Floating Abstract Button

-

FontDemo

EMG

Using a custom font

You need to provide the font file! Example uses Iceberg font…​

FragmentsDemos

GS

Simple Fragment and List-Detail Fragments in one project

-

Gallery

EMG

Simple Photo Gallery example.

Deprecated

GcmClient

EMG

Google Cloud Messaging - receiver

-

GcmMockServer

EMG

Google Cloud Messaging - sender

-

GeneralPrompter

EG

A program that shows the Storage Facility to prompt for all files.

-

HapticFeedback

GS

Haptic Feedback recipe.

-

HelloCommandLine

EMAG

HelloWorld

SDK

HelloEclipse

EMG

HelloWorld

Eclipse ADT

HelloEspressoTesting

GS

HelloWorld of EspressoTesting

-

HelloGradle

GS

Hello World with Gradle but NOT Studio.

-

HelloMaven

EMG

HelloWorld using Maven with android-maven-plugin.

-

HelloStudioTesting

GS

HelloWorld of StudioTesting

-

HelloTestingTarget

EMAG

ADT Testing - subject

-

HelloTestingTestProject

EMAG

ADT Testing - Tests

-

HomeAppListView

EMG

A Home Application

Shows running a program

IconizedListView

EMG

List View with Icon

-

IntentsDemo

EMG

Intents

-

IPCDemo

GS

IPC - Inter-Process Communication, simplified demo (2 versions, alas).

-

IpcServiceDemo

GS

IPC - Inter-Process Communication, simplified demo (2 versions, alas).

-

JavascriptDataDemo

EMG

Getting data from Java to JavaScript and back.

-

JavaTimeDemo

MGS

Demos of java.time date/time API

Actually JSR-310 API; almost same but different package

JSONParsing

EG

Simple example of JSON parsing using built-in JSONObject.

-

LayoutBorder

G

Layout Border Demo Project Source for Android

-

ListViewAdvanced

EMG

ListView

-

ListViewDemos

EMGS

ListView

-

ListViewEmpty

EMGS

ListView with empty list: don’t show blank screen!

-

ListViewSectionHeader

EMG

ListView with section headers

-

LocalBroadcastDemo

EMG

Local Broadcast Receiver

-

MapDemosV2

EMG

This is the Google API Maps V2 Demo.

-

MapsV2AddToProject

GS

Adding a Google Maps V2 MapActivity to a project

You must ask for permission from Google (get and provide your own Google API key).

MarketSearch

EMG

Search the Play Store

-

MaterialDemos

EMG

MaterialDesign demos

-

MediaPlayerDemo

EMG

Play media

-

MediaPlayerInteractive

EG

Media Player demo from Marco Dinacci, thanks.

-

MediaRecorderDemo

EMG

Simple sound recorder

-

MenuAction

EMG

Menu Action Handling

-

NdkDemo

EMG

Native Development Kit

C Code

NotificationDemo

EMG

Notifications

-

NumberPickers

EMG

UI for picking numbers

-

OAuth2Demo

GS

Demo of OAuth2 to Google Tasks.

-

OpenGlDemo

EMG

OpenGL graphics

-

OrientationChanges

EMG

Rotation

-

OSMIntro

EMG

Basic OSM map app demo.

Builds with Maven, not with Eclipse. Maybe m2e aar support, isn’t, yet.

OSMOverlay

EMG

OSM Map with a map marker overlay

Compiles, runs, doesn’t load map tiles; needs upgrading to osmdroid-android 5.5

OSMTouchEvents

EMG

OSM Map with touch event handling.

Builds with Maven, not with Eclipse. Maybe m2e aar support, isn’t, yet.

PdfShare

EMG

Create and share a PDF

-

PermissionRequest

G

Shows asking for permissions at runtime, i.e,. "the new way"

-

PhoneGapDemo

EMG

HTML5 app using phonegap/cordova

-

PinchAndZoom

GS

Pinch-and-zoom graphics demo

-

PreferencesDemo

EMG

Preferences

-

ProgressDialogDemo

GS

Demo of a pop-up indefinite progress dialog.

-

RangeGraphDemo

EMG

Using a graphing library

-

RatingBarDemo

EGS

Show use of 5-star RatingBar as used in rankings, surveys, &c.

-

Rebooter

EMG

How to reboot, and why you can’t

-

RecipeList

EMGS

= RecipeList - use an AsyncTask to download data over the 'net via HTTP.

-

RecyclerViewDemo

GS

Demo of RecyclerView, the faster ListView.

-

RemoteSystemsTempFiles

EM

This folder is created automatically by Eclipse and can be ignored.

-

RGraphDemo

EMG

Using a graphing library

-

RuntimeLog

EMG

A simpe runtime log facility

-

ScanBarcode

GS

Scan barcode using ZXing app via Intent

-

SecondScreen

M

Trivial example of one Activity (screen) starting another.

-

SendSMS

EMG

Sends an SMS

-

SensorShakeDetection

GS

Use Accellerometer to detect if the user has shaken the device.

-

SensorUpOrDown

GS

Code for r2051, Checking Whether a Device Is Facing Up or Down

-

ShareActionProviderDemo

EMG

ICS "Share" action

-

ShellCommand

EG

Run a Unix/Linux command via Runtime.exec, capture the output.

-

SimpleAccountAndSyncDemo

EMG

User account on device

-

SimpleCalendar

EMG

Calendar

-

SimpleJumper

EG

Common code for flixel-gdx-based gaming demo.

Game starts, can move left-right only, no scenery. Fails on Intel phone/emulator

SimplePool

EG

Start of a pool/billiards game using AndEngine.

-

SimpleTorchLight

EMG

Simple Torchlight/Flashlight example.

(Most devices now have a built-in control for this)

SlidingDrawer-Topdown

EMG

The main code is from the "Sliding Drawer - Top Down" recipe

-

SMSReceive

EG

Receive an incoming SMS.

-

SnackBarDemo

EMG

Snackbar (bottom message text) demo

-

SoapDemo

EMG

XML SOAP Web Service

-

SoftKeyboardEnterNext

GS

Change the Enter key to "Next" on one-line text fields.

-

SoundRec

EMG

Sound Recorder

-

Speaker

EMG

Text To Speech (TTS)

-

SpeechRecognizerDemo

GS

Speech Recognizer.

-

SpinnerDemo

EMG

Drop-down Spinner Demos

-

SpinningCubeDemo

EG

OpenGL Spinning Cube, from Marco Dinacci

-

SplashDialog

EMG

Splash screen

-

SQLiteDemos

EMG

SQLite demos

-

StandardDrawables

EMG

Use Existing Drawables

-

StaticFileRead

EMG

StaticFileRead - read a file from the application

-

StringsXML

G

Demos for "Nuances of Strings.xml" recipe.

-

TabHostDemo

EMGS

TabHost Demo: Demo of the TabHost widget, in a Dialog.

-

TabSwipeDemo

EMG

Tabbable and swipeable layout

-

TeleCorder

EMG

Telephone call recorder (in progress!)

-

TelephonyManager

EMG

Displays phone info

-

Tipster

EMGS

Full app: compute and show restaurant bill with tip

-

UniqueId

EMG

Find device’s unique ID

-

Vibrate

EMG

Make the device vibrate

-

ViewPagerDemo

EMG

Swipe among views

-

VolleyDemo

EMGS

Demo of Volley networking library

-

WheelPickerDemo

GS

Apple-style Wheel Picker Demo

-

WindowBackgroundDemo

EMG

Graphical window background

-

About

Collected code examples from the O'Reilly Android Cookbook. See README below!

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 70.8%
  • HTML 19.8%
  • JavaScript 7.4%
  • CSS 1.4%
  • PHP 0.4%
  • Shell 0.2%