• Stars
    star
    1,000
  • Rank 44,388 (Top 0.9 %)
  • Language
    Java
  • License
    Other
  • Created over 12 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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, which was at its publication 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 contains one project, and (if it’s used in the book) has a name that is cited at the end of the corresponding Recipe, under the "Source Code Download" section.

Some older 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, it has become clear that AndMore has not attracted enough developer talent to remain viable. Accordingly, the newest projects here are Android-Studio-Only. And Issue #1 calls for moving the existing mass of projects to Studio-only format. For reference, a "canonical" project would look something like this:

README.txt
app/
β”œβ”€β”€ app.iml
β”œβ”€β”€ build/
β”œβ”€β”€ build.gradle
β”œβ”€β”€ libs
β”œβ”€β”€ proguard-rules.pro
└── src
    β”œβ”€β”€ androidTest
    β”‚Β Β  └── java
    β”‚Β Β      └── com
    β”‚Β Β          └── darwinsys
    β”‚Β Β              └── circleviewgroup
    β”‚Β Β                  └── ExampleInstrumentedTest.java
    β”œβ”€β”€ main
    β”‚Β Β  β”œβ”€β”€ AndroidManifest.xml
    β”‚Β Β  β”œβ”€β”€ java
    β”‚Β Β  β”‚Β Β  └── com
    β”‚Β Β  β”‚Β Β      └── androidcookbook
    β”‚Β Β  β”‚Β Β          └── some_project_name
    β”‚Β Β  β”‚Β Β              └── MainActivity.java
    β”‚Β Β  └── res
    β”‚Β Β      β”œβ”€β”€ drawable
    β”‚Β Β      β”œβ”€β”€ layout
    β”‚Β Β      β”‚Β Β  └── activity_main.xml
    β”‚Β Β      β”œβ”€β”€ mipmap-hdpi
    β”‚Β Β      β”‚Β Β  β”œβ”€β”€ ic_launcher.png
    β”‚Β Β      β”‚Β Β  └── ic_launcher_round.png
    β”‚Β Β      β”œβ”€β”€ mipmap-*
    β”‚Β Β      └── values
    β”‚Β Β          β”œβ”€β”€ colors.xml
    β”‚Β Β          β”œβ”€β”€ strings.xml
    β”‚Β Β          └── styles.xml
    └── test
        └── java
            └── com
                └── darwinsys
                    └── circleviewgroup
                        └── ExampleUnitTest.java
build.gradle
gradlew, gradlew.bat
local.properties
settings.gradle

The table List of Projects lists each project, its author, and a short summary.

*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. Except for really old projects, where you’d have to upgrade 6 or 8 times. For these, copying newer build.gradle files from ../AndroidTemplate might be a better bet. Better yet, see https://darwinsys.com/blog/2022-07-26-modernize-android/.

DELETED/RENAMED PROJECTS

JpsTrack and the ToDo* applications have graduated to their own github projects, under https://github.com/IanDarwin.

The Hello*Test projects are moving to names starting with Testing…​

DuellingIDEs has been removed since the duel is over. Just use Android Studio.

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 Function Notes

AboutBoxDemo

Ian Darwin

A re-usable About dialog.

-

AboutInfo

Ian Darwin

Info about device and screen

-

ActionBarCompat

Ian Darwin

Simple ActionBar demo(s)

-

AddContact

Ian Darwin

Add a contact

Shows ContactsContract, content provider

AdMobDemo

Ian Darwin

Using AdMob with interstitial (inter-Activity) ads.

-

Analytics

Ian Darwin

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

-

AndroidPlot

Rachee Singh

Graphing

-

AndroidRss

Wagied Davids

RSS Reader

Works under Maven; Eclipse fails w/ Maven Configuration Problem

AppDownloader

Ian Darwin

Installs another app

Downloading, package management

AppShortcutsDemo

Ian Darwin

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

-

AppSingleton

Ian Darwin

Compilable example of the Application Singleton pattern recipe.

-

AsyncTaskDemo

Ian Darwin

Demo of AsyncTask

-

AutocompleteTextViewContacts

Ian Darwin

Contact picker with autocomplete

-

AutoUpdater

Ian Darwin

App can update itself

see AppDownloader

BackupManager

Ian Darwin

Use Android Backup scheme.

-

BluetoothConnectToDevice

Ian Darwin

Using BlueTooth to connect

-

BluetoothDemo

Ian Darwin

Bluetooth Connection

-

BrowserBookmarks

Ian Darwin

Use the now-defunct Browser Bookmarks content provider

-

CalAdder

Ian Darwin

Add appointment to Calendar

Calendar via Content Provider

CallFaker

Ian Darwin

Pretend a call happened, for testing

-

CallInterceptorIncoming

Johan Pelgrim

Intercept an incoming phone call.

-

CallInterceptorOutgoing

Johan Pelgrim

Intercept outgoing phone calls.

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

CameraIntent

Ian Darwin

CameraIntent - get the camera to take a picture, using androidx API

-

CardDemo

Ian Darwin

Demonstation of Card widget.

-

CheckBoxRadioButton

Ian Darwin

GUI demo

name says it

CircleViewGroup

Ian Darwin

Attempt at a custom layout manager.

-

ContentProviderBookmarks

Ian Darwin

List of bookmarks from Bookmarks Content Provider

Browser ContentProvider

ContentProviderList

Ian Darwin

List of ContentProviders

-

ContentProviderSample

Ashwini Shahapurkar

Implement a ContentProvider

-

ContentProviderTest

Ian Darwin

Test it

-

CordovaDemo

Ian Darwin

Simple Cordova (nee PhoneGap) cross-platform (web-based) toolkit demo.

-

CountDownTimerExample

Wagied Davids

Time-based activity

-

CryptoDemos

Ian Darwin

Cryptography anyone?

-

CurrentMoodWidget

Ian Darwin

Application Widgets have a live display on the home page, like the standard Clock program.

-

CursorLoaderDemo

Ian Darwin

How to load data properly using CursorLoader

-

CustomMenu

Ian Darwin

Menu

-

CustomSubMenu

Ian Darwin

Submenu, created programmatically

-

CustomToast

Rachee Singh

Toast

-

DatabaseFromFile

Ian Darwin

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

-

DataToCursor

Ian Darwin

Fake up a Cursor from a list of files

-

DateFormatDemo

Ian Darwin

Example of various DateFormat usages (the Android one, not java.text nor java.time).

-

DemoSmali

Ian Darwin

A pedagogic project that can be used to show off Smali for short functions.

-

DialogDemos

Ian Darwin

Dialogs

-

DragDropDemo

Ian Darwin

A simple Drag-and-drop example.

-

DreamsDemo

Ian Darwin

Demo of "Dreams" (4.x screensaver)

-

EmailTextView

Wagied Davids

Send contents of EditText via email

-

EmailWithAttachments

Marco Dinacci

Attach file to email

-

EpochJSCalendar

Wagied Davids

Java + JavaScript Epoch Calendar

-

EventListenersDemo

Daniel Fowler

5 Ways to Wire an Event Listener.

-

FacebookSdk

N/R. Pending check.

Access FB API

-

FaceFinder

Wagied Davids

Face locator API in photos

-

FileProviderDemo

Ian Darwin

Demo of FileProvider.

-

FilesystemDemos

Ian Darwin

Internal and external files.

-

FindMeX

Ian Darwin

Find Me X

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

FloatingActionButtonSnackbarDemo

Ian Darwin

Demo of 'fab' Floating Abstract Button

-

FlutterDemo

Ian Darwin

Flutter is a new SDK for cross-platform development

-

FontDemo

Ian Darwin

Using a custom font

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

FragmentsDemos

Ian Darwin

Simple Fragment and List-Detail Fragments in one project

-

Gallery

Ian Darwin

Simple Photo Gallery example.

Deprecated

GcmClient

Ian Darwin

Google Cloud Messaging - receiver

-

GcmMockServer

Ian Darwin

Google Cloud Messaging - sender

-

GeneralPrompter

Ian Darwin

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

-

HapticFeedback

Ian Darwin

Haptic Feedback recipe.

-

HelloCommandLine

Ian Darwin

HelloWorld

SDK

HelloEclipse

Ian Darwin

HelloWorld

Eclipse ADT

HelloGradle

Ian Darwin

Hello World with Gradle but NOT Studio.

-

HelloMaven

Ian Darwin

HelloWorld using Maven with android-maven-plugin.

-

HelloStudioTesting

Ian Darwin

HelloWorld of StudioTesting

-

HelloTestingTarget

AdriΓ‘n Santalla

ADT Testing - subject

-

HelloTestingTestProject

Ian Darwin

ADT Testing - Tests

-

HomeAppListView

Ian Darwin

A Home Application

Shows running a program

IconizedListView

Ian Darwin

List View with Icon

-

ImageButtonDemo

Ian Darwin

ImageButtons!

-

IntentsDemo

Ian Darwin

Intents

-

IPCDemo

Ian Darwin

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

-

IpcServiceDemo

Rupesh Chavan

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

-

JavascriptDataDemo

Ian Darwin

Getting data from Java to JavaScript and back.

-

JavaTimeDemo

Ian Darwin

Demos of java.time date/time API

Actually JSR-310 API; almost same but different package

JSONParsing

Ian Darwin

Simple example of JSON parsing using built-in JSONObject.

-

KotlinVolleyDemo

Ian Darwin

Kotlin version of Volley demo

-

LayoutBorder

Ian Darwin

Layout Border Demo Project Source for Android

-

ListViewAdvanced

Marco Dinacci

ListView

-

ListViewDemos

Ian Darwin

ListView

-

ListViewEmpty

Rachee Singh

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

-

ListViewSectionHeader

Ian Darwin

ListView with section headers

-

LocalBroadcastDemo

Ian Darwin

Local Broadcast Receiver

-

MapDemosV2

Ian Darwin

This is the Google API Maps V2 Demo.

-

MapsV2AddToProject

Ian Darwin

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

Search the Play Store

-

MaterialDemos

Ian Darwin

MaterialDesign demos

-

MediaPlayerDemo

Ian Darwin

Play media

-

MediaPlayerInteractive

Ian Darwin

Media Player demo from Marco Dinacci, thanks.

-

MediaRecorderDemo

Marco Dinacci

Simple sound recorder

-

MenuAction

Ian Darwin

Menu Action Handling

-

MessengerDemo

Ian Darwin

Using a Messenger to send requests to a Service

-

NativeFunctFromJS

Ian Darwin

Try to invoke native code from JavaScript.

-

NdkDemo

Ian Darwin

Native Development Kit

C Code

NotificationDemo

Ian Darwin

Notifications

-

NumberPickers

Ian Darwin

UI for picking numbers

-

OAuth2Demo

Ian Darwin

Demo of OAuth2 to Google Tasks.

-

OpenGlDemo

Marco Dinacci

OpenGL graphics

-

OrientationChanges

Wagied Davids

Rotation

-

OSMIntro

Rachee Singh

Basic OSM map app demo.

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

OSMOverlay

Ian Darwin

OSM Map with a map marker overlay

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

OSMTouchEvents

Ian Darwin

OSM Map with touch event handling.

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

PdfShare

Ian Darwin

Create and share a PDF

-

PermissionRequest

Ian Darwin

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

-

PhoneGapDemo

Shraddha Shravagi

HTML5 app using phonegap/cordova

-

PinchAndZoom

Ian Darwin

Pinch-and-zoom graphics demo

-

PreferencesDemo

Ian Darwin

Preferences

-

ProgressDialogDemo

Ian Darwin

Demo of a pop-up indefinite progress dialog.

-

RangeGraphDemo

Ian Darwin

Using a graphing library

-

RatingBarDemo

Ian Darwin

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

-

Rebooter

Ian Darwin

How to reboot, and why you can’t

-

RecipeList

Ian Darwin

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

-

RecyclerViewDemo

Ian Darwin

Demo of RecyclerView, the faster ListView.

-

RemoteSystemsTempFiles

Ian Darwin

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

-

RGraphDemo

Wagied Davids

Using a graphing library

-

RoomDemo

Ian Darwin

Demo of Room, the official Android ORM.

-

RuntimeLog

Ian Darwin

A simpe runtime log facility

-

ScanBarcode

Ian Darwin

Scan barcode using ZXing app via Intent

-

SecondScreen

Ian Darwin

Trivial example of one Activity (screen) starting another.

-

SendSMS

Colin Wilcox

Sends an SMS

-

SensorShakeDetection

Thomas Manthey

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

-

SensorUpOrDown

Rachee Singh

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

-

ServiceDemos

Ian Darwin

Demo a couple of kinds of Service.

-

ShareActionProviderDemo

Ian Darwin

ICS "Share" action

-

ShellCommand

Ian Darwin

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

-

SimpleAccountAndSyncDemo

Ian Darwin

User account on device

-

SimpleCalendar

Ian Darwin

Calendar

-

SimpleDialer

Ian Darwin

Trivial Dialer - launches Dialer app via Intent

-

SimpleJumper

Wagied Davids

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

Start of a pool/billiards game using AndEngine.

-

SimpleTorchLight

Saketkumar Srivastav

Simple Torchlight/Flashlight example.

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

SlidingDrawer-Topdown

Wagied Davids

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

-

SMSReceive

Ian Darwin

Receive an incoming SMS.

-

SnackBarDemo

Ian Darwin

Snackbar (bottom message text) demo

-

SoapDemo

Ian Darwin

XML SOAP Web Service

-

SoftKeyboardEnterNext

Jonathan Fuerth

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

-

SoundRec

Ian Darwin

Sound Recorder

-

Speaker

Ian Darwin

Text To Speech (TTS)

-

SpeechRecognizerDemo

Ian Darwin

Speech Recognizer.

-

SpinnerDemo

Ian Darwin

Drop-down Spinner Demos

-

SpinningCubeDemo

Marco Dinacci

OpenGL Spinning Cube, from Marco Dinacci

-

SplashDialog

Rachee Singh

Splash screen

-

SQLiteDemos

Ian Darwin

SQLite demos

-

StandardDrawables

Ian Darwin

Use Existing Drawables

-

StaticFileRead

Ian Darwin

StaticFileRead - read a file from the application

-

StringsXML

Daniel Fowler

Demos for "Nuances of Strings.xml" recipe.

-

TabHostDemo

Ian Darwin

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

-

TabSwipeDemo

Ian Darwin

Tabbable and swipeable layout

-

TeleCorder

Ian Darwin

Telephone call recorder (in progress!)

-

TelephonyManager

Pratik Rupwal

Displays phone info

-

TestingWithEspresso

Ian Darwin

HelloWorld of EspressoTesting

-

Tipster

Sunit Katkar

Full app: compute and show restaurant bill with tip

-

UniqueId

Ian Darwin

Find device’s unique ID

-

Vibrate

Rachee Singh

Make the device vibrate

-

ViewPagerDemo

Ian Darwin

Swipe among views

-

VolleyDemo

Ian Darwin

Demo of Volley networking library

-

WheelPickerDemo

Wagied Davids

Apple-style Wheel Picker Demo

-

WindowBackgroundDemo

Ian Darwin

Graphical window background

-

More Repositories

1

javasrc

Ian's Collected code examples from the O'Reilly Java Cookbook & elsewhere
Java
235
star
2

patterns-demos

Examples of Design Patterns in Java
Java
79
star
3

darwinsys-api

Ian Darwin's semi-random collection of Java APIs, all subject to change without notice.
Java
76
star
4

OpenLookCDROM

Final resting place for an archive of the historic artifact "OPEN LOOK and XView CD-ROM"
C
33
star
5

edj

Pronounced "edge". Tiny subset of unix ed(1) in Java.
Java
15
star
6

date4j

Code for date4j.net's simple date API, with a POM file, for upload to Maven Central.
Java
13
star
7

bigmailers

List of "big mailers" for OpenBSD's 'smtpctl spf walk' mechanism
Shell
11
star
8

AndroidOrm

Comparison of various technologies to build a local database as part of an Android app.
Java
10
star
9

pdfshow

Deliver/present talks from PDFs - A simple PDF presenter oriented towards slideshow decks in PDF form
Java
8
star
10

cjp-examples

Testing example programs from the Checking Java Programs book and videos
Java
8
star
11

scripts

A collection of UNIX scripts from mid-1980's to the present to the future.
Shell
7
star
12

SCCS

Re-implementation of SCCS, the first Version Control System for UNiX (before Linux existed).
C
5
star
13

hoc

High Order Calculator from Kernighan & PIke "The Unix Programming Environment"
C
5
star
14

pysrc

Collected Python code samples from using and teaching the language. Scroll down to see the README!
Python
5
star
15

remotecommand

Simple example of Command pattern over remote connection (RMI).
Java
5
star
16

mgdiff

mgdiff - an historical X-based diff viewer
C
3
star
17

spiff

Daniel Nachbar's spiff - makes "controlled approximate comparisons between files"
C
3
star
18

obscripts

Scripts that are primarily useful on OpenBSD
Shell
3
star
19

psplugins

Photoshop plugins from a bygone era (unlikely to be usable w/o significant updating).
C
3
star
20

jwf-impls

Simple Java "signup" sample webapps implemented in various frameworks.
Java
3
star
21

clublist

A simple "List Detail" Club Membership site with JSF, EJB, JPA, DeltaSpike Data, &c.
Java
3
star
22

rnotro

Truly ancient code to convert DEC Runoff documents to Unix/Linux troff
C
2
star
23

tinypad

A trivial text editor a la SimpleText, Notepad, etc. Written in Java
Java
2
star
24

ed

A terribly ancient version of the one true, but terribly ancient, line editor.
C
2
star
25

annabot

Annotations usage tester for Java
Java
2
star
26

login-filter

A Java Servlet Filter to do login processing.
Java
2
star
27

idiff

Kernighan & PIke interactive diff, slightly enhanced.
C
2
star
28

CGIServlet

Tomcat's CGI Servlet, extracted for use in other Java EE containers
Java
2
star
29

CreateProjects

Create a series of Eclipse projects for a course (typically after running makehandsons)
Java
2
star
30

jpademo

A ton of JPA and Hibernate tutorial demos, both APIs demo'd on the same entities
Java
2
star
31

yajinstaller

Yet Another (unfinished) Java Installer
Java
1
star
32

jpstrack.android

JpsTrack is a Map Maker application for OpenStreetMap.org. This is the Android part of it (needs JPSTrack to build!)
Java
1
star
33

TodoMore

Top-level organizing module for TodoMore(TM), a geekish ToDo application.
TSQL
1
star
34

mvn-archetype-android

Maven Archetype for Maven-Eclipse-Gradle-Studio-buildable Android
Shell
1
star
35

TodoAndroid

Android client for TodoMore
Java
1
star
36

TextToPpt

Convert tab-indented slide outline into modern PPTX
Java
1
star
37

ssl_redirector

A simple Java EE redirector from http to https
Java
1
star
38

macsetautoboot

Lets my Mac Mini auto-reboot on OpenBSD
C
1
star
39

Randomness

Examples for the Oracle Java Magazine article on Java 17 randomness.
Java
1
star
40

CrashBurnFree

The maximally minimalistic Java Crash Reporting System.
Java
1
star
41

jpstrack.lib

JpsTrack is a Map Maker application for OpenStreetMap.org. This is the JavaSE and library part of it.
Java
1
star
42

TodoAndroidFirebase

A variant of TodoMore that uses Firebase instead of our own REST service; not inter-operable with the rest.
Java
1
star
43

javaCompiler

Import of Marco Trudel's javaCompiler project "Develop with Java 1.5, deploy native executables for windows, linux and mac! SWT, JFace, AWT and Swing is supported."
Java
1
star
44

AndroidTemplate

Minimal Android Template Application created for API 32
Java
1
star