BlackBerry Persistent store - blackberry

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();
}

Related

Null point exception in persistent object , blackberry application

I am using persistent stores to store data in a Blackberry application. I am trying to store phone number in persistent objects, but after storing, it gives null value.
here i am posting my code:
public static Vector push_data;
public static PersistentObject push_store = null;
public static final long KEY = 0x9df9f961bc333daL;
boolean isNumberVerified;
// PasswordEditField password;
static String verifiedPhoneNumber = "number";
public static String phoneNumber;
static String Number = "number";
public Third() {
super(Field.USE_ALL_HEIGHT | Field.FIELD_HCENTER);
System.out.println("******************** Into SplashScreen");
try {
bitmap = Bitmap.getBitmapResource("im.png");
BitmapField bmpField = new BitmapField(bitmap);
HorizontalFieldManager hfm = new HorizontalFieldManager();
hfm.add(bmpField);`
........
public void fieldChanged(Field field, int context) {
if (field == btnNext) {
final String msg = Util.getRandomNumber();
checkIsVerified(Number, msg);
}
}
private void checkIsVerified(final String Number, final String msg) {
Dialog.alert("Verifying " + Number);
if (verifiedPhoneNumber == Number) {
isNumberVerified = true;
Dialog.alert("isverified " + Number);
push_store = PersistentStore.getPersistentObject( KEY );
push_data = (Vector) push_store.getContents();
if( push_data == null ) {
push_data = new Vector();
push_data.addElement("number");
push_store.setContents( push_data );
push_store.commit();
Dialog.alert("isverified " + push_data);
UiApplication.getUiApplication().pushScreen(new spinner());
} else {
isNumberVerified = false;
UiApplication.getUiApplication().pushScreen(new Sms());
}
}
Try this -
public static String push_data="";
public static PersistentObject push_store;
public static final long KEY = 0x9df9f961bc33352L;
//For get contents
push_store = PersistentStore.getPersistentObject( KEY );
push_data = (String) push_store.getContents();
//For set contents
push_data=Number;
push_store.setContents( push_data );
push_store.commit();

Refreshing Table Model Adapter on deleting record from it : Blackberry

I m creating a Table Model Adapter in Blackberry.(**This is a sample what i m doing****)I have added button field and two Strings.I m putting data in String from vector.Now on button click i want to delete the row against button.The Data is deleted from the database but not removed from Screen view when button is clicked.When i calld the Retrieve() function to call updated database and draw the Table model adapter again....it is adding new Table below old one....not refreshing it. Is there any solution to show the refreshed data in same table.
package mypackage;
import java.util.Vector;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.table.DataTemplate;
import net.rim.device.api.ui.component.table.TableController;
import net.rim.device.api.ui.component.table.TableModelAdapter;
import net.rim.device.api.ui.component.table.TableView;
import net.rim.device.api.ui.component.table.TemplateColumnProperties;
import net.rim.device.api.ui.component.table.TemplateRowProperties;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.decor.BackgroundFactory;
public final class MyScreen extends MainScreen implements FieldChangeListener
{
private DeviceTableModelAdapter _tableModel;
private Vector _cities;
private static final int NUM_ROWS = 1;
private static final int ROW_HEIGHT = 50;
private static final int NUM_COLUMNS = 3;
public ButtonField btn;
public MyScreen(){
super(Manager.NO_VERTICAL_SCROLL);
_cities = new Vector();
_tableModel = new DeviceTableModelAdapter();
Vector sample =new Vector();
sample.addElement("Newyork");
sample.addElement("NewDelhi");
sample.addElement("NewOrleans");
int ik = 0;
while(ik < sample.size())
{
String modelNumber = sample.elementAt(ik).toString();
String modelName = "-Earth-";
String ne = String.valueOf(ik);
Object[] row = {modelName, modelNumber, ne};
_tableModel.addRow(row);
ik++;
}
TableView tableView = new TableView(_tableModel);
tableView.setDataTemplateFocus(BackgroundFactory.createLinearGradientBackground(Color.WHITE, Color.WHITE, Color.BLUEVIOLET, Color.BLUEVIOLET));
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)
{
Object[] data = (Object[]) (_tableModel.getRow(modelRowIndex));
Field[] fields = {getButtonFieldObject((String)data[0]), new LabelField((String) data[1]), new LabelField((String) data[2])};
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);
add(tableView);
}
public void fieldChanged(Field arg0, int arg1) {
/*** tableView.DeleteAll(); ****/
/**** calling Class again to draw the table Modal Adapter again with updated value *******/
}
private final static class City
{
private String _name;
private String _region;
private String _image;
City(String name, String region, String image)
{
_name = name;
_region = region;
_image = image;
}
public String getName()
{
return _name;
}
public String getRegion()
{
return _region;
}
public String getImage()
{
return _image;
}
}
private class DeviceTableModelAdapter extends TableModelAdapter
{
public int getNumberOfRows()
{
return _cities.size();
}
public int getNumberOfColumns()
{
return NUM_COLUMNS;
}
protected boolean doAddRow(Object row)
{
Object[] arrayRow = (Object[]) row;
_cities.addElement(new City((String) arrayRow[0], (String) arrayRow[1], (String) arrayRow[2]));
return true;
}
protected Object doGetRow(int index)
{
City city = (City) _cities.elementAt(index);
Object[] row = {city.getImage(), city.getRegion(), city.getName()};
return row;
}
}
public ButtonField getButtonFieldObject(String arg){
btn = new ButtonField(arg,ButtonField.CONSUME_CLICK);
btn.setChangeListener(this);
return btn;
}
}
What you have to consider is the fact that Blackberry table UI follows the MVC design pattern.
So it means that data are updated in the model.
Like for example:
Object yes = (Object)"Yes";
// gets the Model attached to this View
TableModel tm = (TableModel)view.getModel();
// updates the data attached to the row
tm.setElement(rowIndex, columnIndex, yes);
tm.modelReset();

Refreshing Table Adapter screen : 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;
}
}

Blackberry: saving ListField content and dirty state management

I have prepared a simple test case to demonstrate my problem.
It is just 1 file which will run instantly when added to a new project.
I would like to have a MainScreen displaying an editable list of items:
and when leaving this screen, the user should be asked - if she wants to save the modified list to persistent storage, by presenting the standard Save/Discard/Cancel-dialog:
I have added setDirty(true) to my menu items and the standard dialog does come up okay.
My problem is: I don't know how to clear the dirty flag after saving - in my current code the Save/Discard/Cancel-dialog comes again and again, even if I just view the ListField, without editing it.
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 implements FieldChangeListener {
MyScreen myScreen = new MyScreen();
public static void main(String args[]) {
MyList app = new MyList();
app.enterEventDispatcher();
}
public MyList() {
MainScreen titleScreen = new MainScreen();
titleScreen.setTitle("Click the button:");
ButtonField myButton = new ButtonField("Show the list", ButtonField.CONSUME_CLICK) ;
myButton.setChangeListener(this);
titleScreen.add(myButton);
pushScreen(titleScreen);
}
public void fieldChanged(Field field, int context) {
pushScreen(myScreen);
}
}
class MyScreen extends MainScreen {
ObjectListField myList = new ObjectListField();
static PersistentObject myStore;
static Vector myData;
static {
myStore = PersistentStore.getPersistentObject(0xb77f8e453754f37aL);
myData = (Vector) myStore.getContents();
if (myData == null) {
myData = new Vector();
myData.addElement("String 1");
myData.addElement("String 2");
myData.addElement("String 3");
myStore.setContents(myData);
}
}
public MyScreen() {
setTitle("Edit the list below:");
add(myList);
addMenuItem(addItem);
addMenuItem(editItem);
addMenuItem(removeItem);
}
// load data from persistent store into the ListField
private void loadData() {
// clear the ListField
myList.setSize(0);
// copy data from the Vector to the ListField
for (int i = myData.size() - 1; i >= 0; i--)
myList.insert(0, myData.elementAt(i));
}
// save data from the ListField into the persistent store
private void saveData() {
// clear the Vector
myData.removeAllElements();
// copy data from the ListField to the Vector
for (int i = myList.getSize() - 1; i >=0; i--)
myData.addElement(myList.get(myList, i));
synchronized(PersistentStore.getSynchObject()) {
myStore.commit();
}
}
protected void onUiEngineAttached(boolean attached) {
if (attached) {
loadData();
}
}
public void save() {
saveData();
// UPDATE: when I call setDirty(false); here, then
// the app starts displaying Save/Discard/Cancel dialog
// on its exit - so there must be a better way...
}
private final MenuItem addItem = new MenuItem("Add Item", 0, 0) {
public void run() {
String[] buttons = {"Add", "Cancel"};
Dialog myDialog = new Dialog("Add Item", buttons, null, 0, null);
EditField myEdit = new EditField("Item: ", "");
myDialog.add(myEdit);
if (myDialog.doModal() == 0) {
myList.insert(0, myEdit.getText());
setDirty(true);
}
}
};
private final MenuItem editItem = new MenuItem("Edit Item", 0, 0) {
public void run() {
String[] buttons = {"Save", "Cancel"};
Dialog myDialog = new Dialog("Edit Item", buttons, null, 0, null);
int index = myList.getSelectedIndex();
if (index == -1) {
return;
}
String selectedItem = (String) myList.get(myList, index);
EditField myEdit = new EditField("Item: ", selectedItem);
myDialog.add(myEdit);
if (myDialog.doModal() == 0) {
myList.set(index, myEdit.getText());
setDirty(true);
}
}
};
private final MenuItem removeItem = new MenuItem("Remove Item", 0, 0) {
public void run() {
String[] buttons = {"Delete", "Cancel"};
Dialog myDialog = new Dialog("Remove Item", buttons, null, 0, null);
int index = myList.getSelectedIndex();
if (index == -1) {
return;
}
String selectedItem = (String) myList.get(myList, index);
LabelField myLabel = new LabelField("Really delete " + selectedItem + "?");
myDialog.add(myLabel);
if (myDialog.doModal() == 0) {
myList.delete(index);
setDirty(true);
}
}
};
}
Please share your Blackberry 6 experience, advices in regard to persistent storage are also welcome.
In my real program I'm using KeywordFilterField for viewing a SortedReadableList, so from reading Blackberry docs I suppose, that I must always copy data between SortedReadableList and Vector - because the latter is persistable and the former is not?
setDirty(false) will clear the dirty flag if that is what you are after.

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).

Resources