Mark Murphy - Beginning Android

Здесь есть возможность читать онлайн «Mark Murphy - Beginning Android» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: New York, Год выпуска: 2009, ISBN: 2009, Издательство: Apress, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Beginning Android: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Beginning Android»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Master Android from first principles and begin the journey toward your own successful Android applications!
Dear Reader,
First, welcome to the world of Android! We’re entering a new era of mobile application development, one marked by open platforms and open source, to take ‘walled gardens’ and make them green houses for any and all to participate in. Android is relatively easy for developers, and I believe that this innovation will help generate a large ecosystem of developers and consumers within a very short time. This means that budding developers such as yourself will have many opportunities to design and build your own applications and you’ll have a huge and hungry customer base.
Second, welcome to the book! Its purpose is to start you on your way with building Android applications, and to help you master the learning curve. Android is already a rich framework, comparable in many ways to the richness Android of desktop Java environments. This means that there is a lot of cool stuff for you to pick up along your journey in order to create the slickest, most useful apps Android you can imagine.
The source code for the code samples in this book is all available from the Apress site, so you can stay as hands-on and practical as you like while I introduce you to the core of Android, and invite you to experiment with the various classes and APIs we’ll be looking at. By the time you’ve finished this book, you’ll be creating your own Android applications and asking yourself what your next great application will be…!
Enjoy! Mark Murphy

Beginning Android — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Beginning Android», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Given a Uri, you can perform basic CRUD (create, read, update, delete) operations using a content provider. Uriinstances can represent either collections or individual pieces of content. Given a collection Uri, you can create new pieces of content via insert operations. Given an instance Uri, you can read data represented by the Uri, update that data, or delete the instance outright.

Android lets you use existing content providers or create your own. This chapter covers using content providers; Chapter 28 will explain how you can serve up your own data using the content provider framework.

Pieces of Me

The simplified model of the construction of a content Uriis the scheme, the namespace of data, and, optionally, the instance identifier, all separated by slashes in URL-style notation. The scheme of a content Uri is always content://.

So, a content Uriof content://constants/5represents the constants instance with an identifier of 5.

The combination of the scheme and the namespace is known as the “base Uri” of a content provider, or a set of data supported by a content provider. In the previous example, content://constantsis the base Urifor a content provider that serves up information about “constants” (in this case, physical constants).

The base Urican be more complicated. For example, the base Uri for contacts is content://contacts/people, as the contacts content provider may serve up other data using other base Urivalues.

The base Urirepresents a collection of instances. The base Uricombined with an instance identifier (e.g., 5) represents a single instance.

Most of the Android APIs expect these to be Uriobjects, though in common discussion, it is simpler to think of them as strings. The Uri.parse()static method creates a Uriout of the string representation.

Getting a Handle

Where do these Uriinstances come from?

The most popular starting point, if you know the type of data you want to work with, is to get the base Urifrom the content provider itself in code. For example, CONTENT_URIis the base Urifor contacts represented as people — this maps to content://contacts/people. If you just need the collection, this Uriworks as is; if you need an instance and know its identifier, you can call addId()on the Urito inject it, so you have a Urifor the instance.

You might also get Uriinstances handed to you from other sources, such as getting Urihandles for contacts via sub-activities responding to ACTION_PICKintents. In this case, the Uriis truly an opaque handle… unless you decide to pick it apart using the various getters on the Uriclass.

You can also hard-wire literal Stringobjects and convert them into Uriinstances via Uri.parse(). For example, in Chapter 25, the sample code used an EditTextwith content://contacts/peoplepre-filled in. This isn’t an ideal solution, as the base Urivalues could conceivably change over time.

Making Queries

Given a base Uri, you can run a query to return data out of the content provider related to that Uri. This has much of the feel of SQL: you specify the “columns” to return, the constraints to determine which “rows” to return, a sort order, etc. The difference is that this request is being made of a content provider, not directly of some database (e.g., SQLite).

The nexus of this is the managedQuery()method available to your activity. This method takes five parameters:

1. The base Uriof the content provider to query, or the instance Uriof a specific object to query

2. An array of properties of instances from that content provider that you want returned by the query

3. A constraint statement, functioning like a SQL WHEREclause

4. An optional set of parameters to bind into the constraint clause, replacing any ?s that appear there

5. An optional sort statement, functioning like a SQL ORDER BYclause

This method returns a Cursorobject, which you can use to retrieve the data returned by the query.

“Properties” is to content providers as columns are to databases. In other words, each instance (row) returned by a query consists of a set of properties (columns), each representing some piece of data.

This will hopefully make more sense given an example.

Our content provider examples come from the ContentProvider/Constantssample application, specifically the ConstantsBrowserclass:

constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,

PROJECTION, null, null, null);

In the call to managedQuery(), we provide:

• The Uripassed into the activity by the caller ( CONTENT_URI), in this case representing the collection of physical constants managed by the content provider

• A list of properties to retrieve (see the following code)

• Three null values, indicating that we do not need a constraint clause (the Urirepresents the instance we need), nor parameters for the constraint, nor a sort order (we should only get one entry back)

private static finalString[] PROJECTION = newString[] {

Provider.Constants._ID, Provider.Constants.TITLE,

Provider.Constants.VALUE};

The biggest “magic” here is the list of properties. The lineup of what properties are possible for a given content provider should be provided by the documentation (or source code) for the content provider itself. In this case, we define logical values on the Providercontent provider implementation class that represent the various properties (namely, the unique identifier, the display name or title, and the value of the constant).

Adapting to the Circumstances

Now that we have a Cursorvia managedQuery(), we have access to the query results and can do whatever we want with them. You might, for example, manually extract data from the Cursorto populate widgets or other objects.

However, if the goal of the query was to return a list from which the user should choose an item, you probably should consider using SimpleCursorAdapter. This class bridges between the Cursorand a selection widget, such as a ListViewor Spinner. Pour the Cursorinto a SimpleCursorAdapter, hand the adapter off to the widget, and you’re set — your widget will show the available options.

For example, here is the onCreate()method from ConstantsBrowser, which gives the user a list of physical constants:

@Override

publicvoid onCreate(Bundle savedInstanceState) {

super. onCreate(savedInstanceState);

constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,

PROJECTION, null, null, null);

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Beginning Android»

Представляем Вашему вниманию похожие книги на «Beginning Android» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Beginning Android»

Обсуждение, отзывы о книге «Beginning Android» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x