Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 57

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 57 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 572018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 57)

In this example, we create twoRecordStores, one for storing the image data (the IMAGE RecordStore) and a lightweight INDEX RecordStore. Why do we use aseparate INDEX record store? When we create a new record and save it ina RecordStore with the addRecord() method, an integer record IDis returned that uniquely identifies that record within the RecordStore.This value can be cached by the MIDlet and used to retrieve the recordwhile the MIDlet is running. However, as soon as the MIDlet is shutdown the value of the record ID will be lost, unless, as we do here,we also save the record ID in another RecordStore. By creating alightweight INDEX record store, which contains small records each consisting only of the name of the saved image and the record ID of the savedimage, we can quickly retrieve the names (and record IDs) of the savedimages without having to enumerate through the large RecordStore ofimage data.As we saw earlier, when the GameMIDlet starts, it calls the displayChoiceForm, the first action of which is to call the loadImageNames()method:THE PICTURE PUZZLE315public String[] loadImageNames() throws ApplicationException {String[] images = rms.retrieveStoredImageNames();return images;}This calls the retrieveStoredImageNames() method of theRMSHandler, which enumerates through the INDEX record store andcaches the image names, their record IDs and the ID of the respectiveINDEX entry in a hashtable for use during the lifetime of the application.To retrieve an image from the record store we invoke the retrieveImageFromStore() method, which takes the name of the requiredimage as a parameter and uses it as the key to the hashtable, retrieving thecached record indices.

It uses the record ID of the image data to retrievethe data from the IMAGE RecordStore.To delete a record we use the deleteImageFromStore() method,which takes the name of the image to be deleted as a parameter. It retrievesthe record indices from the hashtable and uses them to delete the imagedata from the IMAGE RecordStore and the key entry from the INDEXRecordStore.

Finally, it removes the relevant entry from the hashtable.The addImageToStore() method takes the image name and imagedata as parameters and adds the image data to the IMAGE RecordStore.The returned record ID and the image name are then stored in the INDEXRecordStore. The returned index entry record ID and the image recordID are cached in the hashtable as an integer array using the image nameas the hash key.5.4.8 SummaryThe Picture Puzzle MIDlet is a fully working example, however, notethat it was written primarily for pedagogic purposes, with clarity of coderegarded as a higher priority than efficiency or richness of features.Adding extra bells and whistles, perhaps including a peer-to-peer modein which a newly captured and scrambled photo is transmitted overBluetooth (using JSR 82) for a friend to unscramble, is left as an exercisefor the reader.The full source code for the Picture Puzzle can be downloaded fromSymbian’s website at www.symbian.com/books.Section 2Writing Quality Code forSmartphones6Making Java Code Portable6.1 IntroductionIn this chapter and the next, we shall examine how to make applicationsas portable as possible and how to write efficient code.

Although Java(particularly wireless Java) is not ”write once, run anywhere”, portingJava MIDlets to different wireless devices is generally straightforward.The problems associated with portability are due to the wide variation inmobile phones: variations in heap memory, persistent storage, screen sizeand resolution, and user input methods all contribute to an application’sinability to execute consistently across a range of devices. Some deviceshave optional APIs and there are network considerations specific to eachoperator, such as permissible JAR file sizes.This chapter will investigate how to develop MIDlets that are portableacross as wide a range of mobile phones as possible.

We will look at howwe can use design patterns and coding guidelines to assist in portability,enabling developers to maximize revenue-earning opportunities fromtheir endeavors.The value of creating portable code is magnified by the number ofJava devices in the marketplace. Many of them are similar; for example,the Series 60 Platform provides a way of creating applications for a broadrange of devices. Even among Series 60 devices, however, differencesexist in the development environment.

Some phones include the WirelessMessaging API (JSR 120) and Java APIs for Bluetooth (JSR 82). Newer Series60 devices, such as the Nokia 6600, have MIDP 2.0, while earlier ones,such as the Nokia 3650, have MIDP 1.0. Symbian OS devices havediverse user interfaces. Screen sizes vary and, more significantly, so douser input methods: the Sony Ericsson P900 uses a large touch screenwith a jog dial, whereas Series 60 phones have a smaller screen and usea keypad and a four-way joystick.Programming Java 2 Micro Edition on Symbian OS: A developer’s guide to MIDP 2.0. Martin de Jode 2004 Symbian Ltd ISBN: 0-470-09223-8320MAKING JAVA CODE PORTABLEThese variations do not, however, mean that an application has tobe totally rewritten to run on all these devices.

Whether our applicationuses high-level components, such as Forms, TextFields and Lists,or does its own drawing and event handling using a Canvas (or indeeduses a combination of these techniques), we can still do much to makeour MIDlet portable.At the very least, the core application should remain the same acrossdevices and any differences should be expressed principally throughvariations in the user interface. For example, graphics may have to beadapted to cope with a smaller screen, or alternative menus may haveto be created for different methods of capturing user input.

Making thecore application invariant requires separating it from the UI, based on asuitable model.As well as creating a portable architecture, the developer may haveto cater for individual device capabilities. This requires knowing whichAPIs are supported by the device and adapting the MIDlet appropriately,either at runtime or by creating different variations.While examining programming models we shall also look at thedifferences among Symbian OS devices and see how this will affectapplication implementation.6.2 Design PatternsThere are many types of structural design that can be adopted whenprogramming with an object-orientated language such as Java, and thesecan be used to facilitate portable code. While we shall not be examiningthe design theory in great detail, it is worth considering the broaderconcepts for MIDlet development in general.

These designs are traditionally associated with desktop or server-based application development;however, they will become more important for wireless applications asthese become more sophisticated and memory and processing powerbecome less of a constraint. Two useful design patterns are listed in thefollowing sections.6.2.1 Model–View–Controller Design PatternThis is an architecture commonly used for GUI applications. It breaksthe application into three specialized entities: a Model, a View and aController.

Each entity is reliant upon the others, but is self-contained.The Model–View–Controller (MVC) pattern traces its roots to the UIparadigm used in the Smalltalk programming language. The three entitiesare as follows:• the Model: also known (perhaps more appropriately) as the EngineThe model holds the application’s data. It processes instructions fromDESIGN PATTERNS321the controller to change the data. It has a relationship with the views,notifying them when its data has changed, thus ensuring the lateststate of the data is reflected in the views. It responds to queries aboutits state from the views.

In short, it provides the core business logicfor the application.• the ViewThe view is responsible for presenting the data to the user. In responseto a notification from the model, the view gets the current state ofthe data and renders it to the screen. It also provides the interface foraccepting input from the user.• the ControllerThe controller is responsible for managing the flow of the application.It responds to captured user input from the views, processing theinput and issuing instructions to the model to change its data stateaccordingly.A UML class diagram of a basic MVC implementation is shown inFigure 6.1 and the interaction between the objects is shown in a UMLsequence diagram (Figure 6.2).One of the ideas behind the MVC pattern is to promote loose couplingbetween the components of the application.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6289
Авторов
на СтудИзбе
315
Средний доход
с одного платного файла
Обучение Подробнее