Get data only one folder not for all folders in treeview - Blackberry - 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

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.

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

Xna (MonoGame) DynamicSoundEffectInstance Buffer already Full exception

I'm making this game in MonoGame (basically Xna) that uses DynamicSoundEffectInstance class. MonoGame does not have an implementation of DynamicSoundEffectInstance yet, so I made my own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if MONOMAC
using MonoMac.OpenAL;
#else
using OpenTK.Audio.OpenAL;
#endif
using System.Threading;
namespace Microsoft.Xna.Framework.Audio
{
public sealed class DynamicSoundEffectInstance : IDisposable
{
private const int BUFFERCOUNT = 2;
private SoundState soundState = SoundState.Stopped;
private AudioChannels channels;
private int sampleRate;
private ALFormat format;
private bool looped = false;
private float volume = 1.0f;
private float pan = 0;
private float pitch = 0f;
private int sourceId;
private int[] bufferIds;
private int[] bufferIdsToFill;
private int currentBufferToFill;
private bool isDisposed = false;
private bool hasSourceId = false;
private Thread bufferFillerThread = null;
// Events
public event EventHandler<EventArgs> BufferNeeded;
internal void OnBufferNeeded(EventArgs args)
{
if (BufferNeeded != null)
{
BufferNeeded(this, args);
}
}
public DynamicSoundEffectInstance(int sampleRate, AudioChannels channels)
{
this.sampleRate = sampleRate;
this.channels = channels;
switch (channels)
{
case AudioChannels.Mono:
this.format = ALFormat.Mono16;
break;
case AudioChannels.Stereo:
this.format = ALFormat.Stereo16;
break;
default:
break;
}
}
public bool IsDisposed
{
get
{
return isDisposed;
}
}
public float Pan
{
get
{
return pan;
}
set
{
pan = value;
if (hasSourceId)
{
// Listener
// Pan
AL.Source(sourceId, ALSource3f.Position, pan, 0.0f, 0.1f);
}
}
}
public float Pitch
{
get
{
return pitch;
}
set
{
pitch = value;
if (hasSourceId)
{
// Pitch
AL.Source(sourceId, ALSourcef.Pitch, XnaPitchToAlPitch(pitch));
}
}
}
public float Volume
{
get
{
return volume;
}
set
{
volume = value;
if (hasSourceId)
{
// Volume
AL.Source(sourceId, ALSourcef.Gain, volume * SoundEffect.MasterVolume);
}
}
}
public SoundState State
{
get
{
return soundState;
}
}
private float XnaPitchToAlPitch(float pitch)
{
// pitch is different in XNA and OpenAL. XNA has a pitch between -1 and 1 for one octave down/up.
// openAL uses 0.5 to 2 for one octave down/up, while 1 is the default. The default value of 0 would make it completely silent.
return (float)Math.Exp(0.69314718 * pitch);
}
public void Play()
{
if (!hasSourceId)
{
bufferIds = AL.GenBuffers(BUFFERCOUNT);
sourceId = AL.GenSource();
hasSourceId = true;
}
soundState = SoundState.Playing;
if (bufferFillerThread == null)
{
bufferIdsToFill = bufferIds;
currentBufferToFill = 0;
OnBufferNeeded(EventArgs.Empty);
bufferFillerThread = new Thread(new ThreadStart(BufferFiller));
bufferFillerThread.Start();
}
AL.SourcePlay(sourceId);
}
public void Apply3D(AudioListener listener, AudioEmitter emitter)
{
Apply3D(new AudioListener[] { listener }, emitter);
}
public void Pause()
{
if (hasSourceId)
{
AL.SourcePause(sourceId);
soundState = SoundState.Paused;
}
}
public void Apply3D(AudioListener[] listeners, AudioEmitter emitter)
{
// get AL's listener position
float x, y, z;
AL.GetListener(ALListener3f.Position, out x, out y, out z);
for (int i = 0; i < listeners.Length; i++)
{
AudioListener listener = listeners[i];
// get the emitter offset from origin
Vector3 posOffset = emitter.Position - listener.Position;
// set up orientation matrix
Matrix orientation = Matrix.CreateWorld(Vector3.Zero, listener.Forward, listener.Up);
// set up our final position and velocity according to orientation of listener
Vector3 finalPos = new Vector3(x + posOffset.X, y + posOffset.Y, z + posOffset.Z);
finalPos = Vector3.Transform(finalPos, orientation);
Vector3 finalVel = emitter.Velocity;
finalVel = Vector3.Transform(finalVel, orientation);
// set the position based on relative positon
AL.Source(sourceId, ALSource3f.Position, finalPos.X, finalPos.Y, finalPos.Z);
AL.Source(sourceId, ALSource3f.Velocity, finalVel.X, finalVel.Y, finalVel.Z);
}
}
public void Dispose()
{
if (!isDisposed)
{
Stop(true);
AL.DeleteBuffers(bufferIds);
AL.DeleteSource(sourceId);
bufferIdsToFill = null;
hasSourceId = false;
isDisposed = true;
}
}
public void Stop()
{
if (hasSourceId)
{
AL.SourceStop(sourceId);
int pendingBuffers = PendingBufferCount;
if(pendingBuffers > 0)
AL.SourceUnqueueBuffers(sourceId, PendingBufferCount);
if (bufferFillerThread != null)
bufferFillerThread.Abort();
bufferFillerThread = null;
}
soundState = SoundState.Stopped;
}
public void Stop(bool immediate)
{
Stop();
}
public TimeSpan GetSampleDuration(int sizeInBytes)
{
throw new NotImplementedException();
}
public int GetSampleSizeInBytes(TimeSpan duration)
{
int size = (int)(duration.TotalMilliseconds * ((float)sampleRate / 1000.0f));
return (size + (size & 1)) * 16;
}
public void SubmitBuffer(byte[] buffer)
{
this.SubmitBuffer(buffer, 0, buffer.Length);
}
public void SubmitBuffer(byte[] buffer, int offset, int count)
{
if (bufferIdsToFill != null) {
AL.BufferData (bufferIdsToFill [currentBufferToFill], format, buffer, count, sampleRate);
AL.SourceQueueBuffer (sourceId, bufferIdsToFill [currentBufferToFill]);
currentBufferToFill++;
if (currentBufferToFill >= bufferIdsToFill.Length)
bufferIdsToFill = null;
else
OnBufferNeeded (EventArgs.Empty);
} else {
throw new Exception ("Buffer already full.");
}
}
private void BufferFiller()
{
bool done = false;
while (!done)
{
var state = AL.GetSourceState(sourceId);
if (state == ALSourceState.Stopped || state == ALSourceState.Initial)
AL.SourcePlay(sourceId);
if (bufferIdsToFill != null)
continue;
int buffersProcessed;
AL.GetSource(sourceId, ALGetSourcei.BuffersProcessed, out buffersProcessed);
if (buffersProcessed == 0)
continue;
bufferIdsToFill = AL.SourceUnqueueBuffers(sourceId, buffersProcessed);
currentBufferToFill = 0;
OnBufferNeeded(EventArgs.Empty);
}
}
public bool IsLooped
{
get
{
return looped;
}
set
{
looped = value;
}
}
public int PendingBufferCount
{
get
{
if (hasSourceId)
{
int buffersQueued;
AL.GetSource(sourceId, ALGetSourcei.BuffersQueued, out buffersQueued);
return buffersQueued;
}
return 0;
}
}
}
}
Now, I followed this tutorial on making dynamic sounds in Xna, which worked with my custom MonoGame class. However, when I run the project (Xamarin Studio 4, Mac OS X 10.8, with MonoGame 3.0.1), it throws this exception:
Buffer already full
Pointing at the code in my custom class:
public void SubmitBuffer(byte[] buffer, int offset, int count)
{
if (bufferIdsToFill != null) {
AL.BufferData (bufferIdsToFill [currentBufferToFill], format, buffer, count, sampleRate);
AL.SourceQueueBuffer (sourceId, bufferIdsToFill [currentBufferToFill]);
currentBufferToFill++;
if (currentBufferToFill >= bufferIdsToFill.Length)
bufferIdsToFill = null;
else
OnBufferNeeded (EventArgs.Empty);
} else {
throw new Exception ("Buffer already full."); //RIGHT HERE IS THE EXCEPTION
}
}
I commented out the exception, and ran it again. It played the sound, with pops in it, but it still played it. How can I clear the buffer, so it is not full? I followed this tutorial EXACTLY, so all the code I added to my project is in there.
Oh! Figured it out myself; I changed the pending buffer count from 3 to 2. My final submit buffer code was:
while(_instance.PendingBufferCount < 2)
SubmitBuffer();
Where the 2 is, used to be a 3. Now it no longer throws the exception.

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

how to find the size of object stored (in bytes or kb,mb) on persistence store in 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).

Resources