Refreshing Table Adapter screen : Blackberry - blackberry

Is there any way to refresh Table Adapter Screen on button click.
If i m callling table method again on button click then it is adding a new table adapter screen below the old on.....I s there any way to refresh the existing screen.The button is deleting elements from table after which i want to refresh it.
public static void richlistshow(){
int ik = target_list.size()-1;
while(ik > 0 )
{
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
City aCity = (City)target_list.elementAt(ik);
String modelNumber = aCity.get_city_name().toString();
String modelName = " X ";
//String ne = String.valueOf(ik);
String date_time = " Date-Time";
Object[] row = {modelName, modelNumber,date_time,logoBitmap};
_tableModel.addRow(row);
ik--;
}
TableView tableView = new TableView(_tableModel);
tableView.setDataTemplateFocus(BackgroundFactory.createLinearGradientBackground(Color.YELLOWGREEN, Color.LIMEGREEN, Color.SEAGREEN, Color.SANDYBROWN));
TableController tableController = new TableController(_tableModel, tableView);
tableController.setFocusPolicy(TableController.ROW_FOCUS);
tableView.setController(tableController);
// Specify a simple data template for displaying 3 columns
DataTemplate dataTemplate = new DataTemplate(tableView, NUM_ROWS, NUM_COLUMNS)
{
public Field[] getDataFields(int modelRowIndex)
{
//final int i =modelRowIndex;
Object[] data = (Object[]) (_tableModel.getRow(modelRowIndex));
final String cname = (String)data[1];
/****** Declaring button for deletion of record from database ******/
ButtonField delete =new ButtonField("X",ButtonField.CONSUME_CLICK);
/******* Setting change listener and defining field change within *******/
delete.setChangeListener(new FieldChangeListener() {
/******* defining what should happen when button is clicked ********/
public void fieldChanged(Field field, int context) {
DatabaseHandler delete_row = new DatabaseHandler();
delete_row.deletetarget(cname);
/****calling function to retrieve values from the databasse table.***/
delete_row.retrieveTarget();
/****************calling method again to show the updated values*************/
richlistshow();//for showing refreshed data after deletion of a record
}
});
Field[] fields = {delete, new LabelField((String) data[1]), new LabelField((String) data[2]),new BitmapField((Bitmap)data[3])};
return fields;
}
};
dataTemplate.useFixedHeight(true);
// Define regions and row height
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT));
for(int i = 0; i < NUM_COLUMNS; i++)
{
dataTemplate.createRegion(new XYRect(i, 0, 1, 1));
dataTemplate.setColumnProperties(i, new TemplateColumnProperties(Display.getWidth() / NUM_COLUMNS));
}
// Apply the template to the view
tableView.setDataTemplate(dataTemplate);
mainManager.add(tableView);
}
public final static class MyCity
{
private String _name;
private String _datetime;
private String _button;
private Bitmap _bitmap;
MyCity(String name, String datetime, String button, Bitmap bitmap)
{
_name = name;
_datetime = datetime;
_button = button;
_bitmap = bitmap;
}
public String getName()
{
return _name;
}
public String getDatetime()
{
return _datetime;
}
public String getButton()
{
return _button;
}
public Bitmap getBitmap()
{
return _bitmap;
}
}
/****************TABLE CONTROLLER CLASS ******************/
private class CityTableModelAdapter extends TableModelAdapter
{
public int getNumberOfRows()
{
return _cities.size();
}
public int getNumberOfColumns()
{
return NUM_COLUMNS;
}
protected boolean doAddRow(Object row)
{
Object[] arrayRow = (Object[]) row;
System.out.println("! : "+arrayRow[0]+" #: "+arrayRow[1]+" #: "+arrayRow[2]);
_cities.addElement(new MyCity((String) arrayRow[0], (String) arrayRow[1], (String) arrayRow[2], (Bitmap) arrayRow[3]));
return true;
}
protected Object doGetRow(int index)
{
MyCity mycity = (MyCity) _cities.elementAt(index);
Object[] row = {mycity.getName(),mycity.getDatetime(),mycity.getButton(),mycity.getBitmap()};
return row;
}
}

Related

How to select combobox by id or value using with BeanItemContainer?

I am using BeanItemContainer for my comboboxes to satisfy key-value pairs.
#SuppressWarnings("serial")
public class ComboBoxItem implements Serializable {
private String id;
private String description;
public ComboBoxItem(final String id, final String description) {
this.id = id;
this.description = description;
}
public final void setId(final String id) {
this.id = id;
}
public final void setDescription(final String description) {
this.description = description;
}
public final String getId() {
return id;
}
public final String getDescription() {
return description;
}
}
I created a sample combobox as below
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
lstAuctionDateList.add(new ComboBoxItem("all", "All"));
BeanItemContainer<ComboBoxItem> auctionDateItems = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class,
lstAuctionDateList);
final ComboBox cbAuctionDate = new ComboBox("Auction Date", auctionDateItems);
cbAuctionDate.addStyleName("small");
cbAuctionDate.setNullSelectionAllowed(false);
cbAuctionDate.setTextInputAllowed(false);
cbAuctionDate.setItemCaptionPropertyId("description");
cbAuctionDate.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
if (cbAuctionDate.getValue() != null) {
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getId());
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getDescription());
}
}
});
It is fine but I can't select any of combobox items by using below codes
cbAuctionDate.select("all");
cbAuctionDate.select("All");
cbAuctionDate.setValue("all");
cbAuctionDate.setValue("All");
What am I wrong ? How can I select my comboxes by programmatically ?
when using a (bean) container and adding items, the identity of the item itself is used as the itemId in the container. E.g. cbActionDate.select(lstAuctionDateList[0]) should work.
You either have yo make your objects immutable or use ways to tell the container, what it has to use for an id (E.g. setBeanIdProperty("id") or setBeanIdResolver).
Making the object immutable should be easy right now (make the class and the private attributes final, drop the setters and let your IDE generate equals and hashCode for you)
You don't need the cbAuctionDate.addItem("All") call, you already have such a item in your collection
I would try it that way:
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
ComboBoxItem allItems= new ComboBoxItem("all", "All");
lstAuctionDateList.add(allItems);
....
...
cbAuctionDate.select(allItems);
Now I created custom ComboBox component for my problem
public class ComboBox extends CustomComponent implements Serializable {
private com.vaadin.ui.ComboBox comboBox;
private BeanItemContainer<ComboBoxItem> entries = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class);
public ComboBox() {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption, final List<ComboBoxItem> items) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
setCompositionRoot(comboBox);
}
public final void addItems(final List<ComboBoxItem> items) {
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
}
private void addItems(final BeanItemContainer<ComboBoxItem> items) {
comboBox.addItems(items);
}
public final void addItem(final ComboBoxItem item) {
if (item != null) {
comboBox.setContainerDataSource(entries);
comboBox.addItem(item);
comboBox.setItemCaptionPropertyId("description");
}
}
public final void selectByIndex(final int index) {
Object[] ids = comboBox.getItemIds().toArray();
comboBox.select(((ComboBoxItem) ids[index]));
}
public final void selectById(final String id) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getId().equals(id)) {
selectByIndex(i);
break;
}
}
}
public final void selectByItemText(final String description) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getDescription().equals(description)) {
selectByIndex(i);
break;
}
}
}
public final int getItemCount() {
return comboBox.getItemIds().toArray().length;
}
public final String getSelectedId() {
return ((ComboBoxItem) comboBox.getValue()).getId();
}
public final String getSelectedItemText() {
return ((ComboBoxItem) comboBox.getValue()).getDescription();
}
public final void addValueChangeListener(final ValueChangeListener listener) {
comboBox.addValueChangeListener(listener);
}
}
and below is test codes
final ComboBox combo = new ComboBox("My ComboBox");
combo.addItem(new ComboBoxItem("all", "All"));
// Add with list
List<ComboBoxItem> items = new ArrayList<ComboBoxItem>();
items.add(new ComboBoxItem("one", "One"));
items.add(new ComboBoxItem("two", "Two"));
items.add(new ComboBoxItem("three", "Three"));
combo.addItems(items);
combo.addItem(new ComboBoxItem("four", "Four"));
combo.addItem(new ComboBoxItem("five", "five"));
combo.selectByIndex(3);
combo.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
System.out.println(combo.getSelectedId() + " --- " + combo.getSelectedItemText());
}
});

Blackberry: Multiline ListView

I have made list view with checkboxes. I have read similar articles n many people have suggested to do changes in drawlistRow but it is not happening. Can u suggest me where should i change to make it a multi line list.The code snippet is :
Updated: I updated my code and it is still not working
public class CheckboxListField extends MainScreen implements ListFieldCallback, FieldChangeListener {
int mCheckBoxesCount = 5;
private Vector _listData = new Vector();
private ListField listField;
private ContactList blackBerryContactList;
private BlackBerryContact blackBerryContact;
private Vector blackBerryContacts;
private MenuItem _toggleItem;
ButtonField button;
BasicEditField mEdit;
CheckboxField cb;
CheckboxField[] chk_service;
HorizontalFieldManager hm4;
CheckboxField[] m_arrFields;
boolean mProgrammatic = false;
public static StringBuffer sbi = new StringBuffer();
VerticalFieldManager checkBoxGroup = new VerticalFieldManager();
LabelField task;
//A class to hold the Strings in the CheckBox and it's checkbox state (checked or unchecked).
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData()
{
_stringVal = "";
_checked = false;
}
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
private void setStringVal(String stringVal)
{
_stringVal = stringVal;
}
private void setChecked(boolean checked)
{
_checked = checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
CheckboxListField()
{
_toggleItem = new MenuItem("Change Option", 200, 10)
{
public void run()
{
//Get the index of the selected row.
int index = listField.getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
listField.invalidate(index);
if (index != -1 && !blackBerryContacts.isEmpty())
{
blackBerryContact =
(BlackBerryContact)blackBerryContacts.
elementAt(listField.getSelectedIndex());
ContactDetailsScreen contactDetailsScreen =
new ContactDetailsScreen(blackBerryContact);
UiApplication.getUiApplication().pushScreen(contactDetailsScreen);
}
}
};
listField = new ListField();
listField.setRowHeight(getFont().getHeight() * 2);
listField.setCallback(this);
reloadContactList();
//CheckboxField[] cb = new CheckboxField[blackBerryContacts.size()];
for(int count = 0; count < blackBerryContacts.size(); ++count)
{
BlackBerryContact item =
(BlackBerryContact)blackBerryContacts.elementAt(count);
String displayName = getDisplayName(item);
CheckboxField cb = new CheckboxField(displayName, false);
cb.setChangeListener(this);
add(cb);
listField.insert(count);
}
blackBerryContacts.addElement(cb);
add(checkBoxGroup);
}
protected void makeMenu(Menu menu, int instance)
{
menu.add(new MenuItem("Get", 2, 2) {
public void run() {
for (int i = 0; i < checkBoxGroup.getFieldCount(); i++) {
//for(int i=0; i<blackBerryContacts.size(); i++) {
CheckboxField checkboxField = (CheckboxField)checkBoxGroup
.getField(i);
if (checkboxField.getChecked()) {
sbi.append(checkboxField.getLabel()).append("\n");
}
}
Dialog.inform("Selected checkbox text::" + sbi);
}
});
super.makeMenu(menu, instance);
}
private boolean reloadContactList()
{
try {
blackBerryContactList =
(ContactList)PIM.getInstance().openPIMList
(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration allContacts = blackBerryContactList.items();
blackBerryContacts = enumToVector(allContacts);
listField.setSize(blackBerryContacts.size());
return true;
} catch (PIMException e)
{
return false;
}
}
//Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//graphics.drawText("ROW", 0, y, 0, w);
//String rowNumber = "one";
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*graphics.drawText("ROW " + rowNumber, y, 0, w);
graphics.drawText("ROW NAME", y, 20, w);
graphics.drawText("row details", y + getFont().getHeight(), 20, w); */
}
public void drawRow(Graphics g, int x, int y, int width, int height) {
// Arrange the cell fields within this row manager.
layout(width, height);
// Place this row manager within its enclosing list.
setPosition(x, y);
// Apply a translating/clipping transformation to the graphics
// context so that this row paints in the right area.
g.pushRegion(getExtent());
// Paint this manager's controlled fields.
subpaint(g);
g.setColor(0x00CACACA);
g.drawLine(0, 0, getPreferredWidth(), 0);
// Restore the graphics context.
g.popContext();
}
public static String getDisplayName(Contact contact)
{
if (contact == null)
{
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " " + displayName;
}
return displayName;
}
}
return displayName;
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
/*if (listField == list)
{
//If index is out of bounds an exception will be thrown,
//but that's the behaviour we want in that case.
//return blackBerryContacts.elementAt(index);
_listData = (Vector) blackBerryContacts.elementAt(index);
return _listData.elementAt(index);
}
return null;*/
}
//Returns the first occurence of the given String, bbeginning the search at index,
//and testing for equality using the equals method.
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
//return _listData.indexOf(p, s);
return -1;
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Graphics.getScreenWidth();
//return Display.getWidth();
}
public void fieldChanged(Field field, int context) {
boolean mProgrammatic = false;
if (!mProgrammatic) {
mProgrammatic = true;
CheckboxField cbField = (CheckboxField) field;
int index = blackBerryContacts.indexOf(cbField);
if (cbField.getChecked())
{
for(int i=0;i<blackBerryContacts.size();i++)
{
Dialog.inform("Selected::" + cbField.getLabel());
sbi=new StringBuffer();
sbi.append(cbField.getLabel());
}
}
mProgrammatic = false;
}
}
This code may be improved with:
Using ListField instead of VerticalFieldManager + CheckboxField array (ListField is much more faster, 100+ controls may slow down UI)
Using simple array instead of vector in list data (it's faster)
Moving contacts load from UI thread (we should aware of blocking UI thread with heavy procedures like IO, networking or work with contact list)
Actually using ListField with two line rows has one issue: we have to set the same height for all rows in ListField. So there always will be two lines per row, no matter if we will use second line or not. But it's really better than UI performance issues.
See code:
public class CheckboxListField extends MainScreen implements
ListFieldCallback {
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private Vector mContacts;
private MenuItem mMenuItemToggle = new MenuItem(
"Change Option", 0, 0) {
public void run() {
toggleItem();
};
};
private MenuItem mMenuItemGet = new MenuItem("Get", 0,
0) {
public void run() {
StringBuffer sbi = new StringBuffer();
for (int i = 0; i < mListData.length; i++) {
ChecklistData checkboxField = mListData[i];
if (checkboxField.isChecked()) {
sbi.append(checkboxField.getStringVal())
.append("\n");
}
}
Dialog.inform("Selected checkbox text::\n"
+ sbi);
}
};
// A class to hold the Strings in the CheckBox and it's checkbox state
// (checked or unchecked).
private class ChecklistData {
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
private void toggleChecked() {
_checked = !_checked;
}
}
CheckboxListField() {
// toggle list field item on navigation click
mListField = new ListField() {
protected boolean navigationClick(int status,
int time) {
toggleItem();
return true;
};
};
// set two line row height
mListField.setRowHeight(getFont().getHeight() * 2);
mListField.setCallback(this);
add(mListField);
// load contacts in separate thread
loadContacts.run();
}
protected Runnable loadContacts = new Runnable() {
public void run() {
reloadContactList();
// fill list field control in UI event thread
UiApplication.getUiApplication().invokeLater(
fillList);
}
};
protected Runnable fillList = new Runnable() {
public void run() {
int size = mContacts.size();
mListData = new ChecklistData[size];
for (int i = 0; i < mContacts.size(); i++) {
BlackBerryContact item = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(item);
mListData[i] = new ChecklistData(
displayName, false);
}
mListField.setSize(size);
}
};
protected void toggleItem() {
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
// Invalidate the modified row of the ListField.
mListField.invalidate(index);
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(mListField
.getSelectedIndex());
// process selected contact here
}
}
protected void makeMenu(Menu menu, int instance) {
menu.add(mMenuItemToggle);
menu.add(mMenuItemGet);
super.makeMenu(menu, instance);
}
private boolean reloadContactList() {
try {
ContactList contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
Enumeration allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
return true;
} catch (PIMException e) {
return false;
}
}
// Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
Object obj = this.get(list, index);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked()) {
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
rowString.append(Characters.BALLOT_BOX);
}
// Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
// Draw the text.
graphics.drawText(rowString.toString(), 0, y,
0, w);
String secondLine = "Lorem ipsum dolor sit amet, "
+ "consectetur adipiscing elit.";
graphics.drawText(secondLine, 0, y
+ getFont().getHeight(),
DrawStyle.ELLIPSIS, w);
} else {
graphics.drawText("No rows available.", 0, y,
0, w);
}
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(
Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " "
+ displayName;
}
return displayName;
}
}
return displayName;
}
// Returns the object at the specified index.
public Object get(ListField list, int index) {
Object result = null;
if (mListData.length > index) {
result = mListData[index];
}
return result;
}
// Returns the first occurrence of the given String,
// beginning the search at index, and testing for
// equality using the equals method.
public int indexOfList(ListField list, String p, int s) {
return -1;
}
// Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
// return Display.getWidth();
}
}
Have a nice coding!

blackberry: adding checkboxes in a list

I have fetched contact list successfully. But I am not able to add check boxes with that list. I have made separate program from checkbox and its working. but not with the contact list. Can anybody tell me here where should I add checkboxes? Here is the code:
public final class ContactsScreen extends MainScreen implements ListFieldCallback {
private ListField listField;
private ContactList blackBerryContactList;
private Vector blackBerryContacts;
public ContactsScreen(){
CheckboxField checkBox1 = new CheckboxField();
setTitle(new LabelField( "Contacts", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH ));
listField = new ListField();
listField.setCallback(this);
add(listField);
add(new RichTextField("Size" +(listField)));
reloadContactList();
}
private boolean reloadContactList() {
try {
blackBerryContactList = (ContactList)PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration allContacts = blackBerryContactList.items();
blackBerryContacts = enumToVector(allContacts);
listField.setSize(blackBerryContacts.size());
return true;
}
catch(PIMException e){
return false;
}
}
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField fieldVar, Graphics graphics, int index, int y, int width){
if ( listField == fieldVar && index < blackBerryContacts.size())
{
add(new RichTextField(blackBerryContacts.size()));
BlackBerryContact item = (BlackBerryContact)blackBerryContacts.elementAt(index);
String displayName = getDisplayName(item);
graphics.drawText(displayName, 0, y, 0, width);
}
}
public Object get(ListField fieldVar, int index)
{
if (listField == fieldVar) {
return blackBerryContacts.elementAt(index);
}
return null;
}
public int getPreferredWidth(ListField fieldVar ) {
return Display.getWidth();
}
public int indexOfList(ListField fieldVar, String prefix, int start)
{
return -1; // not implemented
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null; }
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
} return displayName;
}
}
ListField is not designed for this. Its list item is not a Manager, so you can't add any child fields to it. In other words this is not possible with ListField on BB. ListField is a way to represent on UI a long list without eating too much RAM (since in this case there is the only UI object - the ListField).
If your list is not too long (10 - 20 items) then consider using VerticalFieldManager instead of ListField. If list is long && you really need check boxes on it then consider using VerticalFieldManager + list pagination.

BlackBerry Alarm Integeration

Below is my application code. i want alarm to ring on my blackberry on every 6 of this month whether this apllication is running or not. please guide me in details i am a beginner.
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
import java.lang.String.*;
public class ListChk extends UiApplication
{
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
String getCompany;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private AutoTextEditField company;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
private ButtonField search;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
ListChk objListChk = new ListChk();
objListChk.enterEventDispatcher();
}//end of main of ListChk
public ListChk()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
company = new AutoTextEditField("Company: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
// A button that saves the the user data persistently when it is clicked
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
// a button which closes the entire application when clicked
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
// A button that shows the List of all Data being stored persistently
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
// pushing the next screen
pushScreen(new ListScreen());
}
});
search = new ButtonField("Search",ButtonField.CONSUME_CLICK);
search.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
pushScreen(new SearchScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(company);
mainScreen.add(gender);
mainScreen.add(status);
// Addning horizontal field manager
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
//adding buttons to the main screen in Horizontal field manager
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
horizontal.add(search);
//Adding the horizontal field manger to the screen
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
Dialog.alert("Closing Application");
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
getCompany = (info.getElement(StoreInfo.setCompany));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.setCompany, company.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
company.setText(null);
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public static final int setCompany = 5;
public StoreInfo()
{
_elements = new Vector(6);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String getUserFirstName;
String getUserLastName;
String getUserEmail;
String getUserGender;
String getUserStatus;
String getUserCompany;
String[] setData ;
String getData = new String();
String collectData = "";
ObjectListField fldList;
int counter = 0;
private ButtonField btnBack;
public ListScreen()
{
setTitle(new LabelField("Showing Data",LabelField.NON_FOCUSABLE));
//getData = myList();
//Dialog.alert(getData);
// setData = split(getData,"$");
// for(int i = 0;i<setData.length;i++)
// {
// add(new RichTextField(setData[i]+"#####"));
// }
showList();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void showList()
{
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLLBAR|HorizontalFieldManager.HORIZONTAL_SCROLL);
//SeparatorField spManager = new SeparatorField();
LabelField lblcheck = new LabelField("check",LabelField.NON_FOCUSABLE);
getData = myList();
setData = split(getData,"$");
fldList = new ObjectListField(ObjectListField.MULTI_SELECT);
fldList.set(setData);
//fldList.setEmptyString("heloo", 12);
//hfManager.add(lblcheck);
hfManager.add(fldList);
//hfManager.add(spManager);
add(hfManager);
addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = fldList.getSelectedIndex();
String item = (String)fldList.get(fldList, selectedIndex);
pushScreen(new ShowDataScreen(item));
}
});
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
public String myList()
{
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--,counter++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
//StoreInfo info = (StoreInfo)_data.lastElement();
getUserFirstName = (info.getElement(StoreInfo.NAME));
getUserLastName = (info.getElement(StoreInfo.LastNAME));
//getUserEmail = (info.getElement(StoreInfo.EMail));
//getUserGender = (info.getElement(StoreInfo.GenDer));
//getUserStatus = (info.getElement(StoreInfo.setStatus));
getUserCompany = (info.getElement(StoreInfo.setCompany));
collectData = collectData + getUserFirstName+" "+getUserLastName+" "+getUserCompany+ "$";
}
}
}
catch(Exception e){}
return collectData;
}//end of myList method
public boolean onClose()
{
System.exit(0);
return true;
}
}//end of class ListScreen
class ShowDataScreen extends MainScreen
{
String getFirstName;
String getLastName;
String getCompany;
String getEmail;
String getGender;
String getStatus;
String[] getData;
public ShowDataScreen(String data)
{
getData = split(data," ");
getFirstName = getData[0];
getLastName = getData[1];
getCompany = getData[2];
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
if (!_data.isEmpty())
{
if((getFirstName.equalsIgnoreCase(info.getElement(StoreInfo.NAME))) && (getLastName.equalsIgnoreCase(info.getElement(StoreInfo.LastNAME))) && (getCompany.equalsIgnoreCase(info.getElement(StoreInfo.setCompany))))
{
getEmail = info.getElement(StoreInfo.EMail);
getGender = info.getElement(StoreInfo.GenDer);
getStatus = info.getElement(StoreInfo.setStatus);
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.NON_FOCUSABLE);
AutoTextEditField name = new AutoTextEditField("Name: ",getFirstName+" "+getLastName);
AutoTextEditField email = new AutoTextEditField("Email: ",getEmail);
AutoTextEditField company = new AutoTextEditField("Company: ",getCompany);
AutoTextEditField Gender = new AutoTextEditField("Gender: ",getGender);
AutoTextEditField status = new AutoTextEditField("Status: ",getStatus);
add(name);
add(email);
add(company);
add(Gender);
add(status);
}
}
}//end of for loop
}//end of try
catch(Exception e){}
//Dialog.alert("fname is "+getFirstName+"\nlastname = "+getLastName+" company is "+getCompany);
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
}
class SearchScreen extends MainScreen
{
private ButtonField btnFirstName;
private ButtonField btnLastName;
private ButtonField btnSearch;
private ButtonField btnEmail;
private SeparatorField sp;
String userName;
HorizontalFieldManager hr = new HorizontalFieldManager();
public AutoTextEditField searchField;
public SearchScreen()
{
sp = new SeparatorField();
setTitle(new LabelField("your Search Options"));
add(new RichTextField("Search by : "));
btnFirstName = new ButtonField("First Name",ButtonField.CONSUME_CLICK);
hr.add(btnFirstName);
btnFirstName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//HorizontalFieldManager hrs = new HorizontalFieldManager();
searchField = new AutoTextEditField("First Name: ","ali");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new FirstnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
//hrs.add(sp);
}
});
btnLastName = new ButtonField("Last Name",ButtonField.CONSUME_CLICK);
hr.add(btnLastName);
btnLastName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Last Name: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new LastnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
btnEmail = new ButtonField("Email",ButtonField.CONSUME_CLICK);
hr.add(btnEmail);
btnEmail.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Email: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new EmailScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
add(hr);
}
void myShow()
{
Dialog.alert(searchField.getText());
}
}
class FirstnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public FirstnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchFirstName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchFirstName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
firstUserName = (info.getElement(StoreInfo.NAME));
if(firstUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class LastnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public LastnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchLastName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchLastName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
lastUserName = (info.getElement(StoreInfo.LastNAME));
if(lastUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class EmailScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public EmailScreen(String mail)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+mail));
userName = mail;
searchEmail();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBa
What are the benefits of integrating with the built-in alarm application? Would it be better for your application to place an event in the device's calendar and make the event show a reminder?
If you have to have a more prominent alarm, why not do it yourself? An alarm is an action the phone does (either make a sound and/or vibrate) that shows on the screen why it is taking that action and the action stops when someone responds to it.
Can you just make an app that starts in the background, checks the day, and makes a sound/vibrates on that day?
The default Alarm app on my phone only supports one time to ring. If I set it to wake me up at 4 a.m., but your app reschedules the alarm on my phone for 8 a.m., you would instantly lose a customer (after I wake up 4 hours too late).

BlackBerry Persistent store

I am developing an application in which I want to store many data entries using persistent store. the problem is whenever new entry is made it replaces the existing entry.
here is my code please help me.
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
/*An application in which user enters the data. this data is displayed when user press the save button*/
public class Display extends UiApplication {
/*declaring Strings to store the data of the user*/
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
/*creating instance of the class */
Display app = new Display();
app.enterEventDispatcher();
}
/*creating default constructor*/
public Display()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(gender);
mainScreen.add(status);
//adding buttons to the main screen
mainScreen.add(close);
mainScreen.add(save);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
//pushing the main screen
pushScreen(mainScreen);
}
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
StoreInfo info = (StoreInfo)
//returning last component of the vector
_data.lastElement();
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
//calling the show method
show();
}
}
}
};
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public StoreInfo()
{
_elements = new Vector(5);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
//creating save method
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
}
Actually it's saves everything perfectly, but retrieving only the last one record:
StoreInfo info = (StoreInfo)_data.lastElement();
Try this to display every record:
for (int i = 0; i < _data.size(); i++) {
StoreInfo info = (StoreInfo)_data.elementAt(i);
...
show();
}

Resources