how to find the size of object stored (in bytes or kb,mb) on persistence store in blackberry - blackberry

I am trying to find the size of the object that I store on persistence store . I have programatically found out the size of object as shown in code but I can not find out the size of this object when it is stored on persistence store.
Does data get compressed automatically when it is comitted to store.
I m using Memory.getFlashStats().getFree(); to get the free size of persistence store before and after commitnig the object to store and the difference between the two values should be equal to the size of object that i have calculated.
please see the code
package Bean;
import java.util.Enumeration;
import java.util.Vector;
import net.rim.device.api.system.Memory;
import net.rim.device.api.system.MemoryStats;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;
import bean.UserCredentials;
public class MyStoreScreen extends MainScreen implements FieldChangeListener
{
private int nObjectSize;
static final long PERSISTENT_STORE_DEMO_ID = 0x42c16456ab0b5eabL;
private static PersistentObject oPersistenStore;
private int nFreePersistenceInStarting=Memory.getPersistentStats().getFree();
private int nFreePersistenceAtEnd;
ButtonField oCalculateMemButton ;
private MenuItem saveItem = new MenuItem("Save ", 110, 10)
{
public void run()
{
Dialog.alert("initially free memory ----------------------"+nFreePersistenceInStarting);
oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
Vector storeVector = (Vector)oPersistenStore.getContents();
Vector userinfo ;
int size = (storeVector == null) ? 0 : storeVector.size();
if(size == 0)
{
userinfo = new Vector();
}
else
{
userinfo = storeVector;
}
UserCredentials oUserCredentials = new UserCredentials("akanksha","chandra",1,3434.3434,343545646);
for(int i =0;i<=100;i++)
{
userinfo.addElement(oUserCredentials);
}
nObjectSize= fnCalculateSizeOfObject(userinfo);
Dialog.alert("size of object is "+ nObjectSize);
synchronized(oPersistenStore)
{
oPersistenStore.setContents(userinfo);
oPersistenStore.commit();
}
}
};
private MenuItem getItem = new MenuItem( "Get item", 110, 11 )
{
public void run()
{
oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
synchronized(oPersistenStore)
{
Vector arrCredential = (Vector)oPersistenStore.getContents();
if(arrCredential != null)
{
String dataContents = "";
int nSize = (arrCredential == null) ? 0 : arrCredential.size();
if(nSize != 0)
{
for (int i = 0; i < nSize; i++)
{
UserCredentials oUserCredentials = (UserCredentials)arrCredential.elementAt(i);
dataContents+="\n size of vector is "+nSize+ " username : "+oUserCredentials.getStrUsername()+"\n password : "+oUserCredentials.getStrPassword();
dataContents += "\n\nUser sal : "+oUserCredentials.getdSalary();
dataContents += "\n amount : "+oUserCredentials.getlAmount();
dataContents += "\n s no "+oUserCredentials.getnSerialNo();
}
Dialog.alert(dataContents);
}
else
{
Dialog.alert("Zero Elements ");
}
}
else
{
Dialog.alert("No contents ");
}
}
}
};
private MenuItem resetStoreItem = new MenuItem( "Delete Store", 110, 11 )
{
public void run()
{
int choice = Dialog.ask(Dialog.D_OK_CANCEL, "Do you want to delete ?");
if(choice == Dialog.D_OK)
{
// oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
PersistentStore.destroyPersistentObject(PERSISTENT_STORE_DEMO_ID);
}
else
{
}
}
};
private MenuItem CalculateTotalFlashUsed = new MenuItem("calculate used flash size ", 0, 7)
{
public void run()
{
Dialog.alert("used size of Persistence Store is "+fnUsedPersistenceSize());
};
};
public MyStoreScreen()
{
oCalculateMemButton = new ButtonField("calculate free flash memory in starting", ButtonField.CONSUME_CLICK);
oCalculateMemButton.setChangeListener(this);
this.add(oCalculateMemButton);
this.addMenuItem(saveItem);
this.addMenuItem(getItem);
this.addMenuItem(resetStoreItem);
this.addMenuItem(CalculateTotalFlashUsed);
oPersistenStore = PersistentStore.getPersistentObject(PERSISTENT_STORE_DEMO_ID);
}
public void fieldChanged(Field field, int context)
{
if(field ==oCalculateMemButton)
{
// nFreeFlashInStarting =Memory.getFlashTotal();
// nFreeFlashInStarting =Memory.getFlashStats().getFree();
// nFreeFlashAtEnd =Memory.getFlashStats().getFree();
// String message = "total flash is Memory.getFlashStats().getAllocated(); "+nFreeFlashInStarting+" Memory.getFlashTotal() is : "+Memory.getFlashTotal();
String message = "total free flash memory in starting is :"+ nFreePersistenceInStarting;
Dialog.alert(message);
}
}
private int fnCalculateSizeOfObject(Vector userInfo )
{
int nSize = 0;
Enumeration oEnumeration = userInfo.elements();
while(oEnumeration.hasMoreElements())
{
UserCredentials oUserCredentials = (UserCredentials) oEnumeration.nextElement();
String UserName = oUserCredentials.getStrUsername();
String password = oUserCredentials.getStrPassword();
int nSerialNo = oUserCredentials.getnSerialNo();
double dSalary = oUserCredentials.getdSalary();
long lAmount = oUserCredentials.getlAmount();
nSize+= 4+8+8+fnCalculateSizeOfString(UserName)+fnCalculateSizeOfString(password);
}
return nSize;
}
private int fnCalculateSizeOfString(String strInputString)
{
//convert String to char array
char[] characterArray = strInputString.toCharArray();
int nlength = characterArray.length;
return nlength;
}
public int fnUsedPersistenceSize()
{
nFreePersistenceAtEnd = Memory.getPersistentStats().getFree();
int nUsedPersistenceMemory = nFreePersistenceInStarting -nFreePersistenceAtEnd;
return nUsedPersistenceMemory;
}
}

Memory.getFlashStats().getFree() is not that accurate, you can see it when measuring storage of the same object several times - values may be different every time.
The best way to measure object size is to calculate its fields size (what you actually doing).

Related

Is this the best way to get all elements & attributes in an XML file using Saxon?

Our program displays a tree control showing the metadata structure of the XML file they are using as a datasource. So it displays all elements & attributes in use in the XML file, like this:
Employees
Employee
FirstName
LastName
Orders
Order
OrderId
For the case where the user does not pass us a XSD file, we need to walk the XML file and build up the metadata structure.
The full code for this is at SaxonQuestions.zip, TestBuildTree.java and is also listed below.
I am concerned that my code is not the most efficient, or maybe even wrong. It works, but it works on the 3 XML files I tested it on. My questions are:
What is the best way to get the root element from the DOM? Is it walking the children of the DOM root node?
What is the best way to determine if an element has data (as opposed to just child elements)? The best I could come up with throws an exception if not and I don't think code executing the happy path should throw an exception.
What is the best way to get the class of the data held in an element or attribute? Is it: ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Is the best way to walk all the nodes to use XdmNode.axisIterator? And to do so as I have in this code?
TestBuildTree.java
import net.sf.saxon.s9api.*;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class TestBuildTree {
public static void main(String[] args) throws Exception {
XmlDatasource datasource = new XmlDatasource(
new FileInputStream(new File("files", "SouthWind.xml").getCanonicalPath()),
null);
// Question:
// Is this the best way to get the root element?
// get the root element
XdmNode rootNode = null;
for (XdmNode node : datasource.getXmlRootNode().children()) {
if (node.getNodeKind() == XdmNodeKind.ELEMENT) {
rootNode = node;
break;
}
}
TestBuildTree buildTree = new TestBuildTree(rootNode);
Element root = buildTree.addNode();
System.out.println("Schema:");
printElement("", root);
}
private static void printElement(String indent, Element element) {
System.out.println(indent + "<" + element.name + "> (" + (element.type == null ? "null" : element.type.getSimpleName()) + ")");
indent += " ";
for (Attribute attr : element.attributes)
System.out.println(indent + "=" + attr.name + " (" + (attr.type == null ? "null" : attr.type.getSimpleName()) + ")");
for (Element child : element.children)
printElement(indent, child);
}
protected XdmItem currentNode;
public TestBuildTree(XdmItem currentNode) {
this.currentNode = currentNode;
}
private Element addNode() throws SaxonApiException {
String name = ((XdmNode)currentNode).getNodeName().getLocalName();
// Question:
// Is this the best way to determine that this element has data (as opposed to child elements)?
Boolean elementHasData;
try {
((XdmNode) currentNode).getTypedValue();
elementHasData = true;
} catch (Exception ex) {
elementHasData = false;
}
// Questions:
// Is this the best way to get the type of the element value?
// If no schema is it always String?
Class valueClass = ! elementHasData ? null : ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Element element = new Element(name, valueClass, null);
// add in attributes
XdmSequenceIterator currentSequence;
if ((currentSequence = moveTo(Axis.ATTRIBUTE)) != null) {
do {
name = ((XdmNode) currentNode).getNodeName().getLocalName();
// Questions:
// Is this the best way to get the type of the attribute value?
// If no schema is it always String?
valueClass = ((XdmAtomicValue)((XdmNode)currentNode).getTypedValue()).getValue().getClass();
Attribute attr = new Attribute(name, valueClass, null);
element.attributes.add(attr);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
// add in children elements
if ((currentSequence = moveTo(Axis.CHILD)) != null) {
do {
Element child = addNode();
// if we don't have this, add it
Element existing = element.getChildByName(child.name);
if (existing == null)
element.children.add(child);
else
// add in any children this does not have
existing.addNewItems (child);
} while (moveToNextInCurrentSequence(currentSequence));
moveTo(Axis.PARENT);
}
return element;
}
// moves to element or attribute
private XdmSequenceIterator moveTo(Axis axis) {
XdmSequenceIterator en = ((XdmNode) currentNode).axisIterator(axis);
boolean gotIt = false;
while (en.hasNext()) {
currentNode = en.next();
if (((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode) currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE) {
gotIt = true;
break;
}
}
if (gotIt) {
if (axis == Axis.ATTRIBUTE || axis == Axis.CHILD || axis == Axis.NAMESPACE)
return en;
return null;
}
return null;
}
// moves to next element or attribute
private Boolean moveToNextInCurrentSequence(XdmSequenceIterator currentSequence)
{
if (currentSequence == null)
return false;
while (currentSequence.hasNext())
{
currentNode = currentSequence.next();
if (((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ELEMENT || ((XdmNode)currentNode).getNodeKind() == XdmNodeKind.ATTRIBUTE)
return true;
}
return false;
}
static class Node {
String name;
Class type;
String description;
public Node(String name, Class type, String description) {
this.name = name;
this.type = type;
this.description = description;
}
}
static class Element extends Node {
List<Element> children;
List<Attribute> attributes;
public Element(String name, Class type, String description) {
super(name, type, description);
children = new ArrayList<>();
attributes = new ArrayList<>();
}
public Element getChildByName(String name) {
for (Element child : children) {
if (child.name.equals(name))
return child;
}
return null;
}
public void addNewItems(Element child) {
for (Attribute attrAdd : child.attributes) {
boolean haveIt = false;
for (Attribute attrExist : attributes)
if (attrExist.name.equals(attrAdd.name)) {
haveIt = true;
break;
}
if (!haveIt)
attributes.add(attrAdd);
}
for (Element elemAdd : child.children) {
Element exist = null;
for (Element elemExist : children)
if (elemExist.name.equals(elemAdd.name)) {
exist = elemExist;
break;
}
if (exist == null)
children.add(elemAdd);
else
exist.addNewItems(elemAdd);
}
}
}
static class Attribute extends Node {
public Attribute(String name, Class type, String description) {
super(name, type, description);
}
}
}
XmlDatasource.java
import com.saxonica.config.EnterpriseConfiguration;
import com.saxonica.ee.s9api.SchemaValidatorImpl;
import net.sf.saxon.Configuration;
import net.sf.saxon.lib.FeatureKeys;
import net.sf.saxon.s9api.*;
import net.sf.saxon.type.SchemaException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class XmlDatasource {
/** the DOM all searches are against */
private XdmNode xmlRootNode;
private XPathCompiler xPathCompiler;
/** key == the prefix; value == the uri mapped to that prefix */
private HashMap<String, String> prefixToUriMap = new HashMap<>();
/** key == the uri mapped to that prefix; value == the prefix */
private HashMap<String, String> uriToPrefixMap = new HashMap<>();
public XmlDatasource (InputStream xmlData, InputStream schemaFile) throws SAXException, SchemaException, SaxonApiException, IOException {
boolean haveSchema = schemaFile != null;
// call this before any instantiation of Saxon classes.
Configuration config = createEnterpriseConfiguration();
if (haveSchema) {
Source schemaSource = new StreamSource(schemaFile);
config.addSchemaSource(schemaSource);
}
Processor processor = new Processor(config);
DocumentBuilder doc_builder = processor.newDocumentBuilder();
XMLReader reader = createXMLReader();
InputSource xmlSource = new InputSource(xmlData);
SAXSource saxSource = new SAXSource(reader, xmlSource);
if (haveSchema) {
SchemaValidator validator = new SchemaValidatorImpl(processor);
doc_builder.setSchemaValidator(validator);
}
xmlRootNode = doc_builder.build(saxSource);
xPathCompiler = processor.newXPathCompiler();
if (haveSchema)
xPathCompiler.setSchemaAware(true);
declareNameSpaces();
}
public XdmNode getXmlRootNode() {
return xmlRootNode;
}
public XPathCompiler getxPathCompiler() {
return xPathCompiler;
}
/**
* Create a XMLReader set to disallow XXE aattacks.
* #return a safe XMLReader.
*/
public static XMLReader createXMLReader() throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
// stop XXE https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
return reader;
}
private void declareNameSpaces() throws SaxonApiException {
// saxon has some of their functions set up with this.
prefixToUriMap.put("saxon", "http://saxon.sf.net");
uriToPrefixMap.put("http://saxon.sf.net", "saxon");
XdmValue list = xPathCompiler.evaluate("//namespace::*", xmlRootNode);
if (list == null || list.size() == 0)
return;
for (int index=0; index<list.size(); index++) {
XdmNode node = (XdmNode) list.itemAt(index);
String prefix = node.getNodeName() == null ? "" : node.getNodeName().getLocalName();
// xml, xsd, & xsi are XML structure ones, not ones used in the XML
if (prefix.equals("xml") || prefix.equals("xsd") || prefix.equals("xsi"))
continue;
// use default prefix if prefix is empty.
if (prefix == null || prefix.isEmpty())
prefix = "def";
// this returns repeats, so if a repeat, go on to next.
if (prefixToUriMap.containsKey(prefix))
continue;
String uri = node.getStringValue();
if (uri != null && !uri.isEmpty()) {
xPathCompiler.declareNamespace(prefix, uri);
prefixToUriMap.put(prefix, uri);
uriToPrefixMap.put(uri, prefix); }
}
}
public static EnterpriseConfiguration createEnterpriseConfiguration()
{
EnterpriseConfiguration configuration = new EnterpriseConfiguration();
configuration.supplyLicenseKey(new BufferedReader(new java.io.StringReader(deobfuscate(key))));
configuration.setConfigurationProperty(FeatureKeys.SUPPRESS_XPATH_WARNINGS, Boolean.TRUE);
return configuration;
}
}

Why does this priority queue implementation only print one value repeatedly?

This program should print out the values in order ascending order. But it only displays 957.0 repeatedly. How do I display the numbers in order?
import java.io.*;
import java.util.*;
class PriorityQ {
public int maxSize;
public double[] queArray;
public int nItems;
//------
public PriorityQ(int s){
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
//-----
public void insert(double item){
int j;
if(nItems == 0){
queArray[nItems++] = item;
}
else{
for(j = nItems-1; j >= 0; j--){
if(item > queArray[j]){
queArray[j + 1] = item;
}
else{
break;
}
}
queArray[j + 1] = item;
nItems++;
}
}
//-----
public double remove(){
return queArray[--nItems];
}
//-----
public double peekMin(){
return queArray[nItems - 1];
}
//-----
public boolean isEmpty(){
return(nItems == 0);
}
//-----
public boolean isFull(){
return(nItems == maxSize);
}
}
//-----
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(546);
thePQ.insert(687);
thePQ.insert(36);
thePQ.insert(98);
thePQ.insert(957);
while(!thePQ.isEmpty()){
double item = thePQ.remove();
System.out.print(item + " ");
}
System.out.println("");
}
}
You should save yourself the effort and use a priority queue with the generic type Double. If you wanted descending order you could even use a comparator that orders the highest value before the lowest, but you asked for ascending.
Your problem is that your array does contain many copies of 957.
This is because of this line in your code:
if(item > queArray[j]){
queArray[j + 1] = item;
}
Try:
import java.io.*;
import java.util.*;
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQueue<Double> thePQ = new PriorityQueue<Double>(5);
thePQ.add(546);
thePQ.add(687);
thePQ.add(36);
thePQ.add(98);
thePQ.add(957);
while(thePQ.size() > 0){
double item = thePQ.poll();
System.out.print(item + " ");
}
System.out.println("");
}
}
Or I can fix your code to print out the queue in descending order leaving it to you to then make it print out in ascending order, the block I pointed to before should read like this instead:
if(item < queArray[j]){
queArray[j + 1] = queArray[j];
}

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

Limited ListField items are drawn instead of complete list in 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;
}

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

Resources