Limited ListField items are drawn instead of complete list in Blackberry - blackberry

I am trying to draw a list of all contacts saved in device. Everything is fine but when I select all contacts, I get only those contacts which are drawn on the screen. In other words, list drawing only those contacts which are visible on screen. To get the remaining contacts I have to scroll the list.
Here is my code:
public class CheckboxListField extends VerticalFieldManager implements ListFieldCallback, FieldChangeListener {
private static Vector selectedContacts ;
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private static Vector mContacts;
private ContactList contactList;
private Enumeration allContacts;
private SendEmail sendEmail;
private boolean isChecked=false;
private BlackBerryContact contactItem;
private VerticalFieldManager _mainVFM = new VerticalFieldManager();
private int i;
private int j=0;
private String emails="";
private ButtonField _inviteButton;
private HorizontalFieldManager selectAllHFM;
private CustomButtonField selectAllButton;
private Bitmap _uncheckBmp;
private Bitmap _checkBmp;
private LabelField selectAllLabel;
private CheckboxField selectAllCheckBox;
private VerticalFieldManager contactListVFM;
private boolean listItemChecked=false;
private StringBuffer rowString;
private boolean getCBoxStatus;
// 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;
private String _telNumber;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
//_telNumber = telNumber;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
public void toggleChecked() {
_checked = !_checked;
}
}
public CheckboxListField() {
_mainVFM.add(createContactList(isChecked));
add(_mainVFM);
}
public VerticalFieldManager createContactList(boolean checked){
isChecked = checked;
selectedContacts = new Vector();
//INVITE BUTTON
contactListVFM = new VerticalFieldManager();
_inviteButton=new ButtonField("Invite Friend");
_inviteButton.setChangeListener(this);
_inviteButton.setMargin(2,0,10,0);
//SELECT ALL CHECKBOX
selectAllHFM = new HorizontalFieldManager();
_uncheckBmp = Bitmap.getBitmapResource("Uncheck.png");
_checkBmp = Bitmap.getBitmapResource("checked.png");
selectAllButton = new CustomButtonField(29, "", _uncheckBmp, _checkBmp, ButtonField.CONSUME_CLICK);
selectAllButton.setChangeListener(this);
selectAllButton.setMargin(5,5,5,5);
selectAllCheckBox = new CheckboxField("Select All", isChecked){
protected boolean navigationClick(int status,
int time) {
selectedContacts = new Vector();
emails = "";
boolean getCBoxStatus = selectAllCheckBox.getChecked();
if(listItemChecked == false){
if(_mainVFM.getFieldCount()!= 0){
_mainVFM.deleteAll();
_mainVFM.add(createContactList(getCBoxStatus));
}
}
return true;
}
};
selectAllCheckBox.setChangeListener(this);
selectAllLabel = new LabelField("Select All");
selectAllLabel.setMargin(5,5,5,5);
selectAllHFM.add(selectAllCheckBox);
//selectAllHFM.add(selectAllLabel);
// 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);
//contactListVFM.add(new NullField(NullField.FOCUSABLE));
contactListVFM.add(_inviteButton);
contactListVFM.add(selectAllHFM);
contactListVFM.add(new SeparatorField());
contactListVFM.add(mListField);
//LOAD CONTACTS
// load contacts in separate thread
loadContacts.run();
return contactListVFM;
}
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++) {
contactItem = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(contactItem);
// String telContact = getContact(item);
mListData[i] = new ChecklistData(
displayName, isChecked);
mListField.invalidate(i);
System.out.println(">>>>>>>>>"+mListData[i]);
}
mListField.setSize(size);
//invalidate();
}
};
protected void toggleItem() {
listItemChecked = true ;
selectAllCheckBox.setChecked(false);
listItemChecked =false ;
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
System.out.println("..............."+index);
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
mListField.invalidate(index);
}
}
private boolean reloadContactList() {
try {
contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
System.out.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>>>>>>>>>>"+mListField.getSize());
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()){
Contact contact = (Contact) allContacts.nextElement();
if(contactList.isSupportedField(Contact.EMAIL)&& (contact.countValues(Contact.EMAIL) > 0)) {
String emailID=contact.getString(Contact.EMAIL, 0);
if(emailID.length() !=0 && emailID != null ){
v.addElement(contact);
}
}
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
rowString = new StringBuffer();
Object obj = this.get(list, index);
if (list.getSelectedIndex() != index) {
graphics.setBackgroundColor(index % 2 == 0 ||index==0 ? Color.WHITE
: Color.LIGHTGRAY);
graphics.clear();
//list.setFocus();
}
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(index);
String email= contact.getString(Contact.EMAIL, 0);
int vecIndex = selectedContacts.indexOf(email);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
if (currentRow.isChecked()) {
if(vecIndex == -1){
selectedContacts.addElement(email);
}
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
selectedContacts.removeElement(email);
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);
}
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];
}
System.out.println(",,,,,,,,,,,,,,,,,,,,,,,"+mListData.length);
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();
}
public void fieldChanged(Field field, int context) {
if(field==_inviteButton){
for(int n=0 ; n<selectedContacts.size() ; n++){
emails= emails + selectedContacts.elementAt(n)+",";
}
//}
String mailBody =": "+Jxa.loginUserName+" invited you on NaijaPings app. Please download NaijaPings Android app from here "+"http://appworld.blackberry.com/webstore/content/77264/?lang=en" ;
sendEmail=new SendEmail(mailBody);
sendEmail.Email(emails,Constant.emailSubject);
emails ="" ;
selectedContacts.removeAllElements();
}else if(field == selectAllCheckBox){
selectedContacts = new Vector();
emails = "";
getCBoxStatus = selectAllCheckBox.getChecked();
//selectedContacts.removeAllElements();
if(listItemChecked == false){
if(_mainVFM.getFieldCount()!= 0){
_mainVFM.deleteAll();
_mainVFM.add(createContactList(getCBoxStatus));
}
}
}
}
}
Here ,in drawListRow() , get() method is called only that many times that is number of contacts are visible on the screen. For remaining contact to add, I have to scroll the list.
In drawListRow() method I am adding those contacts into selectedContacts vector and than using those vector to get contact to send a mail. Contacts will be added only when particular list item will be drawn.
So, how I can get all selected contact without scrolling the list?

This is similar to the problem you had in one of your other recent questions. The problem is that drawListRow() is a callback designed to let you draw the rows that need drawing. It's not meant to do anything else, like assembling a list of contacts to email.
The BlackBerry OS tries to be efficient, so it will only ask you to drawListRow() for the rows that are actually visible to the user (on screen). Anything more would be wasteful.
So, if you want to assemble a list of all selected rows, you should do it somewhere else, not in drawListRow().
It looks to me like you can build a list of all currently selected rows by using this code, wherever you want:
public Vector getSelectedContacts() {
selectedContacts.removeAllElements();
for (int i = 0; i < mListData.length; i++) {
Object obj = mListData[i];
if (obj != null) {
BlackBerryContact contact = (BlackBerryContact) mContacts.elementAt(i);
String email = contact.getString(Contact.EMAIL, 0);
int vecIndex = selectedContacts.indexOf(email);
ChecklistData currentRow = (ChecklistData) obj;
if (currentRow.isChecked()) {
if(vecIndex == -1){
selectedContacts.addElement(email);
}
} else {
// this line is probably not actually needed, since we
// call removeAllElements() at the start of this method
selectedContacts.removeElement(email);
}
}
}
return selectedContacts;
}

Related

How to open new class file on click of treeview parent and child item in blackberry?

public class Expandablelistview extends MainScreen {
public Expandablelistview() {
// A separator field between each type of control\
// setTitle("Tree Field Demo");
String parentfield1 = new String("Demo1");
String parentfield2 = new String("Demo2");
String childfield1 = new String("Demo3");
String childfield2 = new String("Demo4");
String parentfield3 = new String("Demo5");
String parentfield4 = new String("Demo6");
String childfield3 = new String("Demo7");
String childfield4 = new String("Demo8");
String childfield5 = new String("Demo9");
String childfield6 = new String("Demo10");
String parentfield5 = new String("Demo11");
String childfield7 = new String("Demo12");
String childfield8 = new String("Demo13");
TreeCallback myCallback = new TreeCallback();
final TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE);
myTree.setDefaultExpanded(false);
int node12 = myTree.addChildNode(0, parentfield5);
int node13 = myTree.addChildNode(node12, childfield7);
int node14 = myTree.addChildNode(node12, childfield8);
// int node7 = myTree.addChildNode(0, parentfield5);
int node6 = myTree.addChildNode(0, parentfield4);
int node11 = myTree.addChildNode(node6, childfield6);
int node10 = myTree.addChildNode(node6, childfield5);
int node8 = myTree.addChildNode(node6, childfield3);
int node9 = myTree.addChildNode(node6, childfield4);
int node5 = myTree.addChildNode(0, parentfield3);
int node2 = myTree.addChildNode(0, parentfield2);
int node3 = myTree.addChildNode(node2, childfield1);
int node4 = myTree.addChildNode(node2, childfield2);
int node1 = myTree.addChildNode(0, parentfield1);
add(myTree);
// myTree.setChangeListener(new myTreeChangeListener());
// HERE I TRIED FOR ITEM CLICK
FieldChangeListener fdbtncalculate = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
int a = myTree.getNodeCount();
System.out.print("mytree" + a);
if (a == 0) {
Dialog.alert("data");
} else if (a == 1) {
Dialog.alert("data");
}
}
};
myTree.setChangeListener(fdbtncalculate);
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
String text = (String) _tree.getCookie(node);
g.drawText(text, indent, y);
}
}
}
i want to know what i am doing wrong? i want to open my class file on click of parent and child item of treeview for that i used field listener
Instead of using a FieldChangeListener, try this code, which overrides navigationClick():
TreeCallback myCallback = new TreeCallback();
TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0 &&
(status & KeypadListener.STATUS_SHIFT) == 0)
{
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node.
Dialog.alert("clicked leaf node " + getCookie(node));
return true;
} else {
// Node is a parent node
setExpanded(node, !getExpanded(node));
Dialog.alert("clicked parent node " + getCookie(node));
return true;
}
}
return super.navigationClick(status, time);
}
};
I'm not sure what you mean by "open new class file", but whatever you want to do after the user clicks a part of the tree, you would do it where I have the Dialog.alert() code above.

Get data only one folder not for all folders in treeview - Blackberry

i want to show all folders(images, videos,files) with directories/files, currently only show images folder with files, but other folder are not show. I try to find solution but not found. Here is the code & its screenshot(http://postimg.org/image/wm5ypbk9d/).
FileManager.java
package com.rim.samples.device.mapactiondemo;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
public class FilesManager extends MainScreen {
FTPMessages _ftp = null;
String[] fileList;
// ..................
private final Bitmap openIcon = Bitmap.getBitmapResource("open.png");
private final Bitmap closedIcon = Bitmap.getBitmapResource("closed.png");
private final Bitmap movieIcon = Bitmap.getBitmapResource("movie.png");
private final Bitmap songIcon = Bitmap.getBitmapResource("song.png");
private final Bitmap playIcon = Bitmap.getBitmapResource("play.png");
private final Bitmap imgIcon = Bitmap.getBitmapResource("images.png");
String nodeTen;
int node10;
TreeField myTree;
String[] nodeData;
// ListField to be displayed - null - no Field displayed
// List of entries to be displayed - null or length = 0 means no entries
// protected so that another Thread can update this list....
protected ListDirectory[] _resultsList = null; // entries available for
// display
private ListDirectory _selectedEntry = null;
public FilesManager(FTPMessages ftp) {
super();
_ftp = ftp;
// Setting starting directory
try {
/*
* fileList = _ftp.list(); for (int i = 0; i < fileList.length; i++)
* { _ftp.cwd(fileList[i]); }
*/
_ftp.cwd("images");
_ftp.cwd("files");
_ftp.cwd("videos");
} catch (Exception e) {
}
this.setTitle("Server File List");
TreeCallback myCallback = new TreeCallback();
myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0
&& (status & KeypadListener.STATUS_SHIFT) == 0) {
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node. Do some default action or
// else fall through.
// Note: this will also detect empty folders, which
// might or
// might not be something your app has to handle
Dialog.alert("clicked " + getCookie(node));
// TODO: open player screen, etc.
return true;
}
}
return super.navigationClick(status, time);
}
};
myTree.setDefaultExpanded(false);
myTree.setRowHeight(openIcon.getHeight());
try {
node10 = myTree.addChildNode(0, _ftp.pwd());
} catch (Exception e) {
}
this.add(myTree);
refreshList();
}
private void refreshList() {
// TODO Auto-generated method stub
_resultsList = null;
String[] directory = null;
try {
directory = _ftp.list();
} catch (Exception e) {
}
if (directory != null && directory.length > 0) {
_resultsList = new ListDirectory[directory.length];
for (int i = 0; i < directory.length; i++) {
_resultsList[i] = new ListDirectory(directory[i],
ListDirectory.UNIX_SERVER);
}
}
if (_resultsList != null && _resultsList.length > 0) {
// we have some results
for (int i = 0; i < _resultsList.length; i++) {
String bb = directory[i];
String nodeFive = new String(bb);
this.myTree.addChildNode(node10, nodeFive);
}
} else {
}
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
final int PAD = 8;
String text = (String) _tree.getCookie(node);
Bitmap icon = closedIcon;
if (text.endsWith(".mp3")) {
icon = songIcon;
} else if (text.endsWith(".avi")) {
icon = movieIcon;
} else if (text.endsWith(".png") || text.endsWith(".jpg")) {
icon = imgIcon;
} else if (_tree.getExpanded(node)) {
icon = openIcon;
}
g.drawBitmap(indent, y, icon.getWidth(), icon.getHeight(), icon, 0,
0);
// This assumes filenames all contain '.' character!
if (text.indexOf(".") > 0) {
// Leaf node, so this is a playable item (movie or song)
g.drawBitmap(_tree.getWidth() - playIcon.getWidth() - PAD, y
+ PAD, playIcon.getWidth(), playIcon.getHeight(),
playIcon, 0, 0);
}
int fontHeight = getFont().getHeight();
g.drawText(text, indent + icon.getWidth() + PAD,
y + (_tree.getRowHeight() - fontHeight) / 2);
}
}
}
The other classes that used with this code, download from that link(complete project classes)
http://remote.offroadstudios.com/files/filemanager.zip
you can also check files on server, ip:64.207.150.31:21, username:remote, password:123456789

How to get multiple selected list items from list field checkbox and add into an arraylist in blackberry

Please anyone help me get selected listitems from a listfieldcheckbox, and add them into an arraylist. If possible, give any useful links also. Here's my code so far (I am new to blackberry application development). Please help.
package mypackage;
import java.util.Vector;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.IntVector;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements ListFieldCallback
{
private Vector _listData = new Vector();
private Vector _checkedData = new Vector();
private ListField listField;
private static final String[] _elements = {"First element", "Second element","Third element"
};
//private static final String[] _elements1 = {"hai","welcome","where r u"
//};
private MenuItem _getDataMenu,selectall,Delete;
Vector result = new Vector();
protected void makeMenu(Menu menu, int instance)
{
menu.add(_getDataMenu);
menu.add(selectall);
menu.add(Delete);
//Create the default menu.
super.makeMenu(menu, instance);
}
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;
}
}
public Vector getCheckedItems() {
return _checkedData;
}
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
VerticalFieldManager main = new VerticalFieldManager(VerticalFieldManager.USE_ALL_HEIGHT|
VerticalFieldManager.USE_ALL_WIDTH|VerticalFieldManager.VERTICAL_SCROLL);
this.add(main);
HorizontalFieldManager hfm = new HorizontalFieldManager();
main.add(hfm);
listField = new ListField(){
//Allow the space bar to toggle the status of the selected row.
protected boolean keyChar(char key, int status, int time)
{
boolean retVal = false;
//If the spacebar was pressed...
if (key == Characters.SPACE)
{
//Get the index of the selected row.
int index = 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.
invalidate(index);
//Consume this keyChar (key pressed).
retVal = true;
}
return retVal;
}
};
listField.setCallback(this);
reloadList();
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.addElement(new ChecklistData(_elements[count], false));
//_listData.addElement(new ChecklistData(_elements1[count], false));
listField.insert(count);
}
main.add(listField);
_getDataMenu =new MenuItem("Get Data", 200, 10) {
public void run(){
int index = listField.getSelectedIndex();
ChecklistData data = (ChecklistData)_listData.elementAt(index);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
//Dialog.alert(message);
// get all the checked data indices
IntVector selectedIndex = new IntVector(0, 1);
//ChecklistData data;
for (int i=0;i<_listData.size();i++) {
data = (ChecklistData)_listData.elementAt(i);
if(data.isChecked()) {
selectedIndex.addElement(i);
String selectedvalues = data.getStringVal();
System.out.println("Selected items are:"+selectedvalues);
}
}
data = null;
// now selectedIndex will contain all the checked data indices.
//String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
}
};
selectall = new MenuItem("Selectall", 200, 10){
public void run(){
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.setElementAt(new ChecklistData(_elements[count], true), count);
}
}
};
Delete = new MenuItem("Delete", 200, 10){
public void run(){
int index = listField.getSelectedIndex();
_listData.removeElementAt(index);
// update the view
listField.delete(index);
listField.invalidate(index);
}
};
}
private void reloadList() {
// TODO Auto-generated method stub
_listData.setSize(_listData.size());
}
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());
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*if (currentRow.isChecked()) {
if( -1 ==_checkedData.indexOf(currentRow))
_checkedData.addElement(currentRow);
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else {
if( -1 !=_checkedData.indexOf(currentRow))
_checkedData.removeElement(currentRow);
rowString.append(Characters.BALLOT_BOX);
} */
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
}
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
return _listData.indexOf(p, s);
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
protected boolean navigationClick(int status, int time) {
int index1 = listField.getSelectedIndex();
/*System.out.println("Selected item index:"+index1);
//int[] list =listField.getSelection();
//String s = Integer.toString(list);
System.out.println(" items are:"+_elements[index1]);
//ChecklistData data = (ChecklistData)_listData.elementAt(index1);*/
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index1);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
System.out.println("message is:"+message);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index1);
//Invalidate the modified row of the ListField.
listField.invalidate(index1);
return true;
}
}

Backup/Restore net.rim.device.api.util.Persitable object with DesktopManger

The task is to backup/restore Persistable object with BB Desktop Manager or in any other way. The main aim is to keep data between device firmware updates...
I have:
public final class UserList implements Persistable {
//The persistable objects.
private Hashtable fData;
//Initialize the class with empty values.
public UserList() {
fData = new Hashtable();
}
//Initialize the class with the specified values.
public UserList(Hashtable p) {
fData = p;
}
public Hashtable getData() {
return fData;
}}
I also have implemented SyncItem (as found in one of the examples)
public final class UserListSync extends SyncItem {
private static UserList fList;
private static final int FIELDTAG_NAME = 1;
private static final int FIELDTAG_AGE = 2;
private static PersistentObject store;
static {
store = PersistentStore.getPersistentObject(0x3167239af4aa40fL);
}
public UserListSync() {
}
public String getSyncName() {
return "Sync Item Sample";
}
public String getSyncName(Locale locale) {
return null;
}
public int getSyncVersion() {
return 1;
}
public boolean getSyncData(DataBuffer db, int version) {
boolean retVal = true;
synchronized (store) {
if (store.getContents() != null) {
fList = (UserList)store.getContents();
}
}
try {
Enumeration e = fList.getData().keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = (String) fList.getData().get(key);
//Write the name.
db.writeShort(key.length() + 1);
db.writeByte(FIELDTAG_NAME);
db.write(key.getBytes());
db.writeByte(0);
//Write the age.
db.writeShort(value.length() + 1);
db.writeByte(FIELDTAG_AGE);
db.write(value.getBytes());
db.writeByte(0);
}
} catch (Exception e) {
retVal = false;
}
return retVal;
}
//Interprets and stores the data sent from the Desktop Manager.
public boolean setSyncData(DataBuffer db, int version) {
int length;
Hashtable table = new Hashtable();
Vector keys = new Vector();
Vector values = new Vector();
boolean retVal = true;
try {
//Read until the end of the Databuffer.
while (db.available() > 0) {
//Read the length of the data.
length = db.readShort();
//Set the byte array to the length of the data.
byte[] bytes = new byte[length];
//Determine the type of data to be read (name or age).
switch (db.readByte()) {
case FIELDTAG_NAME:
db.readFully(bytes);
keys.addElement(new String(bytes).trim());
break;
case FIELDTAG_AGE:
db.readFully(bytes);
values.addElement(new String(bytes).trim());
break;
}
}
} catch (Exception e) {
retVal = false;
}
for (int i = 0; i < keys.size(); i++) {
table.put(keys.elementAt(i), values.elementAt(i));
}
try {
//Store the new data in the persistent store object.
fList = new UserList(table);
store.setContents(fList);
store.commit();
} catch (Exception e) {
retVal = false;
}
return retVal;
}}
The entry poing is following:
public class SyncItemSample extends UiApplication {
private static PersistentObject store;
private static UserList userList;
static {
store = PersistentStore.getPersistentObject(0x3167239af4aa40fL);
}
public static void main(String[] args) {
SyncItemSample app = new SyncItemSample();
app.enterEventDispatcher();
}
public SyncItemSample() {
UserListScreen userListScreen;
//Check to see if the store exists on the BlackBerry.
synchronized (store) {
if (store.getContents() == null) {
//Store does not exist, create it with default values
userList = new UserList();
store.setContents(userList);
store.commit();
} else {
//Store exists, retrieve data from store.
userList = (UserList)store.getContents();
}
}
//Create and push the UserListScreen.
userListScreen = new UserListScreen(userList);
pushScreen(userListScreen);
}}
And here is an implementation of screen:
public final class UserListScreen extends MainScreen {
Vector fLabels = new Vector();
Vector fValues = new Vector();
VerticalFieldManager leftColumn = new VerticalFieldManager();
VerticalFieldManager rightColumn = new VerticalFieldManager();
UserList fList;
public UserListScreen(UserList list) {
super();
fList = list;
//Create a horizontal field manager to hold the two vertical field
//managers to display the names and ages in two columns.
VerticalFieldManager inputManager = new VerticalFieldManager();
HorizontalFieldManager backGround = new HorizontalFieldManager();
//Array of fields to display the names and ages.
LabelField title = new LabelField("User List",
LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
setTitle(title);
final TextField fld1 = new TextField(TextField.NO_NEWLINE);
fld1.setLabel("input label");
inputManager.add(fld1);
final TextField fld2 = new TextField(TextField.NO_NEWLINE);
fld2.setLabel("input value");
inputManager.add(fld2);
final ButtonField fld3 = new ButtonField();
fld3.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
fList.getData().put(fld1.getText().trim(), fld2.getText().trim());
refresh();
}
});
fld3.setLabel("add");
inputManager.add(fld3);
add(inputManager);
//Add the column titles and a blank field to create a space.
LabelField leftTitle = new LabelField("label ");
leftColumn.add(leftTitle);
LabelField rightTitle = new LabelField("value");
rightColumn.add(rightTitle);
refresh();
//Add the two vertical columns to the horizontal field manager.
backGround.add(leftColumn);
backGround.add(rightColumn);
//Add the horizontal field manager to the screen.
add(backGround);
}
private void refresh() {
leftColumn.deleteAll();
rightColumn.deleteAll();
fLabels.removeAllElements();
fValues.removeAllElements();
//Populate and add the name and age fields.
Enumeration e = fList.getData().keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = (String) fList.getData().get(key);
final LabelField tmp1 = new LabelField(key);
final LabelField tmp2 = new LabelField(value);
leftColumn.add(tmp1);
rightColumn.add(tmp2);
fLabels.addElement(tmp1);
fValues.addElement(tmp2);
}
}
public boolean onClose() {
System.exit(0);
return true;
}}
So as you see it should be very easy...
So all of these I run application, add values to Persistent object and they are added correctly, are stored during device resets and so on...
When I run Desktop Manager and make a Backup it seems that UserList is backed-up, as size of backup grows together with adding new data into persistent store.
But when I run "Wipe device" on my BB 9300 (and all data from Persistent store is cleared as it is expected) and then run Restore from just made backup file - nothing is updated in the Application and persistent store is seems to be empty.
In some examples I have found adding alternate entry point "init" but I can't tune eveything like it is described with my EclipsePlugin
Could you advice me how to store data in backup file and the to retrieve the same data from backup and load it back to the application, or how to log any of events with Desktop Manager?
If someone has experienced the same problem you can try to disconnect the device before wiping it. It is strange but it helped :)

Blackberry not able to fetch Latitude and longitude

I need to get the users latitude and longitude to display data in increasing order of distance.
I am using 2 phones in 2 different countries to test the app. It works fine with a bb bold 9700 when used in south asia. But does not with a bb 9650 when used in nyc.
I tried using the bb gps api based classes and also google tower based gps classes.
Both don't seem to work in nyc with bb 9650.I used other location based apps like yelp etc which work perfectly.
Attaching both the codes
Phone GPS
public class GPS_Location
{
private String log;
double longi;
double lati;
public GPS_Location()
{
new LocationTracker();
}
public boolean onClose()
{
Application.getApplication().requestBackground();
return false;
}
class LocationTracker extends TimerTask
{
private Timer timer;
private LocationProvider provider;
Criteria cr;
public LocationTracker()
{
timer = new Timer();
cr= new Criteria();
resetGPS();
timer.schedule(this, 0, 60000);
}
public void resetGPS()
{
try
{
provider = LocationProvider.getInstance(cr);
if(provider != null)
{
/*provider.setLocationListener(null, 0, 0, 0);
provider.reset();
provider = null;*/
provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
}
//provider = LocationProvider.getInstance(null);
} catch(Exception e)
{
}
}
public void run()
{
System.out.println("********************");
}
private class MyLocationListener implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location != null && location.isValid())
{
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try
{
lati = location.getQualifiedCoordinates().getLatitude();
System.out.println("********************latitude :: "+lati);
longi = location.getQualifiedCoordinates().getLongitude();
System.out.println("********************longitude ::"+longi);
CustomSession.getInstance().setLatitude(lati);
CustomSession.getInstance().setLongitude(longi);
}
catch(Exception e)
{
}
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
//LocationTracker.this.resetGPS();
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
{
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
}
}
cell tower google service
public class JsonGenerator {
public void locating() throws IOException{
byte[] postData = getGPSJsonObject().toString().getBytes();
JSONObject jsonObject = null;
HttpConnection gpsConnection;
DataOutputStream os;
DataInputStream dis;
String gpsString = retrunURLString("http://www.google.com/loc/json");
try {
gpsConnection = (HttpConnection) Connector.open(gpsString);
gpsConnection.setRequestMethod(HttpConnection.POST);
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_LENGTH, String
.valueOf(postData.length));
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_TYPE,
"application / requestJson");
os = gpsConnection.openDataOutputStream();
os.write(postData);
int rc = gpsConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
return;
}
dis = gpsConnection.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = dis.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
String jsonString = new String(data);
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject locationObject = jsonObject.getJSONObject("location");
if (locationObject.getDouble("latitude") != 0.0
&& locationObject.getDouble("longitude") != 0.0) {
System.out.println("Latitute is =================::::"+locationObject.getDouble("latitude"));
System.out.println("Llongitude is =================::::"+locationObject.getDouble("longitude"));
CustomSession.getInstance().setLatitude(locationObject.getDouble("latitude"));
CustomSession.getInstance().setLongitude(locationObject.getDouble("longitude"));
// Global.horizontal_accuracy = locationObject
// .getDouble("accuracy");
// Global.locAvailable = true;
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public JSONObject getGPSJsonObject() {
JSONObject jsonString = new JSONObject();
try {
jsonString.put("version", "1.1.0");
jsonString.put("host", "maps.google.com");
int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
jsonString.put("home_mobile_country_code", Integer.parseInt(Integer
.toHexString(x)));
jsonString.put("home_mobile_network_code", RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
int radio = RadioInfo.getNetworkType();
if(radio==RadioInfo.NETWORK_CDMA){
jsonString.put("radio_type", "cdma");
}
else{
jsonString.put("radio_type", "gsm");
}
jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
jsonString.put("request_address", true);
jsonString.put("address_language", "en_GB");
CellTower cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo
.getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
Hashtable map = new Hashtable();
map.put("mobile_country_code", new Integer(Integer
.parseInt(cellInfo.mobileCountryCode)));
map.put("location_area_code",
new Integer(cellInfo.locationAreaCode));
map.put("signal_strength", new Integer(cellInfo.signalStrength));
map.put("cell_id", new Integer(cellInfo.cellID));
map.put("age", new Integer(0));
map.put("mobile_network_code", new Integer(
cellInfo.mobileNetworkCode));
JSONArray array = new JSONArray();
array.put(0, map);
jsonString.put("cell_towers", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
public static String retrunURLString(String url) {
String urlString = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// WIFI
urlString = url + ";interface=wifi";
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
ServiceRecord record = getWAP2ServiceRecord();
if (record != null
&& (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// WAP 2.0
urlString = url + ";deviceside=true;ConnectionUID="
+ record.getUid();
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// BES/MDS
urlString = url + ";deviceside=false";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Direct TCP/IP
urlString = url + ";deviceside=true";
} else if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
// BIS
urlString = url + ";deviceside=false;ConnectionUID="
+ record.getUid();
}
}
return urlString;
}
protected static ServiceRecord getWAP2ServiceRecord() {
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
for (int i = 0; i < records.length; i++) {
String cid = records[i].getCid().toLowerCase();
String uid = records[i].getUid().toLowerCase();
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
return null;
}
private class CellTower {
public String mobileCountryCode;
public int locationAreaCode;
public int signalStrength;
public int cellID;
public int age;
public int mobileNetworkCode;
private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc) {
mobileCountryCode = mcc;
locationAreaCode = lac;
signalStrength = ss;
cellID = ci;
age = a;
mobileNetworkCode = mnc;
}
}
}
Ideally you should be using multiple fix methods (your Criteria) to gather GPS information. Using just the default will not work in all circumstances, so you need to have fallback options. Here are the Criteria, in preferred order, that I use in the States and seems to do well. You just have to loop through them until you have a set that works.
//Speed optimal
BlackBerryCriteria speed = new BlackBerryCriteria();
speed.setHorizontalAccuracy(50);
speed.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
speed.setCostAllowed(true);
speed.setPreferredResponseTime(10000);
//MS-Based
BlackBerryCriteria msBased = new BlackBerryCriteria();
msBased.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
msBased.setHorizontalAccuracy(50);
msBased.setVerticalAccuracy(50);
msBased.setCostAllowed(true);
msBased.setPreferredResponseTime(10000);
//Assisted mode
BlackBerryCriteria assisted = new BlackBerryCriteria();
assisted.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_HIGH);
assisted.setHorizontalAccuracy(50);
assisted.setVerticalAccuracy(50);
assisted.setCostAllowed(true);
assisted.setPreferredResponseTime(10000);
//Autonomous
BlackBerryCriteria autonomous = new BlackBerryCriteria();
autonomous.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
autonomous.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setCostAllowed(true);
autonomous.setPreferredResponseTime(180000);
//Cell site
BlackBerryCriteria cell = new BlackBerryCriteria();
cell.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_LOW);
cell.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setCostAllowed(true);
cell.setPreferredResponseTime(180000);

Resources