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

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

Интервал:

Закладка:

Сделать

This chapter will cover the basics of SQLite use in the context of working on Android. It by no means is a thorough coverage of SQLite as a whole. If you want to learn more about SQLite and how to use it in environments other than Android, a fine book is The Definitive Guide to SQLite [21] http://www.amazon.com/Definitive-Guide-SQLite/dp/1590596730 by Mike Owens (Apress, 2006).

Activities will typically access a database via a content provider or service. Therefore, this chapter does not have a full example. You will find a full example of a content provider that accesses a database in Chapter 28.

A Quick SQLite Primer

SQLite, as the name suggests, uses a dialect of SQL for queries ( SELECT), data manipulation (INSERT, et al), and data definition ( CREATE TABLE, et al). SQLite has a few places where it deviates from the SQL-92 standard, no different than most SQL databases. The good news is that SQLite is so space-efficient that the Android runtime can include all of SQLite, not some arbitrary subset to trim it down to size.

The biggest difference from other SQL databases you will encounter is probably the data typing. While you can specify the data types for columns in a CREATE TABLEstatement, and while SQLite will use those as a hint, that is as far as it goes. You can put whatever data you want in whatever column you want. Put a string in an INTEGER column? Sure! No problem! Vice versa? Works too! SQLite refers to this as “manifest typing,” as described in the documentation: [22] http://www.sqlite.org/different.html

In manifest typing, the datatype is a property of the value itself, not of the column in which the value is stored. SQLite thus allows the user to store any value of any datatype into any column regardless of the declared type of that column.

In addition, there is a handful of standard SQL features not supported in SQLite, notably FOREIGN KEYconstraints, nested transactions, RIGHT OUTER JOINand FULL OUTER JOIN, and some flavors of ALTER TABLE.

Beyond that, though, you get a full SQL system, complete with triggers, transactions, and the like. Stock SQL statements, like SELECT, work pretty much as you might expect.

If you are used to working with a major database, like Oracle, you may look upon SQLite as being a “toy” database. Please bear in mind that Oracle and SQLite are meant to solve different problems, and that you will not likely be seeing a full copy of Oracle on a phone any time soon.

Start at the Beginning

No databases are automatically supplied to you by Android. If you want to use SQLite, you have to create your own database, then populate it with your own tables, indexes, and data.

To create and open a database, your best option is to craft a subclass of SQLiteOpenHelper. This class wraps up the logic to create and upgrade a database, per your specifications, as needed by your application. Your subclass of SQLiteOpenHelperwill need three methods:

• The constructor, chaining upward to the SQLiteOpenHelperconstructor. This takes the Context(e.g., an Activity), the name of the database, an optional cursor factory (typically, just pass null), and an integer representing the version of the database schema you are using.

onCreate(), which passes you a SQLiteDatabaseobject that you need to populate with tables and initial data, as appropriate.

onUpgrade(), which passes you a SQLiteDatabaseobject and the old and new version numbers, so you can figure out how best to convert the database from the old schema to the new one. The simplest, albeit least friendly, approach is to simply drop the old tables and create new ones. This is covered in greater detail in Chapter 28.

The rest of this chapter will discuss how you actually create tables, insert data, drop tables, etc., and will show sample code from a SQLiteOpenHelpersubclass.

To use your SQLiteOpenHelpersubclass, create an instance and ask it to getReadableDatabase()or getWriteableDatabase(), depending upon whether or not you will be changing its contents:

db = (new DatabaseHelper(getContext())).getWritableDatabase();

return (db == null) ? false : true;

This will return a SQLiteDatabaseinstance, which you can then use to query the database or modify its data.

When you are done with the database (e.g., your activity is being closed), simply call close()on the SQLiteDatabaseto release your connection.

Setting the Table

For creating your tables and indexes, you will need to call execSQL()on your SQLiteDatabase, providing the DDL statement you wish to apply against the database. Barring a database error, this method returns nothing.

So, for example, you can use the following code:

db. execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, value REAL);");

This will create a table, named constants, with a primary key column named _idthat is an auto-incremented integer (i.e., SQLite will assign the value for you when you insert rows), plus two data columns: title(text) and value(a float, or “real” in SQLite terms). SQLite will automatically create an index for you on your primary-key column — you could add other indices here via some CREATE INDEXstatements, if you so chose.

Most likely, you will create tables and indexes when you first create the database, or possibly when the database needs upgrading to accommodate a new release of your application. If you do not change your table schemas, you might never drop your tables or indexes, but if you do, just use execSQL()to invoke DROP INDEXand DROP TABLEstatements as needed.

Makin’ Data

Given that you have a database and one or more tables, you probably want to put some data in them and such. You have two major approaches for doing this.

You can always use execSQL(), just like you did for creating the tables. The execSQL()method works for any SQL that does not return results, so it can handle INSERT, UPDATE, DELETE, etc. just fine. So, for example you could use this code:

db. execSQL("INSERT INTO widgets (name, inventory)" +

VALUES ('Sprocket', 5));

Your alternative is to use the insert(), update(), and delete()methods on the SQLiteDatabaseobject. These are “builder” sorts of methods, in that they break down the SQL statements into discrete chunks, then take those chunks as parameters.

These methods make use of ContentValuesobjects, which implement a Map-esque interface, albeit one that has additional methods for working with SQLite types. For example, in addition to get()to retrieve a value by its key, you have getAsInteger(), getAsString(), and so forth.

The insert()method takes the name of the table, the name of one column as the null column hack , and a ContentValueswith the initial values you want put into this row. The null column hack is for the case where the ContentValuesinstance is empty — the column named as the null column hack will be explicitly assigned the value NULLin the SQL INSERTstatement generated by insert().

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

Интервал:

Закладка:

Сделать

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

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


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

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

x