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

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

Интервал:

Закладка:

Сделать

returncount;

}

In this case, updates can either be to a specific instance or applied across the entire collection, so we check the Uri ( isCollectionUri()) and, if it is an update for the collection, just perform the update. If we are updating a single instance, we need to add a constraint to the WHEREclause to only update for the requested row.

delete()

Like update(), delete()receives aUri representing the instance or collection to work with and a WHEREclause and parameters. If the activity is deleting a single instance, the Urishould represent that instance and the WHEREclause may be null. But the activity might be requesting to delete an open-ended set of instances, using the WHERE clause to constrain which ones to delete.

As with update(), though, this is simple if you are using SQLite for database storage (sense a theme?). You can let it handle the idiosyncrasies of parsing and applying the WHEREclause — all you have to do is call delete()on the database.

For example, here is delete()from Provider:

@Override

publicint delete(Uri url, String where, String[] whereArgs) {

int count;

long rowId = 0;

if( isCollectionUri(url)) {

count = db. delete( getTableName(), where, whereArgs);

} else{

String segment = url. getPathSegments(). get(1);

rowId = Long. parseLong(segment);

count = db. delete( getTableName(), getIdColumnName() + "="

+ segment + (!TextUtils. isEmpty(where) ? " AND (" + where + ')' : ""),

whereArgs);

}

getContext(). getContentResolver(). notifyChange(url, null);

returncount;

}

This is almost a clone of the update()implementation described earlier in this chapter — either delete a subset of the entire collection or delete a single instance (if it also satisfies the supplied WHEREclause).

getType()

The last method you need to implement is getType(). This takes a Uriand returns the MIME type associated with that Uri. The Uri could be a collection or an instance Uri; you need to determine which was provided and return the corresponding MIME type.

For example, here is getType()from Provider:

@Override

publicString getType(Uri url) {

if( isCollectionUri(url)) {

return( getCollectionType());

}

return( getSingleType());

}

As you can see, most of the logic delegates to private getCollectionType()and getSingleType()methods:

privateString getCollectionType() {

return("vnd.android.cursor.dir/vnd.commonsware.constant");

}

privateString getSingleType() {

return("vnd.android.cursor.item/vnd.commonsware.constant");

}

Step #2: Supply a Uri

You also need to add a public static member… somewhere, containing the Urifor each collection your content provider supports. Typically this is a public static finalUri put on the content-provider class itself:

public static finalUri CONTENT_URI =

Uri. parse("content://com.commonsware.android.tourit.Provider/tours");

You may wish to use the same namespace for the content Urithat you use for your Java classes, to reduce the chance of collision with others.

Step #3: Declare the Properties

Remember those properties you referenced when you were using a content provider in the previous chapter? Well, you need to have those too for your own content provider.

Specifically, you want a public static class implementing BaseColumnsthat contains your property names, such as this example from Provider:

public static final classConstants implementsBaseColumns {

public static finalUri CONTENT_URI =

Uri. parse("content://com.commonsware.android.constants.Provider/constants");

public static finalString DEFAULT_SORT_ORDER = "title";

public static finalString TITLE = "title";

public static finalString VALUE = "value";

}

If you are using SQLite as a data store, the values for the property name constants should be the corresponding column name in the table, so you can just pass the projection (array of properties) to SQLite on a query(), or pass the ContentValueson an insert()or update().

Note that nothing in here stipulates the types of the properties. They could be strings, integers, or whatever. The biggest limitation is what a Cursorcan provide access to via its property getters. The fact that there is nothing in code that enforces type safety means you should document the property types well so people attempting to use your content provider know what they can expect.

Step #4: Update the Manifest

The glue tying the content-provider implementation to the rest of your application resides in your AndroidManifest.xmlfile. Simply add a provider element as a child of the element:

android:name=".Provider"

android:authorities="com.commonsware.android.tourit.Provider" />

The android:nameproperty is the name of the content-provider class, with a leading dot to indicate it is in the stock namespace for this application’s classes (just like you use with activities).

The android:authoritiesproperty should be a semicolon-delimited list of the authority values supported by the content provider. Recall, from earlier in this chapter, that each content Uriis made up of a scheme, an authority, a data type path, and an instance identifier. Each authority from each CONTENT_URIvalue should be included in the android:authoritieslist.

Now when Android encounters a content Uri, it can sift through the providers registered through manifests to find a matching authority. That tells Android which application and class implements the content provider, and from there Android can bridge between the calling activity and the content provider being called.

Notify-on-Change Support

An optional feature your content provider offers its clients is notify-on-change support. This means that your content provider will let clients know if the data for a given content Urichanges.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x