/Android-Cookbook-Examples

Contributed code examples from O'Reilly Android Cookbook. See #user-content-table README below!

Primary LanguageJavaOtherNOASSERTION

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).

The started-in-Eclipse projects also have configuration files to allow them to be opened in Android Studio.

During the runup to the second edition of the book, AndMore appeared to be a viable project to maintain Android Eclipse development. However, over time, it has become clear that AndMore has not attracted enough developer talent to remain viable. Accordingly, the newest projects here are Android-Studio-Only.

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

*Note that, since Gradle and the Gradle Android Plugin need to be updated just about every time your run Android Studio, there is no attempt made to keep things up-to-date here; just let Studio do its upgrade thing for you and all will be well. They promise.

TL;DR: Build Many Projects with Apache Maven

Prerequisites: Java 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. The Author names have recently been added; if I have missed or mis-attributed any, please let me know and I will happily correct them. You (and I) know who you are.

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

AboutBoxDemo

Ian Darwin

GS

A re-usable About dialog.

-

AboutInfo

Ian Darwin

EMGS

Info about device and screen

-

ActionBarCompat

Ian Darwin

GS

Simple ActionBar demo(s)

-

AddContact

Ian Darwin

EMG

Add a contact

Shows ContactsContract, content provider

AdMobDemo

Ian Darwin

GS

Using AdMob with interstitial (inter-Activity) ads.

-

Analytics

Ian Darwin

EMGS

Ashwini’s Google Analytics for Android Demo, slightly updated.

-

AndroidPlot

Rachee Singh

EMG

Graphing

-

AndroidRss

Wagied Davids

EMG

RSS Reader

Works under Maven; Eclipse fails w/ Maven Configuration Problem

AppDownloader

Ian Darwin

MGS

Installs another app

Downloading, package management

AppShortcutsDemo

Ian Darwin

GS

Shows App Shortcuts, which appear with long-press on app’s launcher icon.

-

AppSingleton

Ian Darwin

GS

Compilable example of the Application Singleton pattern recipe.

-

AutocompleteTextViewContacts

Ian Darwin

EMG

Contact picker with autocomplete

-

AutoUpdater

Ian Darwin

EMG

App can update itself

see AppDownloader

BackupManager

Ian Darwin

EMG

Use Android Backup scheme.

-

BluetoothDemo

Ian Darwin

EMG

Bluetooth Connection

-

CalAdder

Ian Darwin

EMG

Add appointment to Calendar

Calendar via Content Provider

CallFaker

Ian Darwin

EMG

Pretend a call happened, for testing

-

CallInterceptorIncoming

Johan Pelgrim

EGS

Intercept an incoming phone call.

-

CallInterceptorOutgoing

Johan Pelgrim

EG

Intercept outgoing phone calls.

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

CameraIntent

Ian Darwin

GS

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

-

CardDemo

Ian Darwin

GS

Demonstation of Card widget.

-

CheckBoxRadioButton

Ian Darwin

EMG

GUI demo

name says it

ContentProviderBookmarks

Ian Darwin

EMG

List of bookmarks from Bookmarks Content Provider

Browser ContentProvider

ContentProviderList

Ian Darwin

EMG

List of ContentProviders

-

ContentProviderSample

Ashwini Shahapurkar

EMG

Implement a ContentProvider

-

ContentProviderTest

Ian Darwin

EMG

Test it

-

CountDownTimerExample

Wagied Davids

EMG

Time-based activity

-

CurrentMoodWidget

Ian Darwin

EMG

Application Widget

-

CursorLoaderDemo

Ian Darwin

EMG

How to load data properly using CursorLoader

-

CustomMenu

Ian Darwin

EMG

Menu

-

CustomSubMenu

Ian Darwin

GS

Submenu, created programmatically

-

CustomToast

Rachee Singh

EMG

Toast

-

DatabaseFromFile

Ian Darwin

EMG

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

-

DataToCursor

Ian Darwin

EMG

Fake up a Cursor from a list of files

-

DateFormatDemo

Ian Darwin

GS

Example of various DateFormat usages.

-

DialogDemos

Ian Darwin

EMG

Dialogs

-

DragDropDemo

Ian Darwin

EG

A simple Drag-and-drop example.

-

DreamsDemo

Ian Darwin

EMG

Demo of "Dreams" (4.x screensaver)

-

EmailTextView

Wagied Davids

EMG

Send contents of EditText via email

-

EmailWithAttachments

Marco Dinacci

EMG

Attach file to email

-

EpochJSCalendar

Wagied Davids

EMG

Java + JavaScript Epoch Calendar

-

EventListenersDemo

Daniel Fowler

M

5 Ways to Wire an Event Listener.

-

FacebookSdk

Ian Darwin

EMG

Access FB API

-

FaceFinder

Wagied Davids

EMG

Face locator API in photos

-

FileProviderDemo

Ian Darwin

GS

Demo of FileProvider.

-

FilesystemDemos

Ian Darwin

MGS

Internal and external files.

-

FindMeX

Ian Darwin

EG

Find Me X

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

FloatingActionButtonSnackbarDemo

Ian Darwin

GS

Demo of 'fab' Floating Abstract Button

-

FontDemo

Ian Darwin

EMG

Using a custom font

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

FragmentsDemos

Ian Darwin

GS

Simple Fragment and List-Detail Fragments in one project

-

Gallery

Ian Darwin

EMG

Simple Photo Gallery example.

Deprecated

GcmClient

Ian Darwin

EMG

Google Cloud Messaging - receiver

-

GcmMockServer

Ian Darwin

EMG

Google Cloud Messaging - sender

-

GeneralPrompter

Ian Darwin

EG

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

-

HapticFeedback

Ian Darwin

GS

Haptic Feedback recipe.

-

HelloCommandLine

Ian Darwin

EMAG

HelloWorld

SDK

HelloEclipse

Ian Darwin

EMG

HelloWorld

Eclipse ADT

HelloEspressoTesting

Ian Darwin

GS

HelloWorld of EspressoTesting

-

HelloGradle

Ian Darwin

GS

Hello World with Gradle but NOT Studio.

-

HelloMaven

Ian Darwin

EMG

HelloWorld using Maven with android-maven-plugin.

-

HelloStudioTesting

Ian Darwin

GS

HelloWorld of StudioTesting

-

HelloTestingTarget

Adrián Santalla

EMAG

ADT Testing - subject

-

HelloTestingTestProject

Ian Darwin

EMAG

ADT Testing - Tests

-

HomeAppListView

Ian Darwin

EMG

A Home Application

Shows running a program

IconizedListView

Ian Darwin

EMG

List View with Icon

-

IntentsDemo

Ian Darwin

EMG

Intents

-

IPCDemo

Ian Darwin

GS

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

-

IpcServiceDemo

Rupesh Chavan

GS

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

-

JavascriptDataDemo

Ian Darwin

EMG

Getting data from Java to JavaScript and back.

-

JavaTimeDemo

Ian Darwin

MGS

Demos of java.time date/time API

Actually JSR-310 API; almost same but different package

JSONParsing

Ian Darwin

EG

Simple example of JSON parsing using built-in JSONObject.

-

KotlinVolleyDemo

Ian Darwin

GS

Kotlin version of Volley demo

-

LayoutBorder

Ian Darwin

G

Layout Border Demo Project Source for Android

-

ListViewAdvanced

Marco Dinacci

EMG

ListView

-

ListViewDemos

Ian Darwin

EMGS

ListView

-

ListViewEmpty

Rachee Singh

EMGS

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

-

ListViewSectionHeader

Ian Darwin

EMG

ListView with section headers

-

LocalBroadcastDemo

Ian Darwin

EMG

Local Broadcast Receiver

-

MapDemosV2

Ian Darwin

EMG

This is the Google API Maps V2 Demo.

-

MapsV2AddToProject

Ian Darwin

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

Ian Darwin

EMG

Search the Play Store

-

MaterialDemos

Ian Darwin

EMG

MaterialDesign demos

-

MediaPlayerDemo

Ian Darwin

EMG

Play media

-

MediaPlayerInteractive

Ian Darwin

EG

Media Player demo from Marco Dinacci, thanks.

-

MediaRecorderDemo

Marco Dinacci

EMG

Simple sound recorder

-

MenuAction

Ian Darwin

EMG

Menu Action Handling

-

NdkDemo

Ian Darwin

EMG

Native Development Kit

C Code

NotificationDemo

Ian Darwin

EMG

Notifications

-

NumberPickers

Ian Darwin

EMG

UI for picking numbers

-

OAuth2Demo

Ian Darwin

GS

Demo of OAuth2 to Google Tasks.

-

OpenGlDemo

Marco Dinacci

EMG

OpenGL graphics

-

OrientationChanges

Wagied Davids

EMG

Rotation

-

OSMIntro

Rachee Singh

EMG

Basic OSM map app demo.

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

OSMOverlay

Ian Darwin

EMG

OSM Map with a map marker overlay

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

OSMTouchEvents

Ian Darwin

EMG

OSM Map with touch event handling.

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

PdfShare

Ian Darwin

EMG

Create and share a PDF

-

PermissionRequest

Ian Darwin

G

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

-

PhoneGapDemo

Shraddha Shravagi

EMG

HTML5 app using phonegap/cordova

-

PinchAndZoom

Ian Darwin

GS

Pinch-and-zoom graphics demo

-

PreferencesDemo

Ian Darwin

EMG

Preferences

-

ProgressDialogDemo

Ian Darwin

GS

Demo of a pop-up indefinite progress dialog.

-

RangeGraphDemo

Ian Darwin

EMG

Using a graphing library

-

RatingBarDemo

Ian Darwin

EGS

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

-

Rebooter

Ian Darwin

EMG

How to reboot, and why you can’t

-

RecipeList

Ian Darwin

EMGS

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

-

RecyclerViewDemo

Ian Darwin

GS

Demo of RecyclerView, the faster ListView.

-

RemoteSystemsTempFiles

Ian Darwin

EM

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

-

RGraphDemo

Wagied Davids

EMG

Using a graphing library

-

RoomDemo

Ian Darwin

GS

Demo of Room, the official Android ORM.

-

RuntimeLog

Ian Darwin

EMG

A simpe runtime log facility

-

ScanBarcode

Ian Darwin

GS

Scan barcode using ZXing app via Intent

-

SecondScreen

Ian Darwin

M

Trivial example of one Activity (screen) starting another.

-

SendSMS

Colin Wilcox

EMG

Sends an SMS

-

SensorShakeDetection

Thomas Manthey

GS

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

-

SensorUpOrDown

Rachee Singh

GS

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

-

ShareActionProviderDemo

Ian Darwin

EMG

ICS "Share" action

-

ShellCommand

Ian Darwin

EG

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

-

SimpleAccountAndSyncDemo

Ian Darwin

EMG

User account on device

-

SimpleCalendar

Ian Darwin

EMG

Calendar

-

SimpleDialer

Ian Darwin

EMGS

Trivial Dialer - launches Dialer app via Intent

-

SimpleJumper

Wagied Davids

EG

Common code for flixel-gdx-based gaming demo.

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

SimplePool

Wagied Davids

EG

Start of a pool/billiards game using AndEngine.

-

SimpleTorchLight

Saketkumar Srivastav

EMG

Simple Torchlight/Flashlight example.

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

SlidingDrawer-Topdown

Wagied Davids

EMG

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

-

SMSReceive

Ian Darwin

EG

Receive an incoming SMS.

-

SnackBarDemo

Ian Darwin

EMG

Snackbar (bottom message text) demo

-

SoapDemo

Ian Darwin

EMG

XML SOAP Web Service

-

SoftKeyboardEnterNext

Jonathan Fuerth

GS

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

-

SoundRec

Ian Darwin

EMG

Sound Recorder

-

Speaker

Ian Darwin

EMG

Text To Speech (TTS)

-

SpeechRecognizerDemo

Ian Darwin

GS

Speech Recognizer.

-

SpinnerDemo

Ian Darwin

EMG

Drop-down Spinner Demos

-

SpinningCubeDemo

Marco Dinacci

EG

OpenGL Spinning Cube, from Marco Dinacci

-

SplashDialog

Rachee Singh

EMG

Splash screen

-

SQLiteDemos

Ian Darwin

EMG

SQLite demos

-

StandardDrawables

Ian Darwin

EMG

Use Existing Drawables

-

StaticFileRead

Ian Darwin

EMG

StaticFileRead - read a file from the application

-

StringsXML

Daniel Fowler

G

Demos for "Nuances of Strings.xml" recipe.

-

TabHostDemo

Ian Darwin

EMGS

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

-

TabSwipeDemo

Ian Darwin

EMG

Tabbable and swipeable layout

-

TeleCorder

Ian Darwin

EMG

Telephone call recorder (in progress!)

-

TelephonyManager

Pratik Rupwal

EMG

Displays phone info

-

Tipster

Sunit Katkar

EMGS

Full app: compute and show restaurant bill with tip

-

UniqueId

Ian Darwin

EMG

Find device’s unique ID

-

Vibrate

Rachee Singh

EMG

Make the device vibrate

-

ViewPagerDemo

Ian Darwin

EMG

Swipe among views

-

VolleyDemo

Ian Darwin

EMGS

Demo of Volley networking library

-

WheelPickerDemo

Wagied Davids

GS

Apple-style Wheel Picker Demo

-

WindowBackgroundDemo

Ian Darwin

EMG

Graphical window background

-