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

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

Интервал:

Закладка:

Сделать

We hold the URL to the National Weather Service XML in a string resource, and pour in the latitude and longitude at runtime. Given our HttpClientobject created in onCreate(), we populate an HttpGetwith that customized URL, then execute that method. Given the resulting XML from the REST service, we build the forecast HTML page (see “Parsing Responses”) and pour that into the WebKitwidget. If the HttpClientblows up with an exception, we provide that error as a Toast.

Parsing Responses

The response you get will be formatted using some system — HTML, XML, JSON, whatever. It is up to you, of course, to pick out what information you need and do something useful with it. In the case of the WeatherDemo, we need to extract the forecast time, temperature, and icon (indicating sky conditions and precipitation) and generate an HTML page from it.

Android includes:

• Three XML parsers: the traditional W3C DOM ( org.w3c.dom), a SAX parser ( org.xml.sax), and the XML pull parser discussed in Chapter 19

• A JSON parser ( org.json)

You are also welcome to use third-party Java code, where possible, to handle other formats, such as a dedicated RSS/Atom parser for a feed reader. The use of third-party Java code is discussed in Chapter 21.

For WeatherDemo, we use the W3C DOM parser in our buildForecasts()method:

void buildForecasts(String raw) throwsException {

DocumentBuilder builder = DocumentBuilderFactory

. newInstance(). newDocumentBuilder();

Document doc = builder. parse( new InputSource( new StringReader(raw)));

NodeList times = doc. getElementsByTagName("start-valid-time");

for(int i=0; igetLength(); i++) {

Element time = (Element)times. item(i);

Forecast forecast = new Forecast();

forecasts. add(forecast);

forecast. setTime(time. getFirstChild(). getNodeValue());

}

NodeList temps = doc. getElementsByTagName("value");

for(int i=0; igetLength(); i++) {

Element temp = (Element)temps. item(i);

Forecast forecast = forecasts. get(i);

forecast. setTemp( new Integer(temp. getFirstChild(). getNodeValue()));

}

NodeList icons = doc. getElementsByTagName("icon-link");

for(int i=0; igetLength(); i++) {

Element icon = (Element)icons. item(i);

Forecast forecast = forecasts. get(i);

forecast. setIcon(icon. getFirstChild(). getNodeValue());

}

}

The National Weather Service XML format is… curiously structured, relying heavily on sequential position in lists versus the more object-oriented style you find in formats like RSS or Atom. That being said, we can take a few liberties and simplify the parsing somewhat, taking advantage of the fact that the elements we want ( start-valid-timefor the forecast time, value for the temperature, and icon-linkfor the icon URL) are all unique within the document.

The HTML comes in as an InputStreamand is fed into the DOM parser. From there, we scan for the start-valid-timeelements and populate a set of Forecastmodels using those start times. Then, we find the temperature value elements and icon-linkURLs and fill those into the Forecastobjects.

In turn, the generatePage()method creates a rudimentary HTML table with the forecasts:

String generatePage() {

StringBuffer bufResult = new StringBuffer("

");

bufResult. append("

" +

"

");

for(Forecast forecast : forecasts) {

bufResult. append("

bufResult. append(forecast. getTime());

bufResult. append("

bufResult. append(forecast. getTemp());

bufResult. append("

bufResult. append(forecast. getIcon());

bufResult. append("\">

");

}

bufResult. append("

Time Temperature Forecast
"); ");
");

return(bufResult. toString());

}

The result can be seen in Figure 22-1.

Figure 221 The WeatherDemo sample application Stuff to Consider If you - фото 72

Figure 22-1. The WeatherDemo sample application

Stuff to Consider

If you need to use SSL, bear in mind that the default HttpClientsetup does not include SSL support. Mostly, this is because you need to decide how to handle SSL certificate presentation — do you blindly accept all certificates, even self-signed or expired ones? Or do you want to ask the user if they really want to use some strange certificates?

Similarly, HttpClient, by default, is designed for single-threaded use. If you will be using HttpClientfrom a service or some other place where multiple threads might be an issue, you can readily set up HttpClientto support multiple threads.

For these sorts of topics, you are best served by checking out the HttpComponentsWeb site for documentation and support.

PART 4

Intents

CHAPTER 23

Creating Intent Filters

Up to now, the focus of this book has been on activities opened directly by the user from the device’s launcher. This, of course, is the most obvious case for getting your activity up and visible to the user. In many cases it is the primary way the user will start using your application.

However, the Android system is based upon lots of loosely-coupled components. What you might accomplish in a desktop GUI via dialog boxes, child windows, and the like are mostly supposed to be independent activities. While one activity will be “special”, in that it shows up in the launcher, the other activities all need to be reached… somehow.

The “how” is via intents.

An intent is basically a message that you pass to Android saying, “Yo! I want to do… er… something! Yeah!” How specific the “something” is depends on the situation — sometimes you know exactly what you want to do (e.g., open up one of your other activities), and sometimes you don’t.

In the abstract, Android is all about intents and receivers of those intents. So, now that we are well-versed in creating activities, let’s dive into intents, so we can create more complex applications while simultaneously being “good Android citizens.”

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

Интервал:

Закладка:

Сделать

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

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


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

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