J2ME- Database file
A Database file is a a special file that you can store records or data and can retrieve those records for later uses. Data stored in the database file are still available for the program although it quits.
To create a database to store your data for uses in your application, you can use RecordStore object that exists in the javax.microedition.rms package. With the RecordStore object, each record of the database file is stored with a unique number(primary key). The number is assigned automatically by the system when the record is added to the database file.
-Create a database file
To create a database file, you need to use the openRecordStore(file_name, create_if_not_exist) method of the RecordStore object. The file_name is the name of the database file. The value of the create_if_not_exist can be true or false. If the value is true, the database file will be created for you if it does not exist.
This statement will create a RecordStore object named db if this database does not exist. This database file is stored physically in the appdb folder. In my machine this file is stored in C:\Users\Dcc\j2mewtk\2.5.2\appdb\DefaultColorPhone.
-Add records to the database file
To add records to the database file, you can use the addRecord(data_in_byte, index, length) method of the RecordStore object. This method returns the record key number of the new added record.
The first argument indicates that the data needs to be converted in byte before passing to the function. The index argument is the index of the first relevant byte for this record into the data buffer. The length argument specifies the length of data bytes to be added to the database file.
This statement adds data record to the db database. The key number of the record is stored in num variable.
-Delete the record from the database file
If a record in the database file is no longer being used, you can delete it by using deleteRecord(record_number) method. This method does not return a value.
This statement will delete the record with the key num.
-Read the record from the database file
Reading the record from the database is also a simple process. You can use getRecord(record_number,copy_byte,index) method of the RecordStore object. This method returns the length(in byte) of the copied record.
The first argument is the record key number of the record that you want to read. The copy_byte argment is the array of bytes that will be used to store the record read from the database file. The last argument is the index to the buffer to start copy the record.
This statement will read the first record and store this record in the copy_data array and the length of the copied record is assigned to the len variable.
In the example code below, we create a simple image viewer application that the user can view a selected image and add an image file to the database.