Related
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());
}
});
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;
}
}
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!
I'm trying to create an app displaying few extra rows on the top of a list of items with a "live search" field on the top:
Of course I've tried using a KeywordFilterField with overriden setSize() for that at first. But this didn't work well - because I couldn't control, when and how setSize() was called by the KeywordFilterField and this has given me drawing issues (a row was not drawn when I had a keyword entered and added a new item to the list, etc.)
So I am trying to "go back to the roots" and use a ListField (and a BasicEditField on the top) this time, because there I can control myself, when and how setSize() is called.
Below is my simplified test code - src\mypackage\MyList.java and border.png.
The code works well, except for the filtering issue - which I will describe below.
package mypackage;
import java.util.*;
import net.rim.device.api.collection.*;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.system.*;
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.ui.decor.*;
import net.rim.device.api.util.*;
public class MyList extends UiApplication {
public static void main(String args[]) {
MyList app = new MyList();
app.enterEventDispatcher();
}
public MyList() {
pushScreen(new MyScreen());
}
}
class MyScreen extends MainScreen {
static final int EXTRA_ROWS = 3;
BasicFilteredList myFilter = new BasicFilteredList();
Background myBg = BackgroundFactory.createSolidBackground(0x111111);
StringProvider myProvider = new StringProvider("Search");
BasicEditField myFind = new BasicEditField(USE_ALL_WIDTH) {
protected void paint(Graphics g) {
if (getTextLength() == 0) {
g.setColor(Color.LIGHTGRAY);
g.drawText(myProvider.toString(), 0, 0);
}
g.setColor(Color.BLACK);
super.paint(g);
}
};
MyItemList myItems = new MyItemList();
// add 1 row for the "* Empty *" string
ListField myList = new ListField(EXTRA_ROWS + 1) {
protected boolean navigationClick(int status, int time) {
int index = getSelectedIndex();
if (index >= EXTRA_ROWS && myItems.size() > 0) {
String str = ((MyItem) myItems.getAt(
index - EXTRA_ROWS)).toString();
Status.show("You have clicked - " + str);
}
return true;
}
};
Border myBorder = BorderFactory.createBitmapBorder(
new XYEdges(12, 12, 12, 12),
Bitmap.getBitmapResource("border.png"));
public MyScreen() {
getMainManager().setBackground(myBg);
myFind.setBorder(myBorder);
setTitle(myFind);
myItems.doAdd(new MyItem(1, "Eins"));
myItems.doAdd(new MyItem(2, "Zwei"));
myItems.doAdd(new MyItem(3, "Drei"));
myItems.doAdd(new MyItem(4, "Vier"));
myList.setCallback(new MyListFieldCallback());
add(myList);
myFilter.addDataSet(1, myItems.getElements(), "Test",
BasicFilteredList.COMPARISON_IGNORE_CASE);
}
protected boolean keyChar(char key, int status, int time) {
if (key == Characters.BACKSPACE && myFind.getTextLength() == 0) {
Status.show("Kill kill kill!");
return true;
}
if (myFind.getTextLength() > 0) {
System.err.println("XXX filter for " + myFind.getText());
}
return super.keyChar(key, status, time);
}
private class MyListFieldCallback implements ListFieldCallback {
public void drawListRow(ListField list, Graphics g, int index, int y, int width) {
Font i = getFont().derive(Font.ITALIC);
g.setColor(Color.DIMGRAY);
g.drawLine(0, y-9, width, y-9);
g.setColor(Color.WHITE);
if (index < EXTRA_ROWS) {
g.setFont(i);
g.drawText("Add Item", 0, y, DrawStyle.ELLIPSIS|DrawStyle.HCENTER, width);
return;
}
if (myItems.size() == 0) {
g.setFont(i);
g.drawText(list.getEmptyString(), 0, y, DrawStyle.ELLIPSIS|DrawStyle.HCENTER, width);
return;
}
MyItem item = (MyItem) myItems.getAt(index - EXTRA_ROWS);
g.drawText(item.toString(), 0, y, DrawStyle.ELLIPSIS|DrawStyle.HCENTER, width);
}
public Object get(ListField list, int index) {
return myItems.getAt(index);
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
public int indexOfList(ListField list, String prefix, int start) {
return 0;
}
}
class MyItemList extends SortedReadableList {
public MyItemList() {
super(new MyItem.MyComparator());
}
protected void doAdd(Object obj) {
super.doAdd(obj);
myList.setSize(size() + EXTRA_ROWS);
}
protected boolean doRemove(Object obj) {
// if the list is empty, add 1 row for "* Empty *" string
int size = (size() == 0 ? EXTRA_ROWS + 1 : size() - 1 + EXTRA_ROWS);
myList.setSize(size);
return super.doRemove(obj);
}
protected Object[] getElements() {
return super.getElements();
}
}
}
class MyItem {
int _num;
String _name;
public MyItem(int num, String name) {
_num = num;
_name = name;
}
public String toString() {
return _num + ": " + _name;
}
static class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
MyItem item1 = (MyItem) obj1;
MyItem item2 = (MyItem) obj2;
return item1.toString().compareTo(item2.toString());
}
}
static class MyProvider implements KeywordProvider {
public String[] getKeywords(Object obj) {
MyItem item = (MyItem) obj;
return new String[]{ Integer.toString(item._num), item._name };
}
}
}
My problem is that I do not know how to add filtering.
For example when a user enters "E" into myFind, my code will detect this event in the keyChar() and also I understand, that I will have to call myList.setSize(EXTRA_ROWS + 1) because there will be 1 filtered result.
But how do I filter the items displayed by myList, how to implement this?
Maybe I could use BasicFilteredList and its method
public void addDataSet(int id,
Object[] objects,
String name,
long style)
but I'm not sure how to apply it here?
UPDATE:
I've added a BasicFilteredList to my test code above, but am still not sure how to marry it with a ListField.
You have to do the filtering in code somewhere, and then store the result. Override myFind.update(int) to run the filtering when the filtering text changes. In addition to myItems, you need to store myFilteredItems. After filtering, call setSize() on the listfield. The listfield drawing code also needs to draw from the filtered collection. Then you should be set.
I've ended up with this code which seems to work well for me (except 2 minor issues listed below) and the green answer mark goes to Michael Donohue for his valuable suggestions.
I use 2 Vectors: myData and myFilteredData. And for UI I use a ListField and a BasicEditField:
border.png:
src\mypackage\MyList.java:
package mypackage;
import java.util.*;
import net.rim.device.api.collection.*;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.system.*;
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.ui.decor.*;
import net.rim.device.api.util.*;
public class MyList extends UiApplication {
public static void main(String args[]) {
MyList app = new MyList();
app.enterEventDispatcher();
}
public MyList() {
pushScreen(new MyScreen());
}
}
class MyScreen extends MainScreen {
static final int EXTRA_ROWS = 3;
Background myBg = BackgroundFactory.createSolidBackground(0x111111);
StringProvider myProvider = new StringProvider("Search");
BasicEditField myFind = new BasicEditField(USE_ALL_WIDTH|TextField.NO_NEWLINE) {
protected void paint(Graphics g) {
if (getTextLength() == 0) {
g.setColor(Color.LIGHTGRAY);
g.drawText(myProvider.toString(), 0, 0);
}
g.setColor(Color.BLACK);
super.paint(g);
}
protected void update(int delta) {
filterData(getText());
}
};
Vector myData = new Vector();
final static SimpleSortingVector myFilteredData = new SimpleSortingVector();
// add 1 row for the "* Empty *" string
ListField myList = new ListField(EXTRA_ROWS + 1) {
protected boolean navigationClick(int status, int time) {
int index = getSelectedIndex();
if (index >= EXTRA_ROWS && myFilteredData.size() > 0) {
String str = ((MyItem) myFilteredData.elementAt(index - EXTRA_ROWS)).toString();
Status.show("You have clicked - " + str);
}
return true;
}
};
Border myBorder = BorderFactory.createBitmapBorder(
new XYEdges(12, 12, 12, 12),
Bitmap.getBitmapResource("border.png"));
public MyScreen() {
getMainManager().setBackground(myBg);
myFind.setBorder(myBorder);
setTitle(myFind);
myData.addElement(new MyItem(1, "Eins"));
myData.addElement(new MyItem(2, "Zwei"));
myData.addElement(new MyItem(3, "Drei"));
myData.addElement(new MyItem(4, "Vier"));
myFilteredData.setSortComparator(new MyItem.MyComparator());
filterData("");
myList.setCallback(new MyListFieldCallback());
add(myList);
}
private void filterData(String prefix) {
myFilteredData.removeAllElements();
if (prefix == null || prefix.length() == 0) {
// no prefix specified - copy everything
for (int i = myData.size() - 1; i >= 0; i--) {
MyItem item = (MyItem) myData.elementAt(i);
myFilteredData.addElement(item);
}
} else {
// copy only strings starting with prefix
for (int i = myData.size() - 1; i >= 0; i--) {
MyItem item = (MyItem) myData.elementAt(i);
String name = item.name.toLowerCase();
if (name.startsWith(prefix.toLowerCase())) {
myFilteredData.addElement(item);
}
}
}
myFilteredData.reSort();
// if the list is empty, add 1 row for "* Empty *" string
int size = (myFilteredData.size() == 0 ? EXTRA_ROWS + 1 : myFilteredData.size() + EXTRA_ROWS);
myList.setSize(size);
}
protected boolean keyChar(char key, int status, int time) {
if (key == Characters.BACKSPACE && myFind.getTextLength() == 0) {
int index = myList.getSelectedIndex();
if (index >= EXTRA_ROWS && myFilteredData.size() > 0) {
String str = ((MyItem) myFilteredData.elementAt(index - EXTRA_ROWS)).toString();
Status.show("You're deleting - " + str);
}
return true;
}
return super.keyChar(key, status, time);
}
static class MyListFieldCallback implements ListFieldCallback {
public void drawListRow(ListField list, Graphics g, int index, int y, int width) {
Font i = g.getFont().derive(Font.ITALIC);
g.setColor(Color.DIMGRAY);
g.drawLine(0, y-9, width, y-9);
g.setColor(Color.WHITE);
if (index < EXTRA_ROWS) {
g.setFont(i);
g.drawText("Add Item", 0, y, DrawStyle.ELLIPSIS|DrawStyle.HCENTER, width);
return;
}
if (myFilteredData.size() == 0) {
g.setFont(i);
g.drawText(list.getEmptyString(), 0, y, DrawStyle.ELLIPSIS|DrawStyle.HCENTER, width);
return;
}
MyItem item = (MyItem) myFilteredData.elementAt(index - EXTRA_ROWS);
g.drawText(item.toString(), 0, y, DrawStyle.ELLIPSIS|DrawStyle.HCENTER, width);
}
public Object get(ListField list, int index) {
return myFilteredData.elementAt(index);
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
public int indexOfList(ListField list, String prefix, int start) {
return myFilteredData.indexOf(prefix, start);
}
}
}
class MyItem {
int num;
String name;
public MyItem(int num, String name) {
this.num = num;
this.name = name;
}
public String toString() {
return num + ": " + name;
}
static class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
MyItem item1 = (MyItem) obj1;
MyItem item2 = (MyItem) obj2;
String name1 = item1.toString().toLowerCase();
String name2 = item2.toString().toLowerCase();
return name1.compareTo(name2);
}
}
}
My minor problems are:
Why do I need to subtract 9 in drawListRow() to draw the lines?
Why does the caret disappear in BasicEditField after using it?
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).