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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

ListAdapter adapter = new SimpleCursorAdapter( this,

R.layout.row, constantsCursor,

newString[] {Provider.Constants.TITLE, Provider.Constants.VALUE},

newint[] {R.id.title, R.id.value});

setListAdapter(adapter);

registerForContextMenu( getListView());

}

After executing the managedQuery()and getting the Cursor, ConstantsBrowsercreates a SimpleCursorAdapterwith the following parameters:

• The activity (or other Context) creating the adapter; in this case, the ConstantsBrowseritself

• The identifier for a layout to be used for rendering the list entries ( R.layout.row)

• The cursor ( constantsCursor)

• The properties to pull out of the cursor and use for configuring the list entry View instances ( TITLEand VALUE)

• The corresponding identifiers of TextViewwidgets in the list entry layout that those properties should go into ( R.id.titleand R.id.value)

After that, we put the adapter into the ListView, and we get the results shown in Figure 27-1.

Figure 271 ConstantsBrowser showing a list of physical constants If you - фото 84

Figure 27-1. ConstantsBrowser, showing a list of physical constants

If you need more control over the views than you can reasonably achieve with the stock view construction logic, subclass SimpleCursorAdapterand override getView()to create your own widgets to go into the list, as demonstrated in Chapter 9.

Doing It By Hand

Of course, you can always do it the “hard way” — pulling data out of the Cursorby hand. The Cursorinterface is similar in concept to other database access APIs offering cursors as objects, though, as always, the devil is in the details.

Position

Cursor instances have a built-in notion of position, akin to the Java Iterator interface. To get to the various rows, you can use:

moveToFirst()to move to the first row in the result set or moveToLast()to move to the last row in the result set

moveToNext()to move to the next row and determine if there is yet another row to process ( moveToNext()returns true if it points to another row after moving, false otherwise)

moveToPrevious()to move to the previous row, as the opposite to moveToNext()

moveToPosition()to move to a specific index, or move()to move to a relative position plus or minus from your current position

getPosition()to return your current index

• a whole host of condition methods, including isFirst(), isLast(), isBeforeFirst(), and isAfterLast()

Getting Properties

Once you have the Cursor positioned at a row of interest, you have a variety of methods to retrieve properties from that row, with different methods supporting different types ( getString(), getInt(), getFloat(), etc.). Each method takes the zero-based index of the property you want to retrieve.

If you want to see if a given property has a value, you can use isNull()to test it for null-ness.

Give and Take

Of course, content providers would be astonishingly weak if you couldn’t add or remove data from them, only update what is there. Fortunately, content providers offer these abilities as well.

To insert data into a content provider, you have two options available on the ContentProviderinterface (available through getContentProvider()to your activity):

• Use insert()with a collection Uriand a ContentValuesstructure describing the initial set of data to put in the row

• Use bulkInsert()with a collection Uriand an array of ContentValuesstructures to populate several rows at once

The insert()method returns a Urifor you to use for future operations on that new object. The bulkInsert()method returns the number of created rows; you would need to do a query to get back at the data you just inserted.

For example, here is a snippet of code from ConstantsBrowserto insert a new constant into the content provider, given a DialogWrapperthat can provide access to the title and value of the constant:

privatevoid processAdd(DialogWrapper wrapper) {

ContentValues values = new ContentValues(2);

values. put(Provider.Constants.TITLE, wrapper. getTitle());

values. put(Provider.Constants.VALUE, wrapper. getValue());

getContentResolver(). insert(Provider.Constants.CONTENT_URI,

values);

constantsCursor. requery();

}

Since we already have an outstanding Cursorfor the content provider’s contents, we call requery()on that to update the Cursor’s contents. This, in turn, will update any SimpleCursorAdapteryou may have wrapping the Cursor— and that will update any selection widgets (e.g., ListView) you have using the adapter.

To delete one or more rows from the content provider, use the delete()method on ContentResolver. This works akin to a SQL DELETEstatement and takes three parameters:

1. A Urirepresenting the collection (or instance) you wish to update

2. A constraint statement, functioning like a SQL WHEREclause, to determine which rows should be updated

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

Beware of the BLOB!

Binary large objects — BLOBs — are supported in many databases, including SQLite. However, the Android model is more aimed at supporting such hunks of data via their own separate content Urivalues. A content provider, therefore, does not provide direct access to binary data, like photos, via a Cursor. Rather, a property in the content provider will give you the content Urifor that particular BLOB. You can use getInputStream()and getOutputStream()on your ContentProviderto read and write the binary data.

Quite possibly, the rationale is to minimize unnecessary data copying. For example, the primary use of a photo in Android is to display it to the user. The ImageViewwidget can do just that, via a content Urito a JPEG. By storing the photo in a manner that has its own Uri, you do not need to copy data out of the content provider into some temporary holding area just to be able to display it — just use the Uri. The expectation, presumably, is that few Android applications will do much more than upload binary data and use widgets or built-in activities to display that data.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x