import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class Midlet extends MIDlet implements CommandListener
{
private RecordStore rs = null; // Record store
private Display display; // Reference to Display object
private List menu; // List object reference
private Form writeForm; // Write records screen
private Form readForm; // Read records screen
private Form deleteForm; // Delete records screen
private Form searchForm; // Search records screen
private TextField textName; // Input name
private TextField textPhone; // Input phone
private TextField textIC;
private TextField textCredit;
private TextField textSearch; // Input search
private String movie1;
private String movie2;
private String movie3;
private String movie4;
private String movie5;
private String category1;
private String category2;
private String category3;
private String category4;
private String category5;
private int choiceGroupIndex;
private Command backCommand = new Command("Back", Command.BACK, 1);
private Command deleteCommand = new Command("Delete", Command.EXIT, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command writeCommand = new Command("Write", Command.OK, 1);
private Command findCommand = new Command("Find", Command.OK, 1);
static final String REC_STORE = "db_lab10"; // Name of record store
public Midlet()
{
// create a list menu
menu = new List("DVD Store", Choice.IMPLICIT);
menu.append("List of DVDs", null);
menu.append("Write", null);
menu.append("Read", null);
menu.append("Delete", null);
menu.append("Search", null);
// add an exit command & register command listener for list menu
menu.addCommand(exitCommand);
menu.setCommandListener(this);
}
public void destroyApp(boolean unconditional)
{
// Close record store
closeRecStore();
// Remove the record store
// deleteRecStore();
menu = null;
writeForm = null;
}
public void startApp()
{
// Create the record store
openRecStore();
// Read back the records
// readStream();
// get reference to Display object
display = Display.getDisplay(this);
// set list menu visible
display.setCurrent(menu);
}
public void pauseApp()
{
}
public void commandAction(Command c, Displayable d)
{
Alert alert;
if (d == menu)
{
if (c == List.SELECT_COMMAND)
{
int selectedIndex = menu.getSelectedIndex();
// debugging only
// System.err.println(menu.getString(selectedIndex));
if (menu.getString(selectedIndex).equals("List of DVDs"))
{
// try to dispose of write form first
writeForm = null;
// create a form for write records screen
writeForm = new Form("DVDs");
// create 2 TextFields for write records screen
//movie1
movie1 = "1. Alice in Wonderland, $15.90";
try{
Image alice = Image.createImage("Alice.png");
writeForm.append(movie1);
writeForm.append(alice);
category1 = "Category: Family / Live-Action "
+ "Cast: David Bernal,Leo Bill "
+ "Rated: PG";
writeForm.append(category1);
}catch(IOException e){}
//movie2
movie2 = "2. Chronicles of Narnia, $17.90";
try{
Image chronicles = Image.createImage("Chronicles.png");
writeForm.append(movie2);
writeForm.append(chronicles);
category2 = "Category: Family / Live-Action "
+ "Cast: Ben Barnes,John Bach "
+ "Rated: PG";
writeForm.append(category2);
}catch(IOException e){}
//movie3
movie3 = "3. Despicable Me, $14.90";
try{
Image despicable = Image.createImage("Despicable.png");
writeForm.append(movie3);
writeForm.append(despicable);
category3 = "Category: Family / Animation "
+ "Cast: Will Arnett,Steve Carell "
+ "Rated: PG";
writeForm.append(category3);
}catch(IOException e){}
//movie4
movie4 = "4. High School Musical, $16.90";
try{
Image hsm = Image.createImage("Hsm.png");
writeForm.append(movie4);
writeForm.append(hsm);
category4 = "Category: Family / Romance "
+ "Cast: Zac Efron,Vanessa "
+ "Rated: PG";
writeForm.append(category4);
}catch(IOException e){}
//movie5
movie5 = "5. Transformer, $19.90";
try{
Image transformer = Image.createImage("Transformer.png");
writeForm.append(movie5);
writeForm.append(transformer);
category5 = "Category: Sci-Fi / Fantasy "
+ "Cast: Megan Fox,Michael "
+ "Rated: PG13";
writeForm.append(category5);
}catch(IOException e){}
// add a back command & register command listener for write records screen
writeForm.addCommand(backCommand);
writeForm.addCommand(writeCommand);
writeForm.setCommandListener(this);
// set write form visible
display.setCurrent(writeForm);
}
else if(menu.getString(selectedIndex).equals("Write"))
{
// try to dispose of write form first
writeForm = null;
// create a form for write records screen
writeForm = new Form("Write Records");
// create 2 TextFields for write records screen
textName = new TextField("Name:", "", 10, TextField.ANY);
textPhone = new TextField("Mobile no. :", "", 8, TextField.NUMERIC);
textIC = new TextField("IC no. :", "", 9, TextField.ANY);
textCredit = new TextField("Credit no. :", "", 8, TextField.NUMERIC);
// append 2 TextFields for write records screen
writeForm.append(textName);
writeForm.append(textPhone);
writeForm.append(textIC);
writeForm.append(textCredit);
//ChoiceGroup for method of payment
//ChoiceGroup choices = new ChoiceGroup ("Method of payment:",Choice.EXCLUSIVE);
//choices.append("Visa",null);
//choices.append("Master Card",null);
//writeForm.append(choices);
// add a back command & register command listener for write records screen
writeForm.addCommand(backCommand);
writeForm.addCommand(writeCommand);
writeForm.setCommandListener(this);
// set write form visible
display.setCurrent(writeForm);
}
else if (menu.getString(selectedIndex).equals("Read"))
{
// try to dispose of read form first
readForm = null;
// create a form for read records screen
readForm = new Form("Read Records");
// add a back command & register command listener for read records screen
readForm.addCommand(backCommand);
readForm.setCommandListener(this);
// print out the results to the screen
int count = readRecordStore(readForm);
if (count == 0)
{
alert = new Alert("Info", "No records are found.", null, AlertType.INFO);
display.setCurrent(alert, menu);
}
else
{
// set read form visible
display.setCurrent(readForm);
}
}
else if (menu.getString(selectedIndex).equals("Delete"))
{
// try to dispose of delete form first
deleteForm = null;
// create a form for delete records screen
deleteForm = new Form("Delete Records");
// create 2 TextFields for delete records screen
textName = new TextField("Name:", "", 10, TextField.ANY);
textPhone = new TextField("Mobile no. :", "", 8, TextField.NUMERIC);
textIC = new TextField("IC no. :", "", 9, TextField.ANY);
textCredit = new TextField("Credit no. :", "", 8, TextField.NUMERIC);
// append 2 TextFields for delete records screen
deleteForm.append(textName);
deleteForm.append(textPhone);
deleteForm.append(textIC);
deleteForm.append(textCredit);
deleteForm.delete(choiceGroupIndex);
// add a back command & register command listener for delete records screen
deleteForm.addCommand(deleteCommand);
deleteForm.addCommand(backCommand);
deleteForm.setCommandListener(this);
// set delete form visible
display.setCurrent(deleteForm);
}
else if (menu.getString(selectedIndex).equals("Search"))
{
// try to dispose of search form first
searchForm = null;
// create a form for search records screen
searchForm = new Form("Search Records");
// create 1 TextField for search records screen
textSearch = new TextField("Find:", "", 10, TextField.ANY);
// append 2 TextFields for search records screen
searchForm.append(textSearch);
// add a back command & register command listener for search records screen
searchForm.addCommand(findCommand);
searchForm.addCommand(backCommand);
searchForm.setCommandListener(this);
// set search form visible
display.setCurrent(searchForm);
}
}
if (c == exitCommand)
{
destroyApp(true);
notifyDestroyed();
}
}
// Write record form
else if (d == writeForm)
{
if (c == backCommand)
{
// set menu form visible
display.setCurrent(menu);
}
else if (c == writeCommand)
{
// Error input
if (textName.getString().equals("") && textPhone.getString().equals("") && textIC.getString().equals("") && textCredit.getString().equals(""))
{
alert = new Alert("Error", "Please fill in the blanks.", null, AlertType.ERROR);
display.setCurrent(alert, writeForm);
return;
}
else if (textName.getString().equals(""))
{
alert = new Alert("Error", "The name is blank.", null, AlertType.ERROR);
display.setCurrent(alert, writeForm);
return;
}
else if (textPhone.getString().equals(""))
{
alert = new Alert("Error", "The phone no. is blank.", null, AlertType.ERROR);
display.setCurrent(alert, writeForm);
return;
}
else if (textIC.getString().equals(""))
{
alert = new Alert("Error", "The IC no. is blank.", null, AlertType.ERROR);
display.setCurrent(alert, writeForm);
return;
}
else if (textCredit.getString().equals(""))
{
alert = new Alert("Error", "The Credit no. is blank.", null, AlertType.ERROR);
display.setCurrent(alert, writeForm);
return;
}
// Write a series of records
writeRecordStore(textName.getString(), Integer.parseInt(textPhone.getString()), textIC.getString(), Integer.parseInt(textCredit.getString()));
alert = new Alert("Info", "Record written.", null, AlertType.INFO);
// set menu form visible
display.setCurrent(alert, menu);
}
}
// Read record form
else if (d == readForm)
{
if (c == backCommand)
{
// set menu form visible
display.setCurrent(menu);
}
}
// Delete record form
else if (d == deleteForm)
{
if (c == backCommand)
{
// set menu form visible
display.setCurrent(menu);
}
else if (c == deleteCommand)
{
// Error input
if (textName.getString().equals("") && textPhone.getString().equals("") && textIC.getString().equals("") && textCredit.getString().equals(""))
{
alert = new Alert("Error", "Please fill in the blanks.", null, AlertType.ERROR);
display.setCurrent(alert, deleteForm);
return;
}
int no = deleteRecordStore(textName.getString(), textPhone.getString(), textIC.getString(), textCredit.getString());
alert = null;
if (no > 0)
alert = new Alert("Info", no + " records deleted.", null, AlertType.INFO);
else if (!textName.getString().equals("") && !textPhone.getString().equals("") && !textIC.getString().equals(""))
alert = new Alert("Error", textName.getString() + ", " + textPhone.getString() +", " + textIC.getString() + " not found.", null, AlertType.ERROR);
else if (!textName.getString().equals(""))
alert = new Alert("Error", textName.getString() + " not found.", null, AlertType.ERROR);
else if (!textPhone.getString().equals(""))
alert = new Alert("Error", textPhone.getString() + " not found.", null, AlertType.ERROR);
else if (!textIC.getString().equals(""))
alert = new Alert("Error", textIC.getString() + " not found.", null, AlertType.ERROR);
else if (!textCredit.getString().equals(""))
alert = new Alert("Error", textCredit.getString() + " not found.", null, AlertType.ERROR);
// set menu form visible
display.setCurrent(alert, menu);
}
}
else if (d == searchForm)
{
if (c == backCommand)
{
// set menu form visible
display.setCurrent(menu);
}
else if (c == findCommand)
{
// Error input
if (textSearch.getString().equals(""))
{
alert = new Alert("Error", "The name is blank.", null, AlertType.ERROR);
display.setCurrent(alert, searchForm);
return;
}
int i = searchRecordStore(textSearch.getString());
// cannot find any matching records
if (i <= 0)
{
alert = new Alert("Error", textSearch.getString() + " not found.", null, AlertType.ERROR);
display.setCurrent(alert, searchForm);
return;
}
// set menu form visible
// display.setCurrent(alert, menu);
}
}
} //commandAction
public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true);
}
catch (Exception e)
{
db("openRecStore(): " + e.toString());
}
}
public void closeRecStore()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
db("closeRecStore(): " + e.toString());
}
}
public void deleteRecStore()
{
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore(REC_STORE);
}
catch (Exception e)
{
db("deleteRecStore(): " + e.toString());
}
}
}
// Write to record store using streams.
public void writeRecordStore(String nData, int pData, String iData, int cData)
{
try
{
// Write data into an internal byte array
ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();
// Write Java data types into the above byte array
DataOutputStream strmDataType = new DataOutputStream(strmBytes);
byte[] record;
// Write Java data types
strmDataType.writeUTF(nData);
strmDataType.writeInt(pData);
strmDataType.writeUTF(iData);
strmDataType.writeInt(cData);
// Clear any buffered data
strmDataType.flush();
// Get stream data into byte array and write record
record = strmBytes.toByteArray();
rs.addRecord(record, 0, record.length);
// Toss any data in the internal array so writes
// starts at beginning (of the internal array)
strmBytes.reset();
strmBytes.close();
strmDataType.close();
}
catch (Exception e)
{
db("writeRecordStore(): " + e.toString());
}
} //writeRecordStore
// Read from the record store using streams
public int readRecordStore(Form readForm)
{
StringItem si;
try
{
// Careful: Make sure this is big enough!
// Better yet, test and reallocate if necessary
byte[] recData = new byte[50];
// Read from the specified byte array
ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
// Read Java data types from the above byte array
DataInputStream strmDataType = new DataInputStream(strmBytes);
if (rs.getNumRecords() > 0)
{
int i = 1;
ComparatorString comp = new ComparatorString();
RecordEnumeration re = rs.enumerateRecords(null, comp, false);
while (re.hasNextElement())
{
i = re.nextRecordId();
// Get data into the byte array
rs.getRecord(i, recData, 0);
// Read back the data types
si = new StringItem("", "Record no: " + i + "\n");
readForm.append(si);
si = new StringItem("", "Name: " + strmDataType.readUTF() + "\n");
readForm.append(si);
si = new StringItem("", "Mobile no. : " + strmDataType.readInt() + "\n");
readForm.append(si);
si = new StringItem("", "IC no. : " + strmDataType.readInt() + "\n");
readForm.append(si);
si = new StringItem("", "Credit no. : " + strmDataType.readInt() + "\n");
readForm.append(si);
si = new StringItem("", "---------------------------\n");
readForm.append(si);
// Reset so read starts at beginning of array
strmBytes.reset();
}
comp.compareStringClose();
// Free enumerator
re.destroy();
}
strmBytes.close();
strmDataType.close();
return (rs.getNumRecords());
}
catch (Exception e)
{
db("readRecordStore(): " + e.toString());
}
return 0;
} //readRecordStore
// Delete the record from the record store
public int deleteRecordStore(String sName, String sPhone, String sIC, String sCredit)
{
String name;
int phone;
String ic;
int credit;
int count = 0;
boolean delete_rec;
try
{
// Careful: Make sure this is big enough!
// Better yet, test and reallocate if necessary
byte[] recData = new byte[50];
// Read from the specified byte array
ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
// Read Java data types from the above byte array
DataInputStream strmDataType = new DataInputStream(strmBytes);
if (rs.getNumRecords() > 0)
{
RecordEnumeration re = rs.enumerateRecords(null, null, true);
while (re.hasNextElement())
{
int i = re.nextRecordId();
// Get data into the byte array
rs.getRecord(i, recData, 0);
name = strmDataType.readUTF();
phone = strmDataType.readInt();
ic = strmDataType.readUTF();
credit = strmDataType.readInt();
delete_rec = false;
if (!sName.equals("") && !sPhone.equals("") && !sIC.equals("") && !sCredit.equals(""))
{
if (name.equals(sName) && phone == Integer.parseInt(sPhone) && ic.equals(sIC) && credit == Integer.parseInt(sCredit))
delete_rec = true;
}
else if (!sName.equals(""))
{
if (name.equals(sName))
delete_rec = true;
}
else if (!sPhone.equals(""))
{
if (phone == Integer.parseInt(sPhone))
delete_rec = true;
}
else if (!sIC.equals(""))
{
if (ic.equals(sIC))
delete_rec = true;
}
else if (!sCredit.equals(""))
{
if (credit == Integer.parseInt(sCredit))
delete_rec = true;
}
if (delete_rec == true)
{
try
{
rs.deleteRecord(i);
count++;
}
catch (Exception e)
{
db("deleteRecordStore_1(): " + e.toString());
}
}
// Reset so read starts at beginning of array
strmBytes.reset();
}
// reconstruct the enumeration
re.rebuild();
}
strmBytes.close();
strmDataType.close();
}
catch (Exception e)
{
db("deleteRecordStore_2(): " + e.toString());
}
return count;
} //deleteRecordStore
/*
* Search using enumerator and record filter
*/
private int searchRecordStore(String search_name)
{
String name;
int phone;
String ic;
int credit;
StringItem si; // The matching text, if any
int count = 0;
try
{
// Record store is not empty
if (rs.getNumRecords() > 0)
{
// Setup the search filter with the user
// requested text
SearchFilter search = new SearchFilter(search_name);
RecordEnumeration re = rs.enumerateRecords(search, null, false);
// A match was found using the filter
while (re.hasNextElement())
{
// Read from the specified byte array
ByteArrayInputStream strmBytes = new ByteArrayInputStream(re.nextRecord());
// Read Java data types from the above byte array
DataInputStream strmDataType = new DataInputStream(strmBytes);
name = strmDataType.readUTF();
phone = strmDataType.readInt();
ic = strmDataType.readUTF();
credit = strmDataType.readInt();
count++;
// Show matching result in stringItem component
si = new StringItem("", "Mobile no: " + phone + "\n");
searchForm.append(si);
strmBytes.close(); // Close stream
strmDataType.close(); // Close stream
}
search.searchFilterClose(); // Close record filter
re.destroy(); // Free enumerator
// search records found
if (count > 0)
{
si = new StringItem("", count + " records found.\n");
searchForm.append(si);
}
return count;
}
else
return -1;
}
catch (Exception e)
{
db("searchRecordStore(): " + e.toString());
}
return -1;
} //searchRecordStore
/*
* Simple message to console for debug/errors
* When used with Exceptions we should handle the
* error in a more appropriate manner.
*/
public void db(String str)
{
System.err.println("Msg: " + str);
}
/*
* Compares two strings to determine sort order
* Each records passed in contains multiple Java data
* types - use only the String data for sorting
*/
class ComparatorString implements RecordComparator
{
private byte[] recData = new byte[10];
// Read from a specified byte array
private ByteArrayInputStream strmBytes = null;
// Read Java data types from the above byte array
private DataInputStream strmDataType = null;
public void compareStringClose()
{
try
{
if (strmBytes != null)
strmBytes.close();
if (strmDataType != null)
strmDataType.close();
}
catch (Exception e)
{
}
}
public int compare(byte[] rec1, byte[] rec2)
{
String str1, str2;
try
{
// If either record is larger than our buffer,
// reallocate
int maxsize = Math.max(rec1.length, rec2.length);
if (maxsize > recData.length)
recData = new byte[maxsize];
// Read record #1
// Only need one read because the string to
// sort on is the first "field" in the record
strmBytes = new ByteArrayInputStream(rec1);
strmDataType = new DataInputStream(strmBytes);
str1 = strmDataType.readUTF();
// Read record #2
strmBytes = new ByteArrayInputStream(rec2);
strmDataType = new DataInputStream(strmBytes);
str2 = strmDataType.readUTF();
// Compare record #1 and #2
int result = str1.compareTo(str2);
if (result == 0)
return RecordComparator.EQUIVALENT;
else if (result < 0)
return RecordComparator.PRECEDES;
else
return RecordComparator.FOLLOWS;
}
catch (Exception e)
{
return RecordComparator.EQUIVALENT;
}
}
} //ComparatorString
/*
* Search for text within a record
* Each records passed in contains multiple Java data
* types (String and integer)
*/
class SearchFilter implements RecordFilter
{
private String searchText = null;
// Read from a specified byte array
private ByteArrayInputStream strmBytes = null;
// Read Java data types from the above byte array
private DataInputStream strmDataType = null;
public SearchFilter(String searchText)
{
// This is the text to search for
this.searchText = searchText.toLowerCase();
}
// Cleanup
public void searchFilterClose()
{
try
{
if (strmBytes != null)
strmBytes.close();
if (strmDataType != null)
strmDataType.close();
}
catch (Exception e)
{
}
}
public boolean matches(byte[] candidate)
{
String str = null;
try
{
strmBytes = new ByteArrayInputStream(candidate);
strmDataType = new DataInputStream(strmBytes);
// Although 3 pieces of data were written to
// the record (String and integer)
// we only need one read because the string to
// search is the first "field" in the record
str = strmDataType.readUTF().toLowerCase();
}
catch (Exception e)
{
return false;
}
// Look for a match
if (str != null && str.indexOf(searchText) != -1)
return true;
else
return false;
} //matches
} //StringSearch
} //RMSPhoneBookMIDlet
How to read data from choice group?
Page 1 of 10 Replies - 381 Views - Last Post: 30 January 2011 - 12:58 AM
#1
How to read data from choice group?
Posted 30 January 2011 - 12:58 AM
Hi, I have no idea how to read the data from choice group and show it in my read form. I've commented the choice group so as to let the codes debug with error free. Here are my working codes. Can anybody teach me how to read the choosen choice from choice group and show it in my read form?
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote


|