Главная » Просмотр файлов » John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG

John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (779881), страница 20

Файл №779881 John.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG (Symbian Books) 20 страницаJohn.Wiley.and.Sons.Rapid.Mobile.Enterprise.Development.for.Symbian.OS.An.Introduction.to.OPL.Application.Design.and.Programming.May.2005.eBook-LinG2018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

(Note: You should know what we havehere is a ‘flat file’ database, i.e. the structure is consistent. There are morecomplex databases called relational databases, but these are beyond thescope of this book.)6.2 Our First OPL Database6.2.1 The INI FileWe’ve already created our first database, and many of the commandswe’re going to use have been seen already. Inside Event Core are all therelevant procedures to create, open, and save a simple database.

So whatare the differences between the INI database and the one we’re going tocreate and use in this program? The main difference is that the Notepaddatabase will have more than one record, so we’ll need to be awarewhere we are in the database at any point in time; more on that in amoment. For now, let’s have a look at the procedures and methods we’regoing to use on the Notepad database.6.2.2 ConstructionThe headings in any program database need to be decided right at thestart of the process – once we have CREATEd the database for the firsttime, we will not be able to change the headings. For our Notepad,this isn’t too complicated, but you need to be aware of this issue whencreating your own databases.A Notepad database will have two fields. Heading (which will bedisplayed on the main screen for the user to choose) and Text, which iswhat will hold the actual information.6.2.3 Creating or Opening our Notepad DatabaseIn a similar way to the LoadINI: procedure, here’s how we open ourNotepad database:PROC OpenFile:(Filename$)IF NOT EXIST(FileName$)CreateFile:(FileName$)RETURNENDIFCloseFile:OPEN FileName$,B,Heading$,Text$FileOpen%=1rem Set Other StuffTrueCursor%=1 : TopCursor%=1ENDPOUR FIRST OPL DATABASE103PROC CloseFile:IF FileOpen%=0 : RETURN : ENDIFTRAP USE BTRAP CLOSEFileOpen%=0ENDPThis routine will commonly be called from inside the InitApp: procedure.

In Notepad, we will only ever use one database, but it is possibleto extend the program at a later date to be able to use more than one file,and switch between them as required.Firstly in the code, we check to see if the file actually exists. If itdoes not (perhaps because this is the first time the program has beenrun), we jump to the CreateFile: procedure (which we’ll come to ina moment).Let’s assume it does exist. Unlike the INI file, we have to keep ourNotepad database open throughout the time the program is running, as itwill need to be constantly read and edited. Therefore we have a variable(FileOpen%) to track this, where 0=closed and 1=open. We open thedatabase, and assign it the reference letter "B" (remember that when weuse the INI file, we use the letter "A").

After that we note what nameswe are going to use to look up the two fields, using as descriptive (to us)names as possible. We also set our two cursors to 1. We’ll discuss whywe have two cursors once we have all our database procedures in place.PROC CloseFile: is simply a procedure to close the open databasefile referenced as B. Not strictly needed when we are hard-coding asingle database to the program, but it will give you ideas for creatingan app that can have more than one file.

We have a check to ensurethat the database is really closed (if it is, FileOpen% will equal zero,and we can safely return from this procedure). We then ensure we areusing the correct database reference (TRAP USE B) and then CLOSE thefile, TRAPping any error if there is one. Finally we set the FileOpen%variable to zero:PROC CreateFile:(FileName$)CloseFile:TRAP DELETE FileName$rem *** Create File HereCREATE FileName$,B,Heading$,Text$USE Brem Add Two 'default' records.INSERTB.Heading$="Welcome to Notepad"B.Text$="This is a simple database notepad application"PUTINSERTB.Heading$="Feel free to delete these"104DATABASES AND A NOTEPAD PROGRAMB.Text$="After all, this is your own app"PUTCLOSEOpenFile:(FileName$)ENDPIn CreateFile:, we again check to see if the database alreadyexists – something a multi-file program will need, but this means wecan also use this to ‘reset’ our database from a menu option if we want to(i.e.

start again from scratch). We then create the two initial entries intothe Notepad so when the user opens the app they see something otherthan a white screen. Finally we CLOSE the database to ensure all thechanges are saved, and then call OpenFile: to re-open the database.6.2.4 The Position and Other Database CommandsOne of the things you’ll need to always keep in mind with your databaseis that each database can only reference one entry (with all the fields inthat one entry) at a time. That entry will be whatever the current positionin the database is. If your database is a stack of index cards, then theposition is the index card that is currently on top of the pile.You can find out where your position is in the database withCurrentPosition%=POSYou can jump to a specified position:POSITION NewPosition%or move through the records one at a time, both forwards and backwards usingNEXTandBACKJumping the position to the start or end of the database can be done withFIRSTandLASTOUR FIRST OPL DATABASE105All these commands (and other database commands) are, as usual, inthe command list Appendix.

They affect only the current database. Tochange to another database (if you have two or more databases open) usethe USE command with the reference letter:USE BWhenever you first open a database, it is set to be the current database,which is why the INI procedures never really needed the USE command.However, here we will begin to introduce it anyway because we havemore than one database – and of course it’s good programming style!6.2.5 Displaying a CursorIn the Othello program, we had a constant representing the height of theplaying squares so we knew just how many pixels we had to move thecursor.

In Notepad, we will have a variable to represent this – becausethe fonts we use on each UI are different heights. We set this PROC Init:just after working out which UI we are running on.Let’s say (for example) that our screen can see seven lines of text. Thecursor method we used in Othello will happily cope with seven lines oftext, but what happens at eight lines of text? The cursor value would beincreased to eight, and it would still be printed, but outside the visiblearea of the window.We overcome this with a dual cursor method:Three values are used, and are stored as GLOBAL variables:GLOBAL TrueCursor%, TopCursor%, MaxCursor%True CursorThis is the cursor value that you are most familiar with. It representswhich entry the cursor is on.

So if you have 100 entries in the database,106DATABASES AND A NOTEPAD PROGRAMand the cursor is on record 99, then the TrueCursor% will equal 99.TrueCursor% cannot have a value less than one or more than the totalnumber of entries.Top CursorIn our diagram, the thin box over one line (which is a single entry inthe database) represents the true cursor position.

The box covering sevenentries shows the seven entries that can be shown on the screen at anyone time.Going back to the question, what happens when we move the cursordown to the eighth entry? Well we simply shift this ‘visible display box’down to make sure the eighth entry is inside the box. In other words, ifTrueCursor% is going to drop out the visible display, then move downthe visible display one entry.To represent where this box is in the list of entries, our second cursorvalue is used. TopCursor% keeps track of the top entry in the visibledisplay box.Max CursorTopCursor% cannot have a value less than one, or allow itself to bemoved so far down the entries that there are less than (in this example)seven entries in the display box.

This job is helped by MaxCursor%,which is calculated in the Init: procedure. It holds the maximumnumber of entries that can be seen on the screen at any one time. In thiscase, MaxCursor%=7. How do we work it out?MaxCursor%=INT(ScreenHeight%/FontHeight%)This will be entered into PROC InitApp:, which we’ll discuss oncewe’ve looked at all the individual elements.Coding the Cursor MovementThe following lines need to be added into the KeyboardDriver:procedure:ELSEIF Key&=KKeyUpArrow%rem CursorUp:IF TrueCursor%=1 : RETURN : ENDIFTrueCursor%=TrueCursor%-1IF TopCursor%>TrueCursor%TopCursor%=TrueCursor%ENDIFPOSITION TrueCursor%OUR FIRST OPL DATABASE107ShowEntries:ELSEIF Key&=KKeyDownArrow%IF TrueCursor%=COUNT : RETURN : ENDIFTrueCursor%=TrueCursor%+1IF EOF : TrueCursor%=TrueCursor%-1 : RETURN : ENDIFPOSITION TrueCursor%IF TopCursor%+MaxCursor%<TrueCursor%TopCursor%=TopCursor%+1ENDIFShowEntries:As well as the similar commands to move the TrueCursor% that arefamiliar from Othello, we have added the code to move the ‘window’ ofentries around depending on where the TrueCursor% lies.On UIQ devices, you would also add in the Key& value for thescrolling wheel.

These are KKeyCBA1& and KKeyCBA2&.Displaying the EntriesThanks to one of the cursor values, we know which database entry willbe at the top of the screen (TopCursor%), and the number of entries weneed to show (MaxCursor%). A simple DO...UNTIL loop will suffice:PROC ShowEntries:LOCAL FooY%,Gnu%FooY%=FontHeight%gUSE Id%(KMainWindow%)USE B : POSITION TopCursor%Gnu%=0DOGnu%=Gnu%+1FooY%=FooY%+FontHeight%gAT 0,FooY%IF POS=TrueCursor% : gSTYLE 4 : ELSE : gSTYLE 0 : ENDIFgPRINTB B.Heading$,Text$,2ENDIFNEXTUNTIL MaxCursor%=Gnu% OR EOFShowEntries:ENDPEOF, end of file, will be true when the position in the database is atthe very end of the database, i.e. if NEXT is called when there are nomore entries.

We call up the values of the heading and text fields byB.Heading$ and B.Text$, which reference the database through theletter "B" and the fields by the names that were given to them when thedatabase was opened in this program.We only show the contents of the heading field in this main screen view.Just before the gPRINTB command (first used back in the Event Corechapter), there is the command gSTYLE. A full breakdown of all the styles108DATABASES AND A NOTEPAD PROGRAMcan be found in the command list, but the IF statement here decides ifthe current entry is the entry with the cursor on it.

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

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

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

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