Android head first java

Head First Android Development

1 Get the book

By far the best book to get you quickly up to speed with Android Development

— Andy Parker, ☆☆☆☆☆ Review, Amazon.com

Head First Android Development cuts through the fog of dozens of components, hundreds of API calls and focuses on the core skills you need. Do you want a book that is more than simply a reproduction of the online documentation? A book that is more like a course, taking you step-by-step through the development of real applications, just as if an experienced Android developer was sitting right next to you? This book teaches Android development by getting you to do Android development.

2 Get the source code

On this page you can find extra information and source code for the book Head First Android Development.

You can download the source code in zip or tar.gz format. Or, if you have git installed, you can get your own copy of the source code repository by typing this on the command line:

And don’t forget: we’re going to continue adding useful information to the Head First Android Wiki.

3 Table of contents

Chapter 1: Getting started

Android has been taking the world by storm. Everybody wants a smart phone or tablet, and Android devices are hugely popular. In this book we’ll teach you how to develop your own apps, and we’ll start by getting you to build a basic app and run it on an Android Virtual Device. Along the way you’ll meet some of the basic components of all Android apps such as activities and layouts. All you need is a little Java know-how…

Apps you’ll build:

Chapter 2: Building Interactive Apps

Most apps need to respond to the user in some way. And in this chapter you’ll see how you can make your apps a bit more interactive. You’ll see how you can get your app to do something in response to what the user does, and how to get your activity and layout talking to each other like best buddies. And along the way we’ll take you a bit deeper into how Android actually works by introducing you to R, the hidden gem that glues everything together.

Apps you’ll build:

Chapter 3: Multiple activities and intents

Most apps need more than one activity. So far we’ve just looked at single-activity apps, which is fine for simple apps. But when things get more complicated, just having the one activity won’t cut it. We’re going to show you how to build apps with multiple activities, and how you can get your apps talking to each other using intents. We’ll also look at how you can use intents to go beyond the boundaries of your app and make activities in other apps on your device perform actions. Things just got a whole lot more powerful…

Apps you’ll build:

Chapter 4: The activity lifecycle

Activities form the foundation of every Android app. So far you’ve seen how to create activities, and made one activity start another using an intent. But what’s really going on beneath the hood? In this chapter we’re going to dig a little deeper into the activity lifecycle. What happens when an activity is created and destroyed? Which methods get called when an activity is made visible and appears in the foreground, and which get called when the activity loses the focus and is hidden? And how do you save and restore your activity’s state?

Apps you’ll build:

Chapter 5: The user interface

Let’s face it, you need to know how to create great layouts. If you’re building apps you want people to use, you need to make sure they look just the way you want. So far we’ve only scratched the surface when it comes to creating layouts, so it’s time to look a little deeper. We’ll introduce you to more types of layout you can use, and we’ll also take you on a tour of the main GUI components and how you use them. By the end of the chapter you’ll see that even though they all look a little different, all layouts and GUI components have more in common than you might think.

Читайте также:  Блютуз геймпад для андроид как настроить

Chapter 6: List views and adapters

Want to know how to best structure your Android app? You’ve learned some of the basic pieces that are user to build apps, and now it’s time to get organized. In this chapter we’ll show you how you can take a bunch of ideas and structure them to build an awesome app. We’ll show you how lists of data can form the core part of your app design, and how linking them together can create a powerful and easy-to-use app. Along the way, you get your first glimpse of using event listeners and adapters to make your app more dynamic.

Apps you’ll build:

Chapter 7: Fragments

You’ve seen how to create apps that work in the same way irrespective of the device they’re running on. But what if you want your app to look and behave differently depending on whether it’s running on a phone or a tablet? In this chapter we’ll show you how to make your app choose the most appropriate layout for the device screen size. We’ll also introduce you to fragments, a way of creating modular code components that can be reused by different activities.

Apps you’ll build:

Chapter 8: Nested fragments

You’ve seen how using fragments in activities allow you to reuse code and make your apps more flexible. In this chapter we’re going to show you how to nest one fragment inside another. You’ll see how to use the child fragment manager to tame unruly fragment transactions. And along the way you’ll see why knowing the differences between activities and fragments is so important.

Apps you’ll build:

Chapter 9: Action Bars

Everybody likes a shortcut. And in this chapter you’ll see how to add shortcuts to your apps using action bars. We’ll show you how to start other activities by adding action items to your action bar, how to share content with other apps using the share action provider, and how to navigate up your app’s hierarchy by implementing the action bar’s Up button. Along the way you’ll see how to give your app a consistant look and feel using themes, and introduce you to the Android support library package.

Apps you’ll build:

Chapter 10: Navigation Drawers

Apps are so much better when they’re easy to navigate. In this chapter we’re going to introduce you to the navigation drawer, a slide-out panel that appears when you swipe your finger or click an icon on the action bar. We’ll show you how to use it to display a list of links that take you to all the major hubs of your app. You’ll also see how switching fragments makes those hubs easy to get to and fast to display.

Apps you’ll build:

Chapter 11: SQLite databases

If you’re recording high scores or saving tweets, your app will need to store data. And on Android you usually keep your data safe inside a SQLite database. In this chapter, we’ll show you how to create a database, add tables to it, and prepopulate it with data, all with the help of the friendly SQLite helper. You’ll then see how you can cleanly roll out upgrades to your database structure, and how to downgrade it if you need pull any changes.

Apps you’ll build:

Chapter 12: Cursors and AsyncTasks

So how do you connect your app to a SQLite database? So far you’ve seen how to create a SQLite database using a SQLite helper. The next step is to get your activities to access it. In this chapter you’ll find out how to use cursors to get data from the database, how to navigate through cursors and how to get data from them. You’ll then find out how to use cursor adapters to connect them to list views. Finally, you’ll see how writing efficient multi-threaded code with AsyncTasks will keep your app speedy.

Apps you’ll build:

Chapter 13: Services

There are some operations you want to keep on running irrespective of which app has the focus. As an example, If you start playing a music file in a music app, you probably expect it to keep on playing when you switch to another app. In this chapter you’ll see how to use Services to deal with situations just like this. Along the way you’ll see how use some of Android’s built-in services. You’ll see how to to keep your users informed with the notification service, and how the location service can tell you where you’re located.

Apps you’ll build:

Chapter 14: Material Design

With API level 21, Google introduced Material Design. In this chapter we’ll look at what Material Design is, and how to make your apps fit in with it. We’ll start by introducing you to card views you can reuse across your app for a consistent look and feel. Then we’ll introduce you to the recycler view, the list view’s flexible friend. Along the way you’ll see how to create your own adapters, and how to completely change the look of a recycler view with just two lines of code.

Читайте также:  Cataclysm dda для андроид

Apps you’ll build:

Appendix 1: ART–The Android Runtime

Android apps need to run on devices with low powered processors and very little memory. Java apps can take up a lot of memory and because they run inside their own Java Virtual Machine (JVM), Java apps can take a long time to start when they’re running on low- powered machines. Android deals with this by not using the JVM for its apps. Instead it uses a very different virtual machine called the Android Runtime (ART). In this appendix we’ll look at how ART gets your Java apps to run well on a small, low-powered device.

Appendix 2: ADB–The Android Debug Bridge

In this book we’ve focused on using an IDE for all your Android needs. But there are times when using a command tool can be plain useful, like those times when Android Studio can’t see your Android device but you just know it’s there. In this chapter we’ll introduce you to the Android Debug Bridge (or adb), a command line tool you can use to communicate with the emulator or Android devices.

Appendix 3: The Android Emulator

Ever felt like you were spending all your time waiting for the emulator? There’s no doubt that using the Android emulator is useful. It allows you to see how your app will run on devices other than the physical ones you have access to. But at times it can feel a little… sluggish. In this appendix we’re going to explain why the emulator can seem slow, Even better, we’ll give you a few tips we’ve learned for speeding it up.

Appendix 4: Top Ten Things (We Didn’t Cover)

Even after all that, there’s still a little more. There are just a few more things we think you need to know. We wouldn’t feel right about ignoring them, and we really wanted to give you a book you’d be able to lift without extensive training at the local gym. Before you put down the book, read through these tidbits.

Источник

Книга «Head First. Программирование для Android»

Привет, Хаброжители! Мы пополнили серию «Head First O’Reilly» новой книгой:

В этой книге мы научим вас разрабатывать собственные приложения, а также покажем, как построить простое приложение и запустить его на виртуальном устройстве Android. Вы узнаете, как структурировать приложения, познакомитесь с дизайном интерфейсов, научитесь создавать базы данных, заставите работать свои приложения на любых смартфонах и планшетах. Попутно будут рассмотрены основные компоненты приложений Android — такие, как активности и макеты. Все, что от вас потребуется, — некоторые базовые знания Java.

Для кого написана эта книга?


Если вы ответите «да» на все следующие вопросы:
1. Вы уже умеете программировать на Java?
2. Вы хотите достичь мастерства в области разработки приложения для Android, создать следующий бестселлер в области программных продуктов, заработать целое состояние и купить собственный остров?
3. Вы предпочитаете заниматься практической работой и применять полученные знания вместо того, чтобы выслушивать нудные многочасовые лекции?

тогда эта книга для вас.

Кому эта книга не подойдет?


Если вы ответите «да» на один из следующих вопросов:
1. Вам нужен краткий вводный курс или справочник по разработке приложений для Android?
2. Вы скорее пойдете к зубному врачу, чем опробуете что-нибудь новое? Вы считаете, что в книге по Android не должно быть веселых человечков, а если читатель будет помирать со скуки — еще лучше?

… эта книга не для вас.

Эта книга для тех, кто хочет учиться.


Как мы что-то узнаем? Сначала нужно это «что-то» понять, а потом не забыть. Затолкать в голову побольше фактов недостаточно. Согласно новейшим исследованиям в области когнитивистики, нейробиологии и психологии обучения, для усвоения материала требуется что-то большее, чем простой текст на странице. Мы знаем, как заставить ваш мозг работать.

Основные принципы серии «Head First»:

Наглядность. Графика запоминается лучше, чем обычный текст, и значительно повышает эффективность восприятия информации (до 89 % по данным исследований). Кроме того, материал становится более понятным. Текст размещается на рисунках, к которым он относится, а не под ними или на соседней странице — и вероятность успешного решения задач, относящихся к материалу, повышается вдвое.

Разговорный стиль изложения. Недавние исследования показали, что при разговорном стиле изложения материала (вместо формальных лекций) улучшение результатов на итоговом тестировании достигает 40 %. Рассказывайте историю, вместо того чтобы читать лекцию. Не относитесь к себе слишком серьезно. Что привлечет ваше внимание: занимательная беседа за столом или лекция?

Активное участие читателя. Пока вы не начнете напрягать извилины, в вашей голове ничего не про-изойдет. Читатель должен быть заинтересован в результате; он должен решать задачи, формулировать выводы и овладевать новыми знаниями. А для этого необходимы упражнения и каверзные вопросы, в решении которых задействованы оба полушария мозга и разные чувства.

Читайте также:  Как перепрошить андроид приставку h96 max

Привлечение (и сохранение) внимания читателя. Ситуация, знакомая каждому: «Я очень хочу изучить это, но засыпаю на первой странице». Мозг обращает внимание на интересное, странное, притягательное, неожиданное. Изучение сложной технической темы не обязано быть скучным. Интересное узнается намного быстрее.

Обращение к эмоциям. Известно, что наша способность запоминать в значительной мере зависит от эмоционального сопереживания. Мы запоминаем то, что нам небезразлично. Мы запоминаем, когда что-то чувствуем. Нет, сантименты здесь ни при чем: речь идет о таких эмоциях, как удивление, любопытство, интерес и чувство «Да я крут!» при решении задачи, которую окружающие считают сложной — или когда вы понимаете, что разбираетесь в теме лучше, чем всезнайка Боб из технического отдела.

Примите к сведению


Это учебник, а не справочник. Мы намеренно убрали из книги все, что могло бы помешать изучению материала, над которым вы работаете. И при первом чтении книги начинать следует с самого начала, потому что книга предполагает наличие у читателя определенных знаний и опыта.

Предполагается, что у вас уже есть опыт программирования на языке Java.
Мы будем строить приложения Android с использованием Java и XML. Предполагается, что вы уже знакомы с языком программирования Java. Если вы еще никогда не писали программы на Java, прочитайте Head First Java, прежде чем браться за эту книгу.

Мы начинаем строить приложения с первой главы.
Хотите — верьте, хотите — нет, но даже если вы никогда не программировали для Android, вы все равно можете сходу взяться за создание приложений. Заодно вы познакомитесь с Android Studio, основной интегрированной средой разработки для Android.

Примеры создавались для обучения.
Во время работы над книгой мы построим несколько разных приложений. Некоторые из них очень малы, чтобы вы могли сосредоточиться на конкретных аспектах Android. Другие, более крупные приложения показывают, как разные компоненты работают в сочетании друг с другом. Мы не будем доводить до конца все части всех приложений, но ничто не мешает вам экспериментировать с ними самостоятельно — это часть учебного процесса. Исходный код всех приложений доступен по адресу: tinyurl.com/HeadFirstAndroid.

Упражнения ОБЯЗАТЕЛЬНЫ.
Упражнения являются частью основного материала книги. Одни упражнения способствуют запоминанию материала, другие помогают лучше понять его, третьи ориентированы на его практическое применение. Не пропускайте упражнения.

Повторение применяется намеренно.
У книг этой серии есть одна принципиальная особенность: мы хотим, чтобы вы действительно хорошо усвоили материал. И чтобы вы запомнили все, что узнали. Большинство справочников не ставит своей целью успешное запоминание, но это не справочник, а учебник, поэтому некоторые концепции излагаются в книге по нескольку раз.

Упражнения «Мозговой штурм» не имеют ответов.
В некоторых из них правильного ответа вообще нет, в других вы должны сами решить, насколько правильны ваши ответы (это является частью процесса обучения). В некоторых упражнениях «Мозговой штурм» приводятся подсказки, которые помогут вам найти нужное направление.

Об авторах


Дон Гриффитс начала с изучения математики в одном из ведущих университетов Великобритании, где получила диплом с отличием. Затем она продолжила карьеру в области разработки программного обеспечения; ее опыт работы в IT-отрасли составляет 20 лет.
Прежде чем браться за книгу Head First. Программирование для Android, Дон написала уже три книги из серии Head First (Head First Statistics, Head First 2D Geometry и Head First C), а также участвовала в работе над другими книгами этой серии.
Когда Дон не работает над книгами серии Head First, она обычно совершенствует свое мастерство тай цзи, увлекается чтением, бегом, плетением кружев и кулинарией. Но больше всего ей нравится проводить время с ее замечательным мужем Дэвидом.

Дэвид Гриффитс увлекся программированием в 12 лет, после документального фильма о работе Сеймура Пейперта. В 15 лет он написал реализацию языка программирования LOGO, созданного Пейпертом. После изучения теоретической математики в университете он начал писать программы для компьютеров и статьи в журналах. Он работал преподавателем гибких методологий разработки, разработчиком и дежурным по гаражу (хотя и в другом порядке). Дэвид пишет программы на 10 языках и прозу на одном. А когда он не занят программированием, литературной работой или преподаванием, он проводит свободное время в путешествиях со своей очаровательной женой — и соавтором — Дон. До Head First. Программирование для Android Дэвид написал еще три книги из серии Head First: Head First Rails, Head First Programming и Head First C.

Научные редакторы


Эдвард Ю Шун Вон увлекается программированием с того момента, когда он написал свою первую строку кода Haskell в 2006-м. В настоящее время он работает над событийным управлением торговыми операциями в центре Лондона. Он щедро делится своей страстью к разработке с сообществами London Java Community и Software Craftsmanship Community. В свободное время Эдварда можно найти на футбольном поле или за подготовкой игровых обзоров для YouTube (@arkangelofkaos).

Тони Уильямс — разработчик с опытом программирования на языке Java и создания приложений для Android.

Более подробно с книгой можно ознакомиться на сайте издательства
Оглавление
Отрывок

Для Хаброжителей скидка 25% по купону — Head First Android

Источник

Оцените статью