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).
Related
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();
I am trying to save a path to an image in the persistent store to show the image when a user chooses a specific product from a history list(one image per product, taken by the user). Now the problem I am having is that when I load the app to the phone for the first time and try adding an entry to the persistent store, it throws an error a bit after and the app freezes. However when I come back, and add an image again, it works just fine and the images always load when I choose each specific product.
This is leading me to believe that the culprit is the first store8.commit() that I'm doing, for some reason it throws an exception : No Stack Trace, when debugging. Here is my code:
public class Storage extends Application {
private static final long PERSISTENT_KEY8 = 0x2c4c45c139ee9728L;
static PersistentObject store8 = PersistentStore.getPersistentObject(PERSISTENT_KEY8);
private static Vector pics;
/**
* Picture Section ***********************************************************
*/
public static void savePicture(){
store8.setContents(new Vector());
store8.commit();
if(pics == null){
pics = new Vector();
}
synchronized(store8) {
store8.setContents(pics);
store8.commit();
}
}
public static String getPicture(String productName){
if(pics.size()==0){
return "";
}else{
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
return product.getPic();
}
}
return "";
}
}
public static void removePicture(String productName){
if(pics.size()==0){
return;
}else{
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
pics.removeElementAt(i);
}
}
}
}
public static void loadPicture(){
pics = (Vector)store8.getContents();
if(pics == null){
pics = new Vector();
}
}
public static void setPicture(Pics pro){
if(pics.size()!=0){
for(int j = 0; j< pics.size() ; j++){
Pics product = (Pics)pics.elementAt(j);
if(pro.getProductName().equals(product.getProductName())){
pics.removeElementAt(j);
}
}
}
pics.addElement(pro);
}
}
So that is the class that contains my methods to save the image. Now for the other class where I am manipulating it:
public class ProductImage extends MainScreen implements FieldChangeListener, AppLaunchResource {
private ImageButtonField logo;
private ButtonField newImage, chooseExisting;
public static BitmapField takenPicture;
//public static String picPath ="";
private String currentPicture = "";
private String currentProduct ="";
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
this.setTitle(new LabelField("Add An Image", Field.FIELD_HCENTER));
if(ToolbarManager.isToolbarSupported())
{
Toolbar tb = new Toolbar();
setToolbar(tb.createToolBar());
}
else{
Toolbar tb = new Toolbar();
add(tb.createNavBar());
}
try{
Storage.loadPicture();
}catch(NullPointerException e){
e.printStackTrace();
}
newImage = new ButtonField("Take Photo", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) (net.rim.device.api.system.Display.getWidth());
}
};
chooseExisting= new ButtonField("Change Image", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) (net.rim.device.api.system.Display.getWidth());
}
};
newImage.setChangeListener(this);
chooseExisting.setChangeListener(this);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
VerticalFieldManager vfMain = new VerticalFieldManager();
vfMain.add(new SeparatorField());
vfMain.add(newImage);
vfMain.add(chooseExisting);
vfMain.add(takenPicture);
add(vfMain);
currentPicture = Storage.getPicture(currentProduct);
showPicture();
}
public void choosePicture(){
String imageExtensions[] = {"jpg", "jpeg",
"bmp", "png", "gif"};
FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
fps.pickFile();
String theFile = fps.getFile();
UiApplication.getUiApplication().pushScreen(fps);
if (theFile == null)
{
Dialog.alert("Screen was dismissed. No file was selected.");
}
else
{
try{
String path= "file:///" + theFile;
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
if(Display.getHeight()>Display.getWidth()){
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
else{
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
UiApplication.getUiApplication().popScreen(fps);
takenPicture.setBitmap(eImage.getBitmap());
Storage.setPicture(new Pics(currentProduct, path));
try{
Storage.savePicture();
}catch(Exception e){
e.printStackTrace();
}
}
catch(Exception e){
}
Dialog.alert("Picture Saved");
}
}
public void showPicture(){
if(currentPicture != ""){
try{
String path= currentPicture;
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
if(Display.getHeight()>Display.getWidth()){
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
else{
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
takenPicture.setBitmap(eImage.getBitmap());
}
catch(Exception e){
}
}
}
public void fieldChanged(Field field, int context) {
if(field == logo){
}
else if(field == newImage){
takePicture();
}
else if(field == chooseExisting){
choosePicture();
}
}
}
I removed many parts of this class, sorry if it is long, there are basically 4 Storage method calls in this code and I believe they are all in the right place.. but again im having the problem on first load, not afterwards.
Can anyone see what Im doing wrong here? I have had this problem for a week
Thanks for any help provided!
Try something like this:
public class Storage extends Application{
private static final long PERSISTENT_KEY8 = 0x2c4c45c139ee9728L;
static PersistentObject store8 = null;
private static Vector pics = null;
static{
store8 = PersistentStore.getPersistentObject(PERSISTENT_KEY8)
pics = (Vector)store8.getContents();
if(pics == null){
pics = new Vector();
store8.setContents(pics);
store8.commit();
}
}
public static void savePicture(){
try{
synchronized(store8){
store8.setContents(pics);
store8.commit();
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static int findPicture(String productName){
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
return i;
}
}
return -1;
}
public static String getPicture(String productName){
int idx = findPicture(productName);
if(idx != -1){
return ((Pics)pics.elementAt(idx)).getPic();
}
return "";
}
public static void removePicture(String productName){
int idx = findPicture(productName);
if(idx != -1){
pics.removeElementAt(idx);
}
}
public static void setPicture(Pics pro){
removePicture(pro.getProductName());
pics.addElement(pro);
}
}
.
public class ProductImage extends MainScreen implements FieldChangeListener, AppLaunchResource {
private ImageButtonField logo;
private ButtonField newImage, chooseExisting;
public static BitmapField takenPicture;
//public static String picPath ="";
private String currentPicture = "";
private String currentProduct = "";
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
setTitle(new LabelField("Add An Image", Field.FIELD_HCENTER));
Toolbar tb = new Toolbar();
if(ToolbarManager.isToolbarSupported()){
setToolbar(tb.createToolBar());
}
else{
add(tb.createNavBar());
}
newImage = new ButtonField("Take Photo", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) Display.getWidth();
}
};
chooseExisting = new ButtonField("Change Image", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) Display.getWidth();
}
};
newImage.setChangeListener(this);
chooseExisting.setChangeListener(this);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
VerticalFieldManager vfMain = new VerticalFieldManager();
vfMain.add(new SeparatorField());
vfMain.add(newImage);
vfMain.add(chooseExisting);
vfMain.add(takenPicture);
add(vfMain);
currentPicture = Storage.getPicture(currentProduct);
showPicture();
}
public void choosePicture(){
String imageExtensions[] = {"jpg", "jpeg", "bmp", "png", "gif"};
FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
fps.pickFile();
String theFile = fps.getFile();
if (theFile == null){
Dialog.alert("Screen was dismissed. No file was selected.");
return;
}
EncodedImage eImage = loadImage("file:///" + theFile);
if(eImage != null){
takenPicture.setBitmap(eImage.getBitmap());
Storage.setPicture(new Pics(currentProduct, path));
Storage.savePicture();
Dialog.alert("Picture Saved");
}
}
private EncodedImage loadImage(String path){
try{
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
int scaleFactorX, scaleFactorY;
if(Display.getHeight()>Display.getWidth()){
scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(Display.getWidth()));
scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
}
else{
scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(Display.getWidth()));
scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(Display.getHeight()));
}
return eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
catch (Exception e){
return null;
}
}
public void showPicture(){
if(currentPicture != ""){
EncodedImage eImage = loadImage(currentPicture);
if (eImage != null){
takenPicture.setBitmap(eImage.getBitmap());
}
}
}
public void fieldChanged(Field field, int context){
if(field == logo){
}
else if(field == newImage){
takePicture();
}
else if(field == chooseExisting){
choosePicture();
}
}
}
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 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();
}