Bada Tutorial - Fundamentals

Embed Size (px)

Citation preview

  • 8/3/2019 Bada Tutorial - Fundamentals

    1/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 1

    Version 1.0b1Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved

    bada Tutorial:

    Fundamentals(Idioms, Base, Io, System, Debugging)

  • 8/3/2019 Bada Tutorial - Fundamentals

    2/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 2

    Contents

    Idioms

    Base

    Collection

    Runtime

    Utility

    Io System

    Debugging

  • 8/3/2019 Bada Tutorial - Fundamentals

    3/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 3

    Overview

    The Fundamentals tutorial contains pre-requisite information thatyou need to start with bada and write your software.

    Read this tutorial after you have read the SDK tutorial and installedthe bada SDK and IDE. Use the bada SDK to access furtherinformation about the many examples and sample applications thatare explained in the tutorials.

    There are instances where bada departs slightly from what you maybe familiar with. It is important to identify these differences at thebeginning so that you can deal with them quickly and easily.

  • 8/3/2019 Bada Tutorial - Fundamentals

    4/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 4

    Version 1.0b1Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    Idioms

  • 8/3/2019 Bada Tutorial - Fundamentals

    5/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 5

    Contents

    Classes and Interfaces

    2-Phase Construction

    Motivation

    Construct Method

    Methods

    Exception Handling Ownership Policy

    Review

    Answers

  • 8/3/2019 Bada Tutorial - Fundamentals

    6/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 6

    Classes and Interfaces (1/2)

    Most classes in bada derive from the Object class.

    Exceptions: Classes that have only static methods.

    Samsung bada defines Interface (classes with an I prefix) as anabstract base class where all methods are purely virtual. Forexample: IList, IMap, and IEvent.

    Multiple Inheritance: To avoid the common pitfallsof multiple inheritance, classesMUST NOT inherit from morethan one base class.

    However, multiple interface

    inheritance is permitted. When inheriting from bada classes

    or interfaces, DO NOT use the

    virtual keyword unless there is a strong reason to do so.

    Object

    Most classes

    reside here Very few classesdo not derivefrom Object

  • 8/3/2019 Bada Tutorial - Fundamentals

    7/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 7

    Recommended Not Recommended

    public class MyForm

    :public Osp::Ui::Controls::Form,

    public Osp::Ui::IActionEventListener

    {

    InheritedClass(void);

    ~ InheritedClass(void);

    };

    public class MyForm

    :public Osp::Ui::Controls::Form,

    virtual public

    Osp::Ui::IActionEventListener

    {

    InheritedClass(void);

    ~ InheritedClass(void);

    };

    Classes and Interfaces (2/2)

    When using inheritance, do not use the virtual keyword, as it cancause problems on the bada target with the currently supportedtargeting environment and tool chain.

  • 8/3/2019 Bada Tutorial - Fundamentals

    8/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 8

    2-Phase Construction: Motivation

    In C++, when a failure occurs in allocating resources duringan objects construction, the object is partially constructed andits destructor is not called, possibly causing a resource leak.class SimpleClass;

    class ComplexClass

    {

    public:

    ComplexClass (void) {

    SimpleClass* p1 = new SimpleClass();

    SimpleClass* p2 = new SimpleClass(); // Out-of-memory error.

    }

    ~ComplexClass (void) { delete p1; delete p2; }

    private:

    SimpleClass* p1;SimpleClass* p2;

    };

    void

    MyClass::SomeFunction()

    {

    ComplexClass a; // Calls the constructor, which throws an exception.

    // Destructor is not called and p1 is leaked.

    }

  • 8/3/2019 Bada Tutorial - Fundamentals

    9/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 9

    2-Phase Construction: Construct Method

    To prevent resource leaks, resource allocation logic is extractedout of the constructor, and put into the Construct() method.

    class TwoPhaseClass

    {

    public:TwoPhaseClass(void) : p1(null), p2(null) { }

    ~TwoPhaseClass(void) { delete p1; delete p2; }

    result Construct(void) {SimpleClass * p1 = new SimpleClass();

    SimpleClass * p2 = new SimpleClass(); // Out-of-memory error.}

    private:

    SimpleClass* p1;SimpleClass* p2;

    };

    voidMyClass::SomeFunction()

    {

    TwoPhaseClass a; // Calls the constructor which does not throw an exception.

    // Calls the Construct() method which allocates two SimpleClass objects.

    // Destructor is called because a itself is fully constructed.result r = a.Construct();

    }

    1. Object obj; // Allocate memory.

    2. obj.Construct() // Construct object.

  • 8/3/2019 Bada Tutorial - Fundamentals

    10/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 10

    Methods

    There are no properties in bada. Everything is a method.This is total encapsulation.

    This means that you cannot directly access data in bada.

    Because data cannot be directly accessed, it is impossible for datato become corrupted, or to crash the device through data corruption.

    This provides a high level of safety for you as the developer,

    since you do not need to worry about data corruption.

    This also provides a high degree of security for mobile device users.These limitations on data access prevent malicious software from takingadvantage of certain type of security exploits, such as buffer overflows.

  • 8/3/2019 Bada Tutorial - Fundamentals

    11/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 11

    Exception Handling (1/4)

    Samsung bada uses error results instead of C++ exceptions. C++

    exceptions require too large of a runtime for resource-constraineddevices and incur too much overhead. All exceptions are caught as the return type result:

    The E_SUCCESS result indicates a method succeeded, while all otherresultvalues indicate an error.

    GetLastResult(): Returns the last exception or that set bySetLastResult().

    SetLastResult(): Changes the result value. GetErrorMessage(): Returns a char* containing a results message.

    There are 3 result reporting method types:a) result SomeClass::DoSomething()

    Result of the method execution is passed as a return value.

    b) SomeClass * SomeClass::DoSomething()

    The method returns pointer of some class if the method execution succeeds,while it returns null if an exception occurs.

    Calling GetLastResult() after execution of this method gives you the lastresult (exception).

    c) Value-type (or void) SomeClass::DoSomething() This method returns by value (including void) and you dont need to check the

    exception in this case.

  • 8/3/2019 Bada Tutorial - Fundamentals

    12/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 12

    Exception Handling (2/4)

    The following demonstrate three different ways to detect errors:

    result r = E_SUCCESS;

    ...

    // Case 1: The method returns a result.

    r = list.Construct(...);

    if (r != E_SUCCESS) // identical to 'if (IsFailed(r))'

    {

    // Process the error condition.

    }

    // Case 2: The method sets the result in the method body or returns null.

    pObj = list.GetAt(...);

    if (GetLastResult() != E_SUCCESS) // or 'if (pObj == null)'

    {

    // Process the error condition.

    }

    // Case 3r = pObj2->Construct(..);

    TryCatch(r == E_SUCCESS, , "[%s] Service could not be initialized.",

    GetErrorMessage(r));

    ...

    CATCH:

    delete pObj1;

    delete pObj2;

    return;

    If false goes to CATCH

  • 8/3/2019 Bada Tutorial - Fundamentals

    13/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 13

    Exception Handling (3/4)

    The following 4 cases demonstrate handling (propagating)

    and converting exceptions:result r = E_SUCCESS;

    ...

    // Case 1: Use a goto CATCH.r = pList->Construct(...);

    TryCatch(r == E_SUCCESS, delete pList, "[%s] Propagated.", GetErrorMessage(r));...

    CATCH:SetLastResult(r);return null;

    // Case 2: Return a result.

    r = list.Construct(...);

    TryReturn(r == E_SUCCESS, r, "[%s] Propagated.", GetErrorMessage(r);

    // Case 3: Return null.

    r = list.Construct(...);TryReturn(r == E_SUCCESS, null, "[%s] Propagated.", GetErrorMessage(r);

    // Case 4: Convert an error condition into another error condition.

    r = list.indexOf(...);

    TryReturn(r == E_SUCCESS, E_INVALID_ARG, "[E_INVALID_ARG] converted from '%s'.",GetErrorMessage(r));

    goto CATCH condition

    Change 'result' value

  • 8/3/2019 Bada Tutorial - Fundamentals

    14/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 14

    Exception Handling (4/4)

    Log fields are comma separated.

    Interpreting log exception messages:

    Complex objects are represented as shown below:

    0016.917,EXCEPTION,00,34,Osp::Base::Collection::ArrayList::RemoveItems (675), >[E_OUT_OF_RANGE] The startIndex(20) MUST be less than the number of elements(20).

    Prefix for exception log

    Fully-qualified name Line numberUsed internally

    Exception name Variable (actual_value)

    Timestamp

    0050.989,EXCEPTION,.. (), > [..] Thread(name:Consumer priority:5 ...) ..

    Object (property1:value1 property2:value2 ...)

  • 8/3/2019 Bada Tutorial - Fundamentals

    15/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 15

    Ownership Policy (1/3)

    Ownership implies responsibility to delete dynamically allocated

    memory and avoid memory leaks.

    That is, whatever owns an object MUST delete it when it is finished.

    For example:

    Object* pObj = new Object();

    ...

    delete pObj; // Must be deleted to avoid a memory leak.

  • 8/3/2019 Bada Tutorial - Fundamentals

    16/158Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 16

    Ownership Policy (2/3)

    Exclusive ownership means that the ownership cannot be shared.

    There are 2 rules for obtaining ownership:

    The new operator takes ownership of the allocated memory space.

    Ownership can be transferred, but it cannot be shared.

    Heap

    pObject1

    Ptr

    Object1

    pObject2Ptr

    Ownership

  • 8/3/2019 Bada Tutorial - Fundamentals

    17/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 17

    Ownership Policy (3/3)

    If a method has an N postfix, the caller MUST delete the returned

    instance after the caller is finished with the object. Otherwise,the memory for the object is leaked.

    Class ArrayList

    {public:

    IList* SearchN(const String& criteria) const;

    };

    IList* A::SearchN(const String& criteria){

    // Search with criteria and return the results by storing them in the list.

    ArrayList* pList = new ArrayList();

    // Add the search results to the list.

    // ...

    return pList;}

    VoidMyClass::SomeMethod(void)

    {

    A a;

    IList* pList = a.SearchN(L"Most popular");...

    delete pList;

    }

  • 8/3/2019 Bada Tutorial - Fundamentals

    18/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 18

    Review

    1. Can I play with data corruption and other madness?

    2. What is 2-phase construction for?

    3. How do you check for errors in bada?

    4. What does an N postfix signify?

    5. What result returns true from an IsFailed call?

    6. Can you call a Construct() method more than once orrepeatedly?

  • 8/3/2019 Bada Tutorial - Fundamentals

    19/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 19

    Answers

    1. Not really. Samsung bada uses total encapsulation to help insulate

    you from possible data corruption.

    2. 2-phase construction prevents possible resource leaks.

    3. Check the result (a type) of a method call.

    4. An N postfix in a method name indicates that you must manually

    delete the instance that it returns to avoid a memory leak.5. All results except for E_SUCCESS return true in IsFailed.

    6. No. All classes with 2-phase construction have at least 1Construct() method, with many having several overloadedConstruct() methods in order to facilitate different scenarios.

    However, only 1 method should be used, and only used once.Samsung bada classes do not guarantee correct behavior if aConstruct() method is called more than once.

  • 8/3/2019 Bada Tutorial - Fundamentals

    20/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 20Version 1.0b1

    Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    Base

  • 8/3/2019 Bada Tutorial - Fundamentals

    21/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 21

    Contents

    Essential Classes

    Relationships between Classes

    Overview

    Types

    String

    Example: Create and Modify Strings DateTime and TimeSpan

    Example: Create and Use DateTimes

    UuId

    Example: Create a UuId

    Buffer Example: Use Buffers

    FAQ

  • 8/3/2019 Bada Tutorial - Fundamentals

    22/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 22

    Essential Classes (1/2)

    Feature Provided by

    Provides the root class for most classes in bada. Object

    Wraps the native bool. Boolean

    Provides a parameterized class for the primitive array type. Buffer

    Provides the base class for buffers. BufferBase

    Wraps the native byte (unsigned 8-bit integer) array. ByteBuffer

    Provides the abstract base for all numeric value types. Number

    Wraps the native mchar (Unicode character). Character

    Wraps the native double. Double

    Enables comparing Doubles. DoubleComparer

    Wraps the native float. Float

    Enables comparing Floats. FloatComparer

    Wraps the native char (signed 8-bit integer). Int8

    Enables comparing Int8s. Int8Comparer

    Wraps the native int (singed 32-bit integer). Integer

    Enables comparing Integers. IntegerComparer

  • 8/3/2019 Bada Tutorial - Fundamentals

    23/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 23

    Essential Classes (2/2)

    Feature Provided by

    Wraps the native short (signed 16-bit integer). Short

    Enables comparing Shorts. ShortComparer

    Wraps the native long (singed 32-bit integer). Long

    Enables comparing Longs. LongComparer

    Wraps the native long long (singed 64-bit integer). LongLong

    Enables comparing LongLongs. LongLongComparer

    Represents a Unicode string. String

    Enables comparing Strings. StringComparer

    Enables comparing primitive types. ComparerT

    Represents a date and time. DateTime

    Represents an amount of time in milliseconds. TimeSpan

    Wraps the native UUID. UuId

  • 8/3/2019 Bada Tutorial - Fundamentals

    24/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 24

    Relationships between Classes

  • 8/3/2019 Bada Tutorial - Fundamentals

    25/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 25

    Overview

    The Base namespace contains classes and interfaces for base

    types and enumerations, such as String, Buffer, and DateTime. Object:

    The Object class is the base class for most other classes includedin the framework.

    Object provides methods for testing instance equivalence andobtaining an instances hash value.

    Object makes it easier to define behaviors and characteristics thatmust be shared by all classes in the framework.

    Value types: Classes inherited from the Number class wrap C++ primitive types,

    such as char, int, short, long, float, double, and longlong.

  • 8/3/2019 Bada Tutorial - Fundamentals

    26/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 26

    String (1/2)

    A String is a mutable sequence of 2-byte Unicode characters.

    String capacity:

    If no default capacity is specified, the capacity is set to 16 bytes.

    The maximum possible capacity is 2^32 - 1.

    Capacity grows at 1.5 * the current length rounded to the nearestmultiple of 4. Starting from the default capacity of 16 that is:

    16, 24, 36, 54, 80, 120, 180, 272, 408...

    Methods

    Append() Appends the indicated value to the String.

    Insert() Inserts the indicated value at the position.

    Remove() Removes characters within the specified range.IndexOf() Returns the index of the character.

    SubString() Returns the indicated substring.

    ToUpper() Converts all letters to upper case.

    ToLower() Converts all letters to lower case.

  • 8/3/2019 Bada Tutorial - Fundamentals

    27/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 27

    String (2/2)

    You can modify strings using the methods. For example:1. Prefix a string literal with an upper-case L.

    2. Concatenate the string with the Append() method.

    3. Convert the string to upper case with the ToUpper() method.

    4. Delete a substring from a string with the Remove() method.

    String str(Ltest);

    str.Append(L String); // test String

    str.ToUpper(); // TEST STRING

    str.Remove(0, 4); // STRING

    1.

    2.

    3.

    4.

  • 8/3/2019 Bada Tutorial - Fundamentals

    28/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 28

    Example: Create and Modify Strings

    Learn how to use the String class.

    Open \\Examples\Fundamentals\src\BaseExample.cpp, StringExample()

    1. Create an empty String.

    2. Append an integer value to the String instance:

    String::Append(value)

    3. Insert text into the String instance:String::Insert(value, atPosition)

    4. Create a String instance with some text:String::String(value)

    5. Get a substring from the String instance:String::SubString(start, end, string)

  • 8/3/2019 Bada Tutorial - Fundamentals

    29/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 29

    DateTime and TimeSpan (1/2)

    A DateTime represents an instance of a specific date and

    time ranging from 12:00:00 am (Midnight), January 1, 1 A.D.,to 11:59:59 pm, December 31, 9999 A.D.

    A TimeSpan represents a time duration measured in milliseconds.

    DateTime vs. TimeSpan:

    A DateTime represents a single instant in time where a TimeSpan

    represents an amount of time.

    Both include addition and subtraction methods.

    You cannot add 2 DateTimes together.

    You can add a TimeSpan to a DateTime to get a second DateTime.

    You can add a TimeSpan to a TimeSpan to get a second TimeSpan.

  • 8/3/2019 Bada Tutorial - Fundamentals

    30/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 30

    DateTime and TimeSpan (2/2)

    Set DateTimes values with:

    Year, month, and day

    Year, month, day, hour, minutes, and seconds

    Another DateTime

    A TimeSpan since January 1, 1 A.D. 00:00:00 am

    Add (or subtract) time from a DateTime using any of the Add~()

    methods.

    Get a part of a DateTime with any of the Get~() methods.

    Query if it is a leap year with the IsLeapYear() method.

    DateTime dt;

    dt.SetValue(2009, 12, 23); // 2009-12-23

    dt.AddYears(10); // 2019-12-23

    int year = dt.GetYear(); // 2019

    bool leap = dt.IsLeapYear(); // false

  • 8/3/2019 Bada Tutorial - Fundamentals

    31/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 31

    Example: Create and Use DateTimes

    Learn how to use the DateTime class.

    Open \\Examples\Fundamentals\src\BaseExample.cpp, DateTimeExample()

    1. Create a DateTime instance.

    2. Set the DateTime instance year, month, and day:

    DateTime::SetValue(yyyy, mm, dd)3. Add several years to the DateTime instance:

    DateTime::AddYears(years)

    4. Add several months to the DateTime instance:DateTime::AddMonths(months)

    5. Add several days to the DateTime instance:

    DateTime::AddDays(days)6. Get the year portion from the DateTime instance:

    DateTime::GetYear()

    7. Get the month portion from the DateTime instance:DateTime::GetMonth()

    8. Get the day portion from the DateTime instance:DateTime::GetDay()

  • 8/3/2019 Bada Tutorial - Fundamentals

    32/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 32

    UuId

    UuId is a wrapper class for the UUID (Universally Unique Identifier)

    type and includes several useful operators: typedef struct {

    unsigned long x;

    unsigned short s1;

    unsigned short s2;

    unsigned char c[8];

    } UUID;

    UuId Methods and Operators

    Parse() Parses a string representation of a UuId.

    ToString() Returns a string from a UuId.operator!= (const UuId &uuid) Operators must be balanced on the

    right side by something of type UuIdthat contains a UuId value.

    operator== (const UuId &uuid)

    operator= (const UuId &uuid)

  • 8/3/2019 Bada Tutorial - Fundamentals

    33/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 33

    Example: Create a UuId

    Parse a String to create a UuId.

    Open \\Examples\Fundamentals\src\BaseExample.cpp, UuIdExample()

    1. Create a UuId instance.

    2. Create a String that contains a UUID value.

    3. Parse the String with the UuId:UuId::Parse(string)

    4. Get a String representation of the UuId instance:UuId::ToString()

  • 8/3/2019 Bada Tutorial - Fundamentals

    34/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 34

    Buffer (1/3)

    Buffers contain sequences of a specific primitive type, such as int,

    long, double, and char.

    Access to data:

    Absolute read and write methods access data from index 0 to limit -1,and do not modify the properties.

    Relative read and write methods access data from position to limit -1,and move the position to the next when one of the methods is applied.

    Buffer Properties

    Capacity The number of elements that a buffer contains.

    Limit The index of the first element that should not be read or written.

    Position The index of the next element to be read or written.

    Mark Stores an index so that later the position can be set to that index.That is, it sets a marker on an index.

  • 8/3/2019 Bada Tutorial - Fundamentals

    35/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 35

    Buffer (2/3)

    Marking and resetting:

    Mark stores the current position when SetMark() is called. The current position is set to the marker when Reset() is called.

    Markers are invalidated when a position or limit is set to a value lessthan the markers index, InvalidateMark() is called, or Rewind() iscalled.

    ByteBuffer buf;buf.Construct(10); // position: 0

    // limit, capacity: 10

    buf.SetPosition(7); // position: 7

    buf.Flip(); // position: 0

    // limit: 7, capacity: 10

    Buffer Methods

    Clear() Sets the limit to the capacity, the position to zero, and deletes the marker.

    Flip() Sets the limit to the current position and the position to an index.Passing POSITION_TO_ZERO to the method deletes the marker.

    Rewind() Sets the position to zero and leaves the limit unchanged.

  • 8/3/2019 Bada Tutorial - Fundamentals

    36/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 36

    Buffer (3/3)

    Buffer is a parameterized (template-based) class for

    primitive type arrays: typedef Buffer DoubleBuffer

    typedef Buffer FloatBuffer

    typedef Buffer IntBuffer

    typedef Buffer LongBuffer

    typedef Buffer LongLongBuffer

    typedef Buffer McharBuffer

    typedef Buffer ShortBuffer

    ByteBuffer is a wrapper class for a byte (unsigned 8-bit integer)

    array. It defines methods for reading and writing all primitive built-intypes to and from a sequence of bytes.

  • 8/3/2019 Bada Tutorial - Fundamentals

    37/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 37

    Example: Use Buffers

    Learn how to use the Buffer class.

    Open \\Examples\Fundamentals\src\BaseExample.cpp, BufferExample()

    1. Construct an IntBuffer with a specified capacity:IntBuffer::Construct(size)

    2. Declare an array of integers.

    3. Copy all values from the integer array to the IntBuffer instance:IntBuffer::SetArray(array, index, length)

    4. Construct a DoubleBufferwith the same size as the IntBuffer:DoubleBuffer::Construct(size)

    5. Read a value from the IntBuffer and write it to the DoubleBuffer:IntBuffer::Get(value)

    DoubleBuffer::Set(value)

  • 8/3/2019 Bada Tutorial - Fundamentals

    38/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 38

    FAQ

    Can I use Buffer or Buffer?

    No. Do not use either of them. Buffer is the same asIntBuffer. It is highly recommended to use only pre-defined buffers.

    The available buffers are as follows:

    Buffer Primitive Type

    DoubleBuffer double

    FloatBuffer float

    IntBuffer int

    LongBuffer long

    LongLongBuffer longlongMcharBuffer mchar

    ShortBuffer short

  • 8/3/2019 Bada Tutorial - Fundamentals

    39/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 39Version 1.0b1

    Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    Collection

  • 8/3/2019 Bada Tutorial - Fundamentals

    40/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 40

    Contents

    Essential Classes

    Relationships between Classes Overview

    Interfaces

    MapEntry

    ArrayList and LinkedList

    Example: Construct and Modify an ArrayList

    Example: Create and Modify a LinkedListT

    HashMap and MultiHashMap

    Example: Construct and Use a HashMap

    Stack and Queue

    Example: Construct and Use a Stack

    ICompare

    FAQ

    Review

    Answers

  • 8/3/2019 Bada Tutorial - Fundamentals

    41/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 41

    Essential Classes (1/4)

    Feature Provided by

    Represents a last-in, first-out (LIFO) collection. Stack

    Represents a first-in, first-out (FIFO) collection. Queue

    Represents a collection that is individually accessed by index. ArrayList

    Represents a collection that is sequentially accessed. LinkedList

    Represents a collection of key-value pairs that are organized basedon the keys hash code.

    HashMap

    Represents a collection of key-value pairs that are organized based onthe keys hash code. Duplicated keys are allowed, but key-value pairsmust be unique.

    MultiHashMap

    Represents a key-value pair. MapEntry

  • 8/3/2019 Bada Tutorial - Fundamentals

    42/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 42

    Essential Classes (2/4)

    Feature Provided by

    Represents a first-in, last-out template-based collection StackT

    Represents a first-in, first-out template-based collection QueueT

    Represents a template-based collection that is individuallyaccessed by index.

    ArrayListT

    Represents a template-based collection that is sequentially accessed. LinkedListT

    Represents a template-based collection of key-value pairs thatare organized based on the keys hash code.

    HashMapT

    Represents a template-based collection of key-value pairs that areorganized based on the keys hash code. Duplicated keys are allowed,

    but key-value pairs must be unique.

    MultiHashMapT

    Represents a template-based key-value pair. MapEntryT

  • 8/3/2019 Bada Tutorial - Fundamentals

    43/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 43

    Essential Classes (3/4)

    Feature Provided by

    Represents a collection of objects, and defines the size, enumerator,and synchronization mechanism.

    ICollection

    Enables iteration over a collection. IEnumerator

    Represents a collection that is accessed by index. IList

    Represents a collection of key-value pairs. IMap

    Represents a collection of key-value pairs that may have duplicated keys. IMultiMap

    Enables iteration over a map. IMapEnumerator

    Represents a collection of key-value pairs indexed by the keyshash value.

    IHashCodeProvider

    Enables comparisons of two objects. IComparer

  • 8/3/2019 Bada Tutorial - Fundamentals

    44/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 44

    Essential Classes (4/4)

    Feature Provided by

    Represents a template-based collection of objects, and defines the size,enumerator, and synchronization mechanism.

    ICollectionT

    Enables iteration over a template-based collection. IEnumeratorT

    Represents a template-based collection that is accessed by index. IListT

    Represents a template-based collection of key-value pairs. IMapT

    Represents a template-based collection of key-value pairs that may have

    duplicated keys.

    IMultiMapT

    Enables iteration over a template-based map. IMapEnumeratorT

    Represents a template-based collection of key-value pairs indexed bythe keys hash value.

    IHashCodeProviderT

    Enables comparisons of two template-based objects. IComparerT

  • 8/3/2019 Bada Tutorial - Fundamentals

    45/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 45

    Relationships between Classes (1/2)

    Object-based collections

  • 8/3/2019 Bada Tutorial - Fundamentals

    46/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 46

    Relationships between Classes (2/2)

    Template-based collections

  • 8/3/2019 Bada Tutorial - Fundamentals

    47/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 47

    Overview (1/2)

    The Collection namespace contains classes and interfaces

    that define various collections. There are object- and template-based collections:

    Object-based collections derive from ICollection and store objectsthat derive from Object.

    Template-based collections derive from ICollectionT

    and can store primitive types.

    For every class or interface available to an object-based collection,there is a corresponding class or interface available to a template-based collection.

  • 8/3/2019 Bada Tutorial - Fundamentals

    48/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 48

    Overview (2/2)

    IMPORTANT: Object-based collections do not copy objects;

    they only keep pointers to objects. Do not put stack variablesinto collections.

    Template-based collections are mainly used for primitive types.

    ArrayList list;

    list.Construct();

    String str(L"One"); // Do not put stack variables

    list.Add(str); // into collections.

    String* pStr = new String(L"One"); // Use heap variableslist.Add(*pStr); // with collections.

    ArrayListT list;list.Construct();

    int value = 10;

    list.Add(value);

  • 8/3/2019 Bada Tutorial - Fundamentals

    49/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 49

    Interfaces (1/4)

    ICollection is the base interface for all collection classes.

    An ICollection represents a collection of objects, and defines

    the size and enumerator:

    GetCount()

    GetEnumeratorN()

    ICollection

    IList IMap IMultiMap

  • 8/3/2019 Bada Tutorial - Fundamentals

    50/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 50

    Interfaces (2/4)

    IList represents a collection where individual items can be

    individually accessed by index. Methods:

    Add(), Remove(), Contains()

    GetAt(), SetAt()

    InsertAt(), RemoveAt()

    AddItems(), InsertItemsFrom(), RemoveItems(), GetItemsN() ContainsAll(), RemoveAll()

    IndexOf(), LastIndexOf()

    Sort()

  • 8/3/2019 Bada Tutorial - Fundamentals

    51/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 51

    Interfaces (3/4)

    IMap and IMultiMap represent collections of key-value pairs.

    All IMap keys must be unique.

    IMultiMaps can have more than one element with the same key.

    Methods:

    Add(), Remove()

    ContainsKey(), ContainsValue()

    GetValue(), SetValue()

    GetKeysN(), GetValuesN()

    AddItems(), RemoveItems()

    RemoveAll()

    GetEnumeratorN(), GetMapEnumeratorN()

  • 8/3/2019 Bada Tutorial - Fundamentals

    52/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 52

    Interfaces (4/4)

    IEnumerator facilitates simple iteration over a collection:

    GetCurrent()

    MoveNext()

    Reset()

    IMapEnumerator methods:

    GetKey()

    GetValue()

    GetCurrent()

    IBidirectionalEnumerator methods: MovePrevious()

    ResetLast()

    IEnumerator

    IMapEnumerator IBidirectionalEnumerator

  • 8/3/2019 Bada Tutorial - Fundamentals

    53/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 53

    MapEntry

    A MapEntry holds a key-value pair.

    MapEntries are used with the IMapEnumerator interface.IMapEnumerator::GetCurrent() returns a MapEntry object.

    MapEntry

    Value()

    Key()

    IMapEnumerator

    GetKey()

    GetValue()

    GetCurrent()

  • 8/3/2019 Bada Tutorial - Fundamentals

    54/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 54

    ArrayList and LinkedList

    An ArrayList is a collection of objects that can be individually

    accessed by index. The capacity of an ArrayList is the number ofelements the list can hold. As elements are added to a list, thecapacity is automatically increased as required through reallocation.The default capacity is 10.

    A LinkedList is a collection of objects that can be sequentially

    accessed.

    List Methods

    SetCapacity() Sets the list capacity.

    Add() Adds an object to the end of the list.

    RemoveAt() Removes an object at an index.Contains() Returns true if the list contains the specified object.

    GetAt() Gets the object at the specified index.

    SetAt() Replaces an object at the specified index with another object.

  • 8/3/2019 Bada Tutorial - Fundamentals

    55/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 55

    Example: Construct and Modify an ArrayList

    Learn how to use an ArrayList.

    Open \\Examples\Fundamentals\src\CollectionExample.cpp, ArrayListExample()

    1. Construct an ArrayList:ArrayList::Construct()

    2. Add elements to the list:

    ArrayList::Add(object)3. Get an element from the list:ArrayList::GetAt(index)

    4. Insert an element into the list:ArrayList::InsertAt(object, index)

    5. Remove an element from the list:ArrayList::Remove(object)

    ArrayList::RemoveAt(index)6. Sort the list:

    ArrayList::Sort(comparer)

    7. Get an enumerator and use it to access elements in the list:ArrayList::GetEnumeratorN()

    8. Delete all elements in the list:ArrayList::RemoveAll()

    Example: Create and Modify a LinkedListT

  • 8/3/2019 Bada Tutorial - Fundamentals

    56/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 56

    Example: Create and Modify a LinkedListT(1/2) Learn how to use a LinkedListT.

    Open \\Examples\Fundamentals\src\CollectionExample.cpp, LinkedListTExample()

    1. Create a LinkedListT.

    2. Add elements into the list:

    LinkedListT::Add()3. Get all elements from the list:

    LinkedListT::GetAt()

    4. Insert an element into the list:LinkedListT::InsertAt()

    5. Sort the list:LinkedListT::Sort()

    6. Remove an element from the list:LinkedListT::Remove()

    LinkedListT::RemoveAt()

    Example: Create and Modify a LinkedListT

  • 8/3/2019 Bada Tutorial - Fundamentals

    57/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 57

    Example: Create and Modify a LinkedListT(2/2)

    7. Remove an element at a specified index from the list:

    LinkedListT::RemoveAt()8. Get an enumerator and use it to iterate through the list:

    LinkedListT::GetEnumeratorN()

  • 8/3/2019 Bada Tutorial - Fundamentals

    58/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 58

    HashMap and MultiHashMap

    A HashMap is a collection of associated key-value pairs that are organized

    based on the hash code of the key. The default capacity is 16. HashMapscannot contain duplicate keys. Each key maps to one value.

    MultiHashMaps can have keys that uniquely map to multiple values. That

    is, while neither keys nor values are required to be unique, each key-valuepair must be unique.

    HashMap Methods

    Add() Adds a key-value pair.

    Remove() Removes the key-value pair containing the specified key.

    SetValue() Replaces the value associated with the specified key with a new value.

    GetValue() Gets the value associated with the specified key.

    ContainsKey() Returns true if the HashMap contains the specified key.

    ContainsValue() Returns true if the HashMap contains the specified value.

  • 8/3/2019 Bada Tutorial - Fundamentals

    59/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 59

    Example: Construct and Use a HashMap

    Learn how to use a HashMap:

    Open \\Examples\Fundamentals\src\CollectionExample.cpp, HashMapExample()

    1. Construct a HashMap:HashMap::Construct()

    2. Add key-value pairs to the HashMap:HashMap::Add()

    3. Use a key to get a value:HashMap::GetValue()

    4. Use a key to remove a value:

    HashMap::Remove()5. Get an enumerator and use it to iterate through the HashMap:

    HashMap::GetMapEnumeratorN()

    6. Delete all key-value pairs:HashMap::RemoveAll()

  • 8/3/2019 Bada Tutorial - Fundamentals

    60/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 60

    Stack and Queue (1/2)

    A stack is a last-in, first-out (LIFO or FILO) collection of objects.

    If the stack reaches its capacity, the capacity is automaticallyincreased to accommodate more elements.

    A queue is a first-in, first-out (FIFO) collection of objects.

    Objects stored in a queue are inserted at one end and removed fromthe other. Capacity is automatically increased to accommodate more

    elements.

    Methods

    Push() Inserts an object at the top of the stack.

    Pop() Gets and removes the object at the top of the stack.

    Peek() Gets the object at the top of the stack without removing it.

    Methods

    Enqueue() Inserts an object at the end of the queue.

    Dequeue() Gets and removes the element at the beginningof the queue.

  • 8/3/2019 Bada Tutorial - Fundamentals

    61/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 61

    Stack and Queue (2/2)

    Enqueue

    Push

    Dequeue

    Pop

    1

    2

    3

    123

    32123

    LIFO stack

    FIFO queue

    1

    Stack: 3 is Last In, so

    it is, First Out.

    Queue: 1 is First In,so it is, First Out.

  • 8/3/2019 Bada Tutorial - Fundamentals

    62/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 62

    Example: Construct and Use a Stack

    Learn how to use a stack.

    Open \\Examples\Fundamentals\src\CollectionExample.cpp, StackExample()

    1. Construct a stack and specify its capacity:Stack::Construct(capacity)

    2. Push an element onto the stack:Stack::Push(object)

    3. Peek at an element to view its value without removing it:Stack::Peek()

    4. Pop an element from the stack to get its value and remove it:

    Stack::Pop()5. Delete all elements from the stack:

    Stack::RemoveAll()

  • 8/3/2019 Bada Tutorial - Fundamentals

    63/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 63

    ICompare

    ICompare interface implementations compare two object values

    and get an integer result. A result of zero indicates equality.A negative or positive result indicates that the first value is less orgreater than the second value, respectively.

    The following implementationsare supplied with bada:

    DoubleComparer FloatComparer

    Int8Comparer

    IntegerComparer

    LongComparer

    LongLongComparer

    ShortComparer

    StringComparer

    The StringComparer class tests for equivalence.

    That is, < 0 and > 0 have the same meaning, not equivalent.

    Result Means

    < 0 Value1 is less than value2.

    == 0 Value1 is equal to value2.

    > 0 Value1 is greater than value2.

    Q ( /2)

  • 8/3/2019 Bada Tutorial - Fundamentals

    64/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 64

    FAQ (1/2)

    What is the difference between the ArrayList and LinkedList?

    ArrayLists store elements in contiguous memory space. This makesaccessing ArrayLists by index very fast. However, adding andremoving elements is slower than with a LinkedList.

    LinkedLists store elements in nodes that are connected by pointers.This makes accessing LinkedLists by index slower than accessingArrayLists by index. However, adding and removing elements isfaster than with an ArrayList.

    Add or Remove Access

    ArrayList SLOW FAST

    LinkedList FAST SLOW

    FAQ (2/2)

  • 8/3/2019 Bada Tutorial - Fundamentals

    65/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 65

    FAQ (2/2)

    Why must I call RemoveAll(true) before deleting an instance of

    an object-based collection? Object-based collections do not include the ownership concept for

    dynamically allocated memory, so the collections only manage pointersto objects on the heap.

    If you delete the collection, it only deallocates the pointers, and not the

    real objects on the heap. This is a potential memory leak. To avoid memory leaks, you must delete all objects manually or call

    RemoveAll(true).

    However, you do not need to do this in template-based collectionsbecause they manage the objects themselves, and not just the pointers.

    R i

  • 8/3/2019 Bada Tutorial - Fundamentals

    66/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 66

    Review

    1. What 4-letter word describes a stack?

    2. What other 4-letter word describes a queue?3. What method returns a MapEntry?

    A

  • 8/3/2019 Bada Tutorial - Fundamentals

    67/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 67

    Answers

    1. LIFO or FILO.

    2. FIFO.3. IMapEnumerator::GetCurrent().

  • 8/3/2019 Bada Tutorial - Fundamentals

    68/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 68Version 1.0b1

    Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    Runtime

    C t t

  • 8/3/2019 Bada Tutorial - Fundamentals

    69/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 69

    Contents

    Essential Classes and Relationships

    Synchronization Objects

    Mutexes and Semaphores

    Monitor

    Example: Use a Monitor

    Threading Thread-safety

    Thread Types

    Thread Programming

    Timer

    Example: Periodic Timer

    Review

    Answers

    E ti l Cl d R l ti hi

  • 8/3/2019 Bada Tutorial - Fundamentals

    70/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 70

    Essential Classes and Relationships

    Feature Provided by

    Provides a timer. Timer

    Provides a synchronization primitive that grants exclusive access to a shared resource. Mutex

    Provides a synchronization object that maintains a count between zero and a maximum value. Semaphore

    Provides for mutual exclusion with waiting and notification. Monitor

    Provides a thread class that can be inherited. Thread

    IRunnable

    Thread

    Monitor

    Mutex

    Semaphore

    ITimerEventListener

    Timer

    Ti

  • 8/3/2019 Bada Tutorial - Fundamentals

    71/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 71

    Timer

    You can run code at pre-defined intervals using a Timer.

    Once a timer fires, it does not fire again unless you explicitlyset it again. That is, the Timer object is not a periodic timer.

    You cannot use timers in worker threads.

    When a timer times out, theITimerEventListener::OnTimerExpired() event handler is

    called. You can restart the Timer in the event handler to emulate a periodictimer. For example:

    Timer* pTimer = new Timer;

    pTimer->Construct(*pTimerEventListener);

    pTimer->Start(1000); // The timer fires after 1000 milliseconds

    // and the OnTimerExpired event handler

    // is called.

    ...

    void OnTimerExpired(Timer& timer) // Timer event handler.

    {

    DoSomethingUseful(); // Do something useful.

    timer.Start(1000); // Reset the timer.

    }

    E l P i di Ti

  • 8/3/2019 Bada Tutorial - Fundamentals

    72/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 72

    Example: Periodic Timer

    Create a timer and reset it in the event handler so that it mimics

    a periodic timer. Open \\Examples\Fundamentals\src

    \RuntimeExample.cpp, TimerExample()

    1. Create a class and implement an ITimerEventListener in it.

    2. Create a timer.3. Initialize the timer and set the listener:

    Timer::Construct(listener)

    4. Start the time:Timer::Start(milliseconds)

    5. When the time elapses, set the time again in the event handler:Timer::Start(milliseconds)

    S nch oni ation Objects

  • 8/3/2019 Bada Tutorial - Fundamentals

    73/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 73

    Synchronization Objects

    Synchronization objects:

    Mutex: Mutual exclusion (mutex) objects allow multiple threads to access a shared

    resource one at a time in a thread safe manner. A mutex locks an object forexclusive access by a thread.

    Threads that wish to access a mutex-locked object are queued untilthe mutex is released.

    Semaphore: Semaphores allow a limited number of threads to access a resource,

    and keep track of how many threads are accessing that resource.

    Monitor:

    Monitors provide locks for objects to stop other objects from accessingthem when they are in an inconsistent state.

    Using monitors runs the risk of creating a deadlock.

    Monitors support mutual exclusion and wait and notify.

    Mutexes and Semaphores

  • 8/3/2019 Bada Tutorial - Fundamentals

    74/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 74

    Mutexes and Semaphores

    Methods:

    Acquire(): Acquires the resource if it is not acquired. Release(): Releases the resource.

    Examples:

    Mutex Semaphore

    Mutex* pMutex = new

    Mutex;

    pMutex->Create();

    mutex->Acquire();

    // Use shared resource

    mutex->Release();

    Semaphore* pSemaphore = new

    Semaphore;

    pSemaphore >Create();

    semaphore->Acquire();

    // Use shared resource

    semaphore->Release();

    Monitor (1/3)

  • 8/3/2019 Bada Tutorial - Fundamentals

    75/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 75

    Monitor (1/3)

    Monitors provide a way to synchronize (lock) access to objects by

    maintaining a list of threads waiting to access an object. When a thread owns a lock, no other thread may access the object

    until the owning thread relinquishes the lock.

    The section of code where shared resources are used is called thecritical section. These code blocks are enclosed with the monitors

    Enter() and Exit() methods as illustrated below.

    pMonitor->Enter();

    // 1) Do something.

    // 2) Wait, Notify,// or NotifyAll.

    pMonitor->Exit();

    Criticalsection

    Start critical section

    End critical section

    Monitor (2/3)

  • 8/3/2019 Bada Tutorial - Fundamentals

    76/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 76

    Monitor (2/3)

    The Wait(), Notify(), and NotifyAll() methods can only be

    called inside of a critical section, between an Enter() and anExit() call.

    Monitor Methods

    Enter() Marks the start of a critical section (block of code)and locks an object.

    Exit() Marks the end of a critical section (block of code)and releases the lock on the object.

    Wait() Pauses a thread until notified (by another thread).

    Notify() Notifies a waiting thread and releases the locked object to

    it. Thread execution continues.NotifyAll() Notifies all waiting threads. Thread execution continues.

    Monitor (3/3)

  • 8/3/2019 Bada Tutorial - Fundamentals

    77/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 77

    Monitor (3/3)

    Threads that have locks (monitors), transfer execution to waiting

    threads through notifications. Waiting threads resume executionfrom their last called Wait position.

    1. Thread A pauses after 1) Do something and waits for a notificationwhile Thread B is running.

    2. Thread B finishes 2) Do something and notifies Thread A. Thisreleases the lock from Thread B and transfers the lock to Thread A.

    3. Thread A resumes execution and proceeds to 3) Do something.

    Thread A

    pMonitor->Enter();

    // 1) Do something.

    pMonitor->Wait();

    // 3) Do something.

    pMonitor->Exit();

    Thread B

    pMonitor->Enter();

    // 2) Do something.

    pMonitor->Notify();

    pMonitor->Exit();

    Transfers lock from B to A

    Example: Use a Monitor (1/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    78/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 78

    Example: Use a Monitor (1/8)

    Create 2 threads that pass access to a shared private resource

    between themselves. Producer produces (writes) the value for theshared resource, while Consumer consumes (reads) the value.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    There are 3 main steps in this example. Each is broken down intosmaller portions with explanations and code-walk-throughs.

    1. Create 2 classes (Producer and Consumer) that each share a

    monitor and an integer.2. Create the Producers Run() method.

    3. Create the Consumers Run() method.

    Example: Use a Monitor (2/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    79/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 79

    Example: Use a Monitor (2/8)

    Create the Producer class.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    1. Create 2 classes (Producer and Consumer) that each share a

    monitor and an integer.a) The Producer Run() method waits for the Consumer thread to start and

    sets a value for the shared resource (__pShared). It then notifies theConsumer thread.

    class Producer : public Osp::Base::Runtime::Thread

    {

    public:

    Producer(int* pShared, Osp::Base::Runtime::Monitor*pMonitor);

    Osp::Base::Object* Run(void);

    private:

    Osp::Base::Runtime::Monitor* __pMonitor;int* __pShared;

    };

    Shared privateresources

    Example: Use a Monitor (3/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    80/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 80

    Example: Use a Monitor (3/8)

    Create the Consumer class.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    b) The Consumer Run() method waits for a notification from the Producerthread and reads the value of the shared resource (__pShared). It thennotifies the Producer thread so that the producer thread can increment thevalue of the shared resource (__pShared).

    class Consumer : public Osp::Base::Runtime::Thread

    {public:

    Consumer(int* pShared, Osp::Base::Runtime::Monitor*

    pMonitor);Osp::Base::Object* Run(void);

    private:

    Osp::Base::Runtime::Monitor* __pMonitor;

    int* __pShared;

    };

    Shared privateresources

    Example: Use a Monitor (4/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    81/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 81

    Example: Use a Monitor (4/8)

    Create the Producers Run() method.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    Object* Producer::Run(void)

    {

    result r;

    // Begin critical section

    r = __pMonitor->Enter();// Wait for the Consumer to start

    r = __pMonitor->Wait();

    // Produce number value 6 times

    for (int i = 0; i < 6; i++)

    {

    //See next page for loop details

    }// Exit the monitor

    r = __pMonitor->Exit();

    return null;

    CATCH2:

    __pMonitor->Exit();

    return null;

    }

    a

    b

    d

    c

    2. In the Producers Run() method:a) Enter() the monitor.

    This marks the start of the criticalsection where the lock is obtained.

    b) Wait() for the Consumer to start.The entire process relies on boththreads, so you must ensure that theother thread is alive. You do this lettingthe Producer thread wait here andcalling Notify() at the beginning ofthe Consumer thread.

    c) Enter() the monitor.This marks the start of the criticalsection where the lock is obtained.

    d) Wait() for the Consumer to start.The entire process relies on boththreads, so you must ensure that theother thread is alive. You do this lettingthe Producer thread wait here andcalling Notify() at the beginning ofthe Consumer thread.

    Example: Use a Monitor (5/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    82/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 82

    Example: Use a Monitor (5/8)

    Create the Producers loop.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    During Step 2c, in the Producers Run() method:The loop increments the shared integer, __pShared. It then passes control tothe Consumer thread and continues execution. If __pShared is 5, the loopexits; otherwise execution continues and pauses until the Consumer thread

    passes control back.// Produce number value 6 times

    for (int i = 0; i < 6; i++)

    {

    *__pShared = i;// Notify consumer thread

    r = __pMonitor->Notify();

    if (*__pShared == 5) break;

    // Wait until consumer thread reads the value

    r = __pMonitor->Wait();

    }Pause for the Consumer thread.

    Pass control over to the Consumerthread and continue execution.Loop

    Example: Use a Monitor (6/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    83/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 83

    Example: Use a Monitor (6/8)

    Create the Consumers Run() method.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample() (Osp::Base::Runtime::Monitor)

    Consumer::Run(void)

    {

    result r;

    // Begin critical region

    r = __pMonitor->Enter();

    // Notify to producer threadr = __pMonitor->Notify();

    // Wait for notification

    r = __pMonitor->Wait();

    while (!IsFailed(r))

    {

    //See next page for loop details

    }// Exit monitor

    r = __pMonitor->Exit();

    return null;

    CATCH2:

    __pMonitor->Exit();

    return null;

    }

    a

    b

    d

    c

    3. In the Consumers Run()method (similarly to Step 2):a) Enter() the monitor.

    This marks the start of the criticalsection where the lock is obtained.

    b) Pass control back to theProducer (tell it Consumer hasstarted).The entire process relies on boththreads, so you must ensure thatboth threads are running. You dothis by waiting in the Producerthread and calling Notify() atthe beginning of the Consumerthread.

    c) Loop.This is where you do all of theheavy-lifting for the Consumer.That is, this is the job or taskthat you want to perform.

    d) Exit() the monitor.This marks the end of the critical

    section where the lock is released.

    Example: Use a Monitor (7/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    84/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 84

    Example: Use a Monitor (7/8)

    Create the Consumers loop.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    During Step 3c, in the Consumers Run() method:The loop in the Consumer thread only reads the shared resource(__pShared) and waits.while (!IsFailed(r))

    {

    // Notify producer thread

    r = __pMonitor->Notify();

    if (*__pShared == 5) break;

    // Wait for notificationr = __pMonitor->Wait();

    }

    Pause for the Producer thread.

    Pass control over to the Producer

    thread and continue execution.Loop

    Example: Use a Monitor (8/8)

  • 8/3/2019 Bada Tutorial - Fundamentals

    85/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 85

    Example: Use a Monitor (8/8)

    Create the Producer and Consumer.

    Open \\Examples\Fundamentals\src\RuntimeExample.cpp, ThreadExample()(Osp::Base::Runtime::Monitor)

    4. Create the Producer:

    5. Create the Consumer:

    Producer::Producer(int* pShared, Monitor* pMonitor): __pShared(pShared),

    __pMonitor(pMonitor)

    {

    }

    Consumer::Consumer(int* pShared, Ptr pMonitor)

    : __pShared(pShared),

    __pMonitor(pMonitor)

    {

    }

    Threading

  • 8/3/2019 Bada Tutorial - Fundamentals

    86/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 86

    Threading

    The thread is the basic unit of flow control inside a program.

    It is a single, sequential execution of code inside a program. Multiple threads imply multiple, concurrent lines of execution.

    Process A

    Thread 1

    Thread 2

    ...

    Thread n

    Process B

    Thread 1

    Thread 2

    ...

    Thread n

    Starting a new process

    Starting a new thread

    Thread-safety

  • 8/3/2019 Bada Tutorial - Fundamentals

    87/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 87

    Thread safety

    Since threads can simultaneously use the same resources,

    these shared resources can fall into an inconsistent state. To prevent this, access to shared resources must be guaranteed to

    be mutually exclusive. That is, when one thread is using a resource,no other thread may access it.

    Resources that are categorized as thread-safe can be safely used

    by multiple threads without fear of falling into an inconsistent state. Static resources are most often thread-safe.

    Instances are most often not thread-safe.

    For example:

    Osp::Base::Utility::Math::Sin(x) is thread-safe. The value that

    Sin() returns is only dependent on the parameters. Osp::Base::UuId::Equals(obj) is not thread-safe. The value returned

    by Equals() is dependent on the UuId instances, and the expected return

    value can change if another thread changes the value of the instanceof the UuId object.

    Thread Types

  • 8/3/2019 Bada Tutorial - Fundamentals

    88/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 88

    Thread Types

    Event-driven threads:

    Run event-loops internally. Can use asynchronous calls.

    Worker threads:

    Execute the main body of the thread and exit.

    Cannot use asynchronous calls because worker threads do not

    run event-loops.

    Thread Programming (1/6)

  • 8/3/2019 Bada Tutorial - Fundamentals

    89/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 89

    Thread Programming (1/6)

    Threading can be done in 2 ways:

    a) Define a new class and inherit from Thread: Implement any or all of Threads 3 virtual

    methods: OnStart()

    Run()

    OnStop()

    You can use the default implementation of theRun() method for event-driven threads. (Thatis, you do not need to implement IRunnable.)

    b) Define an IRunnable object and pass it to

    a thread instance:

    Threads execute the Run() method in anIrunnable implementation.

    You can execute any IRunnable object bypassing it to a thread.

    class MyThread:

    public Thread {

    //...

    }

    class MyRunnable:

    public IRunnable,

    public Object{//...

    }

    Thread Programming (2/6)

  • 8/3/2019 Bada Tutorial - Fundamentals

    90/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 90

    Thread Programming (2/6)

    Where worker threads run in a linear fashion, event-driven threads,

    as their name implies, run based on events and loop until theyreceive an event notification to stop.

    Run untilexit event

    OnStart()

    OnStop()

    Event-driven thread

    Run()

    OnStart()

    OnStop()

    Worker thread

    Runslinea

    rly

    Main body executioncontinues its event-loop until it receivesan exit event

    notification to stop.

    Main body ofexecutionfor thread.

    Threadsexit here.

    Thread Programming (3/6)

  • 8/3/2019 Bada Tutorial - Fundamentals

    91/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 91

    Thread Programming (3/6)

    The following example shows

    a worker thread where an instance(pTask) of an IRunnableimplementation (CMyTask) ispassed to a Thread instance(pThread).

    CMyTask* pTask = new Task;Thread* pThread = new Thread;

    pThread->Construct(*pTask);

    pThread->Start();

    delete pThread;

    delete pTask;

    class CMyTask :

    public IRunnable,

    public Object{public:

    CMyTask(void);

    ~CMyTask(void);public:

    void* Run(void);

    }

    CMyTask::CMyTask(void)

    {

    // ...

    }~CMyTask::CMyTask(void)

    {

    // ...

    }

    void* Run(void)

    {

    // ...}

    Thread Programming (4/6)

  • 8/3/2019 Bada Tutorial - Fundamentals

    92/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 92

    Thread Programming (4/6)

    The following example shows

    how to inherit from Thread tocreate a worker thread.

    CMyWorker inherits from Threadand implements the OnStart(),OnStop(), and Run() methods.

    class CMyWorker :

    public Thread{

    public:

    CMyWorker(void);

    ~CMyWorker(void);result Construct(void);

    public:

    bool OnStart(void);

    void OnStop(void);

    void* Run(void);}

    CMyWork::CMyWorker(void){

    // ...

    }

    ~CMyWorker::CMyWorker(void){

    // ...}

    result CMyWorker::Construct(void)

    { return Thread::Construct(); }

    bool CMyWork::OnStart(void)

    { return true; }

    void CMyWorker::OnStop(void) { }

    Object* CMyWorker:: Run(void)

    { return null; }

    Thread Programming (5/6)

  • 8/3/2019 Bada Tutorial - Fundamentals

    93/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 93

    Thread Programming (5/6)

    The following example demonstrates a timer in an event-driven

    thread. The code immediately below shows the interface. The

    implementation follows immediately after.

    class CTimerThread :

    public ITimerEventListener,

    public Thread

    {public:

    CTimerThread (void);

    ~CTimerThread (void);result Construct(void);

    public:

    bool OnStart(void);void OnStop(void);

    public:void OnTimerExpired(Timer& timer);

    private:

    Timer* __pTimer;}

    CTimerThread::CTimerThread(void)

    :__pTimer(null)

    {

    }

    ~CTimerThread::CTimerThread(void)

    {}

    Thread Programming (6/6)

  • 8/3/2019 Bada Tutorial - Fundamentals

    94/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 94

    Thread Programming (6/6)

    This example shows

    the implementationfor a timer thatresets every 60seconds.

    result CTimerThread::Construct(void)

    {result r = E_SUCCESS;r = Thread::Construct(THREAD_TYPE_EVENT_DRIVEN);

    }

    void CTimerThread::OnTimerExpired(Timer& timer)

    {

    __pTimer->Start(60*1000);

    }

    result CTimerThread::OnStart(void)

    {

    __pTimer = new Timer;__pTimer->Construct(*this);

    __pTimer->Start(60*1000);

    return true;}

    void CTimerThread::OnStop(void)

    {__pTimer->Cancel();

    delete __pTimer;

    }

    Review

  • 8/3/2019 Bada Tutorial - Fundamentals

    95/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 95

    Review

    1. How can you set a timer to fire every 5 seconds?

    2. What is the main difference between a worker thread and anevent-driven thread?

    3. What are the 3 basic objects you can use for threadsynchronization.

    4. What do the Enter() and Exit() methods of a monitor mark?

    Answers

  • 8/3/2019 Bada Tutorial - Fundamentals

    96/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 96

    Answers

    1. Reset the timer in its OnTimerExpired() method.

    2. Worker threads run linearly from start to finish where even-driventhreads loop internally. In other words, the main body of executionfor an event-driven thread continues its event-loop until it receivesan exit event notification to stop. Also, because event-driventhreads use events, they, unlike worker threads, can also use

    asynchronous calls.3. Mutexes, semaphores, and monitors.

    4. They mark the beginning and end of a critical section of code.

  • 8/3/2019 Bada Tutorial - Fundamentals

    97/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 97Version 1.0b1Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    Utility

    Contents

  • 8/3/2019 Bada Tutorial - Fundamentals

    98/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 98

    Contents

    Essential Classes and Relationships

    Relationships between Classes Overview

    Math

    Example: Get the Area of a Circle

    StringTokenizer

    Example: Split a String into Tokens

    StringUtil

    Example: Convert a String

    Uri

    Example: Resolve a URI FAQ

    Review

    Answers

    Essential Classes and Relationships

  • 8/3/2019 Bada Tutorial - Fundamentals

    99/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 99

    sse t a C asses a d e at o s ps

    Feature Provided by

    Wraps the native math libraries. Math

    Splits strings at specified delimiters. StringTokenizer

    Converts between strings and McharBuffers and UTF-8ByteBuffers.

    StringUtil

    Facilitates building and analyzing URIs. Uri

    Base::Object

    Math StringTokenizerStringUtil Uri

    Overview

  • 8/3/2019 Bada Tutorial - Fundamentals

    100/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 100

    The Utility namespace contains 4 useful utility classes:

    Math, StringTokenizer, StringUtil, and Uri. The Math class contains mathematical functions, such as a sine,

    absolute value, ceiling, floor, logarithm, and exponent functions.

    You can split strings at delimiters with the StringTokenizer class.

    You can convert strings to and from mchar buffers and UTF-8 bytebuffers with the StringUtil class.

    You can create and analyze URIs with the Uri class.

    Math

  • 8/3/2019 Bada Tutorial - Fundamentals

    101/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 101

    The Math class wraps the native math library.

    double value1 = 2.0;

    double value2 = Math::GetPi(); // 3.141592...

    double minValue = Math::Min(value1, value2); // 2.0

    Mathematical Functions

    Abs() Ceiling() Floor() Log10() Rand() Sqrt()

    Acos() Cos() GetE() Max() Round() Srand()

    Asin() Cosh() GetPi() Min() Sin() Tan()

    Atan() Exp() Log() Pow() Sinh() Tanh()

    Example: Get the Area of a Circle

  • 8/3/2019 Bada Tutorial - Fundamentals

    102/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 102

    p

    Get the area of a circle.

    Open \\Examples\Fundamentals\src\UtilityExample.cpp, MathExample()

    1. Get the area by multiplying by the radius squared (r2):Math::GetPi()

    Math::Pow(radius, 2)

    StringTokenizer

  • 8/3/2019 Bada Tutorial - Fundamentals

    103/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 103

    g

    You can use StringTokenizer to cut strings into tokens and

    count them. If a delimiter is not defined, then the default delimiters are used.

    Default delimiters: space, tab, newline, carriage return, and form feed.

    : Space (0x20)

    \t: Tab (0x09)

    \n: New line (0x0A) \r: Carriage return (0X0D)

    \f: Form feed (0x0C)

    String str(Lbada Sample code);

    StringTokenizer st(str);

    String token;

    st.GetNextToken(token); // badast.GetNextToken(token); // Sample

    Example: Split a String into Tokens

  • 8/3/2019 Bada Tutorial - Fundamentals

    104/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 104

    p p g

    Use the StringTokenizer class to split a string into tokens.

    Open \\Examples\Fundamentals\src\UtilityExample.cpp, StringTokenizerExample()

    1. Create a sample string instance.

    2. Create a StringTokenizerwith a string and a delimeter:

    StringTokenizer::StringTokenizer()3. Check if there are more tokens. If not, go to step 6:

    StringTokenizer::HasMoreTokens()

    4. Get the next token:StringTokenizer::GetNextToken()

    5. Go to step 2.

    6. End.

  • 8/3/2019 Bada Tutorial - Fundamentals

    105/158

    Example: Convert a String

  • 8/3/2019 Bada Tutorial - Fundamentals

    106/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 106

    p g

    Convert a String into an McharBuffer.

    Open \\Examples\Fundamentals\src\UtilityExample.cpp, StringUtilExample()

    1. Create a sample String.

    2. Convert the String to an McharBuffer:

    StringUtil::StringToMbN(string)3. Get the length of the string in the McharBuffer:

    StringUtil::GetStringLengthInMb(mcharBuff)

    4. Convert the McharBuffer back to a String:StringUtil::MbToString(mcharBuff, string)

    Uri

  • 8/3/2019 Bada Tutorial - Fundamentals

    107/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 107

    The Uri class represents a Uniform Resource Identifier (URI)

    reference as defined by RFC 2396. It provides methods to access individual components of a URI.

    You can create URIs and access portions or all of a URI withUri methods.

    String uriStr(L"http://www.samsung.com");

    Uri uri;uri.SetUri(uriStr);

    String scheme = uri.GetScheme(); // http

    String host = uri.GetHost(); // www.samsung.com

    Example: Resolve a URI

  • 8/3/2019 Bada Tutorial - Fundamentals

    108/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 108

    p

    Resolve one URI against another URI.

    Open \\Examples\Fundamentals\src\UtilityExample.cpp, UriExample()

    1. Create 2 Uris:Uri::SetUri()

    2. Resolve one Uri against the other:Uri::Resolve()

    3. Get the content of the Uri as a String and check the result:Uri::ToString()

    FAQ

  • 8/3/2019 Bada Tutorial - Fundamentals

    109/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 109

    Why is -1 or zero returned when an McharBuffer is filled with data

    and GetStringLengthInMb() is called? -1 is returned if a null character does not exist between

    the current position of the McharBuffer and its limit.

    0 is returned if the value of the current position ofthe McharBuffer is null. Call Rewind() and SetPosition()

    on the McharBuffer before invokingGetStringLengthInMb() to correctly set its current position.

    Review

  • 8/3/2019 Bada Tutorial - Fundamentals

    110/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 110

    1. What does a StringTokenizer do?

    2. What class is best to create links to web sites?

    Answers

  • 8/3/2019 Bada Tutorial - Fundamentals

    111/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 111

    1. It splits strings on pre-defined characters with the defaults being

    the space, form feed, new line, and tab characters.2. Uri.

  • 8/3/2019 Bada Tutorial - Fundamentals

    112/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 112Version 1.0b1Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    Io

    Contents

  • 8/3/2019 Bada Tutorial - Fundamentals

    113/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 113

    Essential Classes

    Relationships between Classes Overview

    bada File System

    Directory and File

    Example: Navigate a Directory

    Example: Get File Attributes Database

    SQL

    Example: Create a Database and Table

    Example: Run a Query

    Registry Example: Read a Registry Entry

    FAQ

    Review

    Answers

    Essential Classes

  • 8/3/2019 Bada Tutorial - Fundamentals

    114/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 114

    Features Provided by

    Implements basic database features to create, delete, execute SQL commands,

    and perform other common database management tasks.

    Database

    Provides a method for navigating the result of DbStatement. DbEnumerator

    Provides a method for creating and evaluating pre-compiled statement. DbStatement

    Provides methods for working with directories. Directory

    Stores the information of each directory entry. DirEntry

    Provides methods to access DirEntry class and get Directory information. DirEnumerator

    Provides basic file operations, and input and output, such as create, remove,and read and write.

    File

    Provides methods for reading the attributes of file. FileAttributes

    Provides a registry loading and unloading mechanism to every applicationand the entire system.

    Registry

    Relationships between Classes

  • 8/3/2019 Bada Tutorial - Fundamentals

    115/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 115

    Base::Object

    Io::File Io::Directory Io::Registry Io::Database

    Base::Object

    Io::File Io::Directory Io::Registry

    Overview

  • 8/3/2019 Bada Tutorial - Fundamentals

    116/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 116

    The Io namespace resides under the Base namespace,

    and contains input and output classes, such as File, Directory,Databases, and Registry.

    Every Io class has a subsystem handle as its member.

    Io includes the following:

    File operations, such as create, open, save, copy, move, and delete.

    Directory operations, such as create, rename, delete, and read directorycontents.

    Registry operations, such as create, read, and delete name-value pairs.

    Database provides basic methods for managing the bada databasesystem and manipulating database schema.

    bada File System (1/2)

  • 8/3/2019 Bada Tutorial - Fundamentals

    117/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 117

    Every bada application is assigned a private storage area in the file

    system when it is installed. This is the application home directory. There are simple rules regarding file system access:

    Absolute paths are always used in the Io namespace.

    The path delimiter is a single slash (/).

    Applications can only access the following directories:

    Directory Usage Permission Namespace foraccess methods

    Notes

    /HomeHome directory for bada

    applications.

    Read and

    Write

    Io CWD (Current

    Working Directory)

    is not supported.Only absolute

    paths are allowed

    system-wide.

    The file system is

    case-sensitive bydefault. However,

    if the execution

    environment isWIN32, the file

    system is case-

    insensitive.

    /Home/Share

    Used to share data with

    other bada application. It is

    strongly recommended that

    the application should

    remove data in this folder

    as soon as they are not

    needed anymore to save

    system storage.

    Read and

    Write

    /Share/[appid]

    Used to read data for otherbada applications. (The

    shared data application ID

    must be known beforehand.)

    Read-only

    bada File System (2/2)

  • 8/3/2019 Bada Tutorial - Fundamentals

    118/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 118

    Directory Usage Permission Namespace foraccess methods

    Notes

    /Res

    Used to read resource files,

    such as the icon file that was

    shipped with the applicationpackage.

    Read-only Io

    CWD (Current

    Working Directory) is

    not supported. Only

    absolute paths are

    allowed system-wide.

    The file system is

    case-sensitive by

    default. However, if

    the execution

    environment is WIN32,

    the file system iscase-insensitive.

    /Share/AppControl/[appcontrol-name]

    Used to read data provided by

    an app control by its name

    Read-only

    /Media/Images Used to read image data. Read-only Io

    (To manipulate the

    user data storedhere, use the Media

    namespace.)

    /Media/Sounds Used to read sound data.

    /Media/Videos Used to read video data.

    /Media/Themes Used to read theme data.

    /Media/OthersUsed to read additional media

    data.

    /Storagecard/Media/ImagesUsed to read image data in

    external memory.

    /Storagecard/Media/SoundsUsed to read sound data in

    external memory.

    /Storagecard/Media/VideosUsed to read video data in

    external memory.

    /Storagecard/Media/Themes

    Used to read theme data in

    external memory.

    /Storagecard/Media/Others

    Used to read additional media

    data in external memory.

    Directory and File

  • 8/3/2019 Bada Tutorial - Fundamentals

    119/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 119

    Directories and files behave the same as on most common

    file systems. Directories can contain other directories and files.

    DirEnumerator facilitates iterating over directories to get

    information on what directories and files they contain.

    /Directory1

    /Directory2 /Directory3 /Directory4

    Directory1

    Directory2

    Directory3

    Directory4

    sun.gif

    rain.gif

    snow.gif

    DirEnumerator

    Example: Navigate a Directory

  • 8/3/2019 Bada Tutorial - Fundamentals

    120/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 120

    Get a list of files and directories in a specific directory.

    Open \\Examples\Fundamentals\src\IoExample.cpp, DirectoryExample()

    1. Construct a Directory to get the list of specific files in a directory:Directory::Construct(directoryName)

    2. Use an enumerator to read the list of files:

    Directory::ReadN()3. Move the DirEnumerator to the first position:

    DirEnumerator::MoveNext()

    4. Get a DirEntry to retrieve file information:DirEnumerator::GetCurrentDirEntry()

    5. Retrieve the file information through the DirEntry:

    DirEntry::GetName()DirEntry::GetFileSize()DirEntry::IsDirectory()DirEntry::IsReadOnly()...

    6. Move the DirEnumerator to the next position:DirEnumerator::MoveNext()

    7. Repeat steps 4 to 6.

    Example: Get File Attributes

  • 8/3/2019 Bada Tutorial - Fundamentals

    121/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 121

    Get different file attributes from a file.

    Open \\Examples\Fundamentals\src\IoExample.cpp, FileAttributeExample()

    1. Get the FileAttributes:File::GetFileAttributes()

    2. Read the attributes from theFileAttributes

    :GetDateTime()

    GetFileSize()

    GetLastModifiedTime()

    IsDirectory()

    IsHidden()

    IsNomalFile()IsReadOnly()

    IsSystemFile()

    Database

  • 8/3/2019 Bada Tutorial - Fundamentals

    122/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 122

    Database thread-safety is guaranteed with a mutex.

    DbEnumerator facilitates data retrieval and iteration over columns

    in query result sets.

    DbEnumeratorID Name Address

    0 Kevin New York

    1 Julie Boston

    2 Joe New York

    3 Mark New York

    4 Robert Seattle

    5 Moe Boston

    ID Name Address0 Kevin New York

    2 Joe New York

    3 Mark New York

    Database

    Thread #1: Keeps the mutex and uses the database.

    Thread #2: Tries to acquire the mutex to use the database, fails and is queued.

    Mutex Mutex

    Example: Create a Database and Table

  • 8/3/2019 Bada Tutorial - Fundamentals

    123/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 123

    Create a new database with a table.

    Open \\Examples\Fundamentals\src\IoExample.cpp, TableExample()

    1. Construct a new database:Database::Construct(dbFileName, false)

    2. Execute SQL to create a table:Database::ExecuteSql(sql, true)

    Note: You must use bada-compatible SQL.

    Example: Run a Query

  • 8/3/2019 Bada Tutorial - Fundamentals

    124/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 124

    Run a SELECT statement on a table.

    Open \\Examples\Fundamentals\src\IoExample.cpp, QueryExample()

    1. Construct an existing database:Database::Construct(dbFileName, false)

    2. Create a SQL statement to bind variables:Database::CreateStatementN(sql)

    3. Bind data to the SQL:DbStatement::BindString(varIndex,

    string)

    4. Execute the SQL statement:

    Database::ExecuteStatementN()

    5. Move the cursor to the next (first) position:DbEnumerator::MoveNext()

    ID Name Address

    0 Kevin New York

    1 Julie Boston

    2 Joe New York

    3 Mark New York

    4 Robert Seattle

    5 Moe Boston

    Registry

  • 8/3/2019 Bada Tutorial - Fundamentals

    125/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 125

    The Registry has three parts.

    Section is prefixed with a hash symbol (#), and is followed by entries. Entries consist of name-value pairs and are expressed as Name=Value.

    Entry names can be duplicated in different sections.

    Entry names must be unique inside of the same section.

    Entry value can be any of the following types: Integer, Double,Float, String, UuId or Bytebuffer.

    #Section1Name1=1

    Name2=string_value

    Name3=1dda4a68-f063-4b14-abee-9c031f3eb021_msPloc

    #Section2Name2=2

    Example: Read a Registry Entry

  • 8/3/2019 Bada Tutorial - Fundamentals

    126/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 126

    Create a registry section, name-value pair, and read the

    name-value pair. Open \\Examples\Fundamentals\src\IoExample.cpp, RegistryExample()

    1. Construct a new Registry:Registry::Construct(regName, true)

    2. Create a section:Registry::AddSection(secName)

    3. Add a name-value pair to the new section:Registry::AddValue(secName, entryName, value)

    4. Get the value from the section using the entry name:

    Registry::GetValue(secName, entryName, valueOut)

    FAQ

  • 8/3/2019 Bada Tutorial - Fundamentals

    127/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 127

    Does the Database class guarantee mutual exclusivity for multiple

    I/O access to a database file? No. It must be guaranteed by application logic.

    How can I handle text files?

    Samsung bada does not differentiate between text files and other filetypes. This means that bada does not run any translation between CR-LF and LF. (This is the same behavior as Unix and GNU Linux systems.)As a result, you need to understand the following guidelines:

    In terms of opening and creating text files:

    Do not use the b (binary) open mode flag with File::Construct(). (Althoughb open mode is recognized by File::Construct() for the purpose of code

    compatibility, it has no effect on actual file operations.)

    In terms of text I/O:

    Use File::Read (Osp::Base::String &) andFile::Write(Osp::Base::String &), if you want to handle the file as unit

    of text.

    Review

  • 8/3/2019 Bada Tutorial - Fundamentals

    128/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 128

    1. True or false. All directories have children.

    2. True or false. You can use T-SQL or PL/SQL in with the database.3. True or false. Registry names do not need to be unique.

    Answers

  • 8/3/2019 Bada Tutorial - Fundamentals

    129/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 129

    1. False. It is certainly possible to have an empty directory.

    2. False. You must use bada-compatible SQL.3. Trick question. It needs to be qualified. You can have non-unique

    entry names as long as they do not reside in the same Section.You cannot have identical entry names inside the same Section.

  • 8/3/2019 Bada Tutorial - Fundamentals

    130/158

    Copyright 2010 Samsung Electronics Co., Ltd. All rights reserved. 130Version 1.0b1

    Copyright 2010 Samsung Electronics, Co., Ltd. All rights reserved

    System

    Contents

  • 8/3/2019 Bada Tutorial - Fundamentals

    131/158

    Copyright 2010 Samsung Ele