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

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

Интервал:

Закладка:

Сделать

ArrayList items = newArrayList();

@Override

publicvoid onCreate(Bundle icicle) {

super. onCreate(icicle);

setContentView(R.layout.main);

selection = (TextView) findViewById(R.id.selection);

try{

InputStream in = getResources(). openRawResource(R.raw.words);

DocumentBuilder builder = DocumentBuilderFactory

. newInstance(). newDocumentBuilder();

Document doc = builder. parse(in, null);

NodeList words = doc. getElementsByTagName("word");

for(int i=0; iwords. getLength(); i++) {

items. add(((Element)words. item(i)). getAttribute("value"));

}

in. close();

} catch(Throwable t) {

Toast

. makeText( this, "Exception: "+t. toString(), 2000). show();

}

setListAdapter( newArrayAdapter( this,

android.R.layout.simple_list_item_1, items));

}

publicvoid onListItemClick(ListView parent, View v, int position,

long id) {

selection. setText(items. get(position). toString());

}

}

The differences between the Chapter 8 example and this one mostly lie within onCreate(). We get an InputStreamfor the XML file ( getResources().openRawResource(R.raw.words)), then use the built-in XML parsing logic to parse the file into a DOM Document, pick out the word elements, then pour the value attributes into an ArrayListfor use by the ArrayAdapter.

The resulting activity looks the same as before (Figure 18-1), since the list of words is the same, just relocated.

Figure 181 The StaticFileDemo sample application Of course there are even - фото 64

Figure 18-1. The StaticFileDemo sample application

Of course, there are even easier ways to have XML files available to you as pre-packaged files, such as by using an XML resource. That is covered in the next chapter. However, while this example uses XML, the file could just as easily have been a simple one-word-per-line list, or in some other format not handled natively by the Android resource system.

Readin’ ’n’ Writin’

Reading and writing your own, application-specific data files is nearly identical to what you might do in a desktop Java application. The key is to use openFileInput()and openFileOutput()on your Activityor other Contextto get an InputStreamand OutputStream, respectively. From that point forward, the process is not much different from using regular Java I/O logic:

• Wrap those streams as needed, such as using an InputStreamReaderor OutputStreamWriterfor text-based I/O.

• Read or write the data.

• Use close()to release the stream when done.

If two applications both try reading a notes.txtfile via openFileInput(), they will each access their own edition of the file. If you need to have one file accessible from many places, you probably want to create a content provider, as will be described in Chapter 28.

Note that openFileInput()and openFileOutput()do not accept file paths (e.g., path/to/file.txt), just simple filenames.

The following code shows the layout for the world’s most trivial text editor, pulled from the Files/ReadWritesample application available on the Apress Web site:

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical">

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Close" />

android:id="@+id/editor"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:singleLine="false"

/>

All we have here is a large text-editing widget with a Close button above it. The Java is only slightly more complicated:

packagecom.commonsware.android.files;

importandroid.app.Activity;

importandroid.os.Bundle;

importandroid.view.View;

importandroid.widget.Button;

importandroid.widget.EditText;

importandroid.widget.Toast;

importjava.io.BufferedReader;

importjava.io.File;

importjava.io.InputStream;

importjava.io.InputStreamReader;

importjava.io.OutputStream;

importjava.io.OutputStreamWriter;

public classReadWriteFileDemo extendsActivity {

private final staticString NOTES = "notes.txt";

privateEditText editor;

@Override

publicvoid onCreate(Bundle icicle) {

super. onCreate(icicle);

setContentView(R.layout.main);

editor = (EditText) findViewById(R.id.editor);

Button btn = (Button) findViewById(R.id.close);

btn. setOnClickListener( newButton. OnClickListener() {

publicvoid onClick(View v) {

finish();

}

});

}

publicvoid onResume() {

super. onResume();

try{

InputStream in = openFileInput(NOTES);

if(in != null) {

InputStreamReader tmp = new InputStreamReader(in);

BufferedReader reader = new BufferedReader(tmp);

String str;

StringBuffer buf = new StringBuffer();

while((str = reader. readLine()) != null) {

buf. append(str+"\n");

}

in. close();

editor. setText(buf. toString());

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

Интервал:

Закладка:

Сделать

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

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


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

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

x