Blackberry custombutton on touch/trackpad frozen screen - blackberry

I created a sort of a grid with multiple vertical and horizontal fieldmanagers.
The code to create the grid is:
public class CategoriasScreen extends MainScreen {
private int colores [] = {Color.BLUE, Color.ALICEBLUE, Color.CHOCOLATE, Color.DARKORANGE, Color.YELLOW};
private int rows;
public CategoriasScreen(){
VerticalFieldManager row;
CategoriaFieldManager cat;
HorizontalFieldManager par;
EncodedImage eImage;
LabelField lf;
rows = 1;
Font font = getFont().derive(Font.PLAIN, Font.getDefault().getHeight() - 8);
setTitle("Categorias");
for(int i = 0; i < rows; i++){
row = new VerticalFieldManager(Field.FIELD_VCENTER | Manager.USE_ALL_WIDTH | Field.NON_FOCUSABLE);
par = new HorizontalFieldManager(Field.FIELD_HCENTER | Field.NON_FOCUSABLE);
cat = new CategoriaFieldManager(i);
eImage = EncodedImage.getEncodedImageResource("img/categoria" + i +".png");
eImage = LoaderScreen.resize(eImage, (int) Display.getWidth() / 5, (int) Display.getHeight() / 5, true);
cat.add(new BitmapField(eImage.getBitmap()));
lf = new LabelField("Categoria " + i, Field.FIELD_HCENTER);
lf.setFont(font);
cat.add(lf);
par.add(cat);
cat = new CategoriaFieldManager(i + 2);
eImage = EncodedImage.getEncodedImageResource("img/categoria" + (i + 2) +".png");
eImage = LoaderScreen.resize(eImage, (int) Display.getWidth() / 5, (int) Display.getHeight() / 5, true);
cat.add(new BitmapField(eImage.getBitmap()));
lf = new LabelField("Categoria " + (i + 2), Field.FIELD_HCENTER);
lf.setFont(font);
cat.add(lf);
par.add(cat);
row.add(par);
add(row);
//add(cat);
}
}
}
For the element inside the grid i extended a VerticalFieldManager and implemented the FieldChangeListener:
public class CategoriaFieldManager extends VerticalFieldManager implements FieldChangeListener{
private int colores [] = {Color.BLUE, Color.ALICEBLUE, Color.CHOCOLATE, Color.DARKORANGE, Color.YELLOW};
private int _idCategoria;
public CategoriaFieldManager(int idCategoria){
super(Field.FOCUSABLE);
_idCategoria = idCategoria;
setBackground(BackgroundFactory.createSolidBackground(colores[0]));
this.setPadding(new XYEdges(15,30,10,30));
this.setBorder(BorderFactory.createSimpleBorder(new XYEdges(20,20,20,20), Border.STYLE_TRANSPARENT));
//cat.setCookie(new Integer(i));
this.setChangeListener(this);
}
protected void sublayout(int width, int height){
super.sublayout((int) Display.getWidth() / 5 , (int) Display.getWidth() / 5);
setExtent((int) Display.getWidth() / 5, (int) Display.getWidth() / 5);
}
protected void onFocus(int direction){
setBackground(BackgroundFactory.createSolidBackground(colores[1]));
}
protected void onUnfocus(){
setBackground(BackgroundFactory.createSolidBackground(colores[0]));
}
public boolean isFocusable(){
return true;
}
protected boolean touchEvent( TouchEvent message ) {
int x = message.getX( 1 );
int y = message.getY( 1 );
if( x < 0 || y < 0 || x > getExtent().width || y > getExtent().height ) {
// Outside the field
return false;
}
switch( message.getEvent() ) {
case TouchEvent.UNCLICK:
fieldChangeNotify(0);
return true;
}
return super.touchEvent( message );
}
protected boolean navigationClick(int status, int time) {
if (status != 0) { // you did not have this check
fieldChangeNotify(0);
}
return true;
}
public void fieldChanged(Field field, int context) {
UiApplication.getUiApplication().pushScreen( new ListadoEstablecimientosScreen(_idCategoria) );
/*UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run() {
Dialog.alert("hola mundo");
}
});*/
}
}
The problem that I've found is that when I touch the screen (anywhere) and then use the trackpad the phone freezes, I have to restart it to use it again. Then comes a notification that says the application was using too many resources. If it helps I've been testing in a BlackBerry Bold 9900

Related

Increase LabelField value as slider is moved

I have created a SliderField class in order to show a drag-able slider in my BlackBerry application. The slider is basically used to set interval for location updates (via GPS) in the app. The app is built on OS 5.0 and so no API was found for the SliderField. The problem
I am facing is that I need to increase the integer value in a label as the slider is moved. For instance, if the integer value in a label is 1 and the user moves the slider the value should increase to 5,10,15 etc. I do not know how to link moving the slider to increasing the value in the label field. Can anyone please help? I am adding the SliderField object to the screen as below:
Bitmap sliderBack = Bitmap.getBitmapResource( "progress51.png" );
Bitmap sliderFocus = Bitmap.getBitmapResource( "progress51.png" );
Bitmap sliderThumb = Bitmap.getBitmapResource( "butt.png" );
SliderField theSlider = new SliderField( sliderThumb, sliderBack, sliderFocus,20, 1, 1, 1 );
secondHFM.add(theSlider)
Below is my code for the SliderField class.
public class SliderField extends Field
{
Bitmap _imageThumb;
Bitmap _imageSlider;
Bitmap _imageSliderLeft;
Bitmap _imageSliderCenter;
Bitmap _imageSliderRight;
Bitmap _imageSliderFocus;
Bitmap _imageSliderFocusLeft;
Bitmap _imageSliderFocusCenter;
Bitmap _imageSliderFocusRight;
private int _numStates;
private int _currentState;
private boolean _selected;
private int _xLeftBackMargin;
private int _xRightBackMargin;
private int _thumbWidth;
private int _thumbHeight;
private int _totalHeight;
private int _totalWidth;
private int _rop;
private int _backgroundColours[];
private int _backgroundSelectedColours[];
private int _defaultSelectColour = 0x977DED;
private int _defaultBackgroundColour = 0x000000;
private int _defaultHoverColour = 0x999999;
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin )
{
this( thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin
, long style )
{
this( thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, style );
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, Bitmap sliderBackgroundFocus
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin )
{
this( thumb, sliderBackground, sliderBackgroundFocus, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, Bitmap sliderBackgroundFocus
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin
, long style )
{
super( style );
if( initialState > numStates || numStates < 2 ){
}
_imageThumb = thumb;
_imageSlider = sliderBackground;
_imageSliderFocus = sliderBackgroundFocus;
_numStates = numStates;
setState( initialState );
_xLeftBackMargin = xLeftBackMargin;
_xRightBackMargin = xRightBackMargin;
_rop = _imageSlider.hasAlpha() ? Graphics.ROP_SRC_ALPHA : Graphics.ROP_SRC_COPY;
_thumbWidth = thumb.getWidth();
_thumbHeight = thumb.getHeight();
initBitmaps();
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin
, int[] colours
, int[] selectColours )
{
this(thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
if( colours.length != numStates+1 ){
throw new IllegalArgumentException();
}
_backgroundColours = colours;
_backgroundSelectedColours = selectColours;
}
public void initBitmaps()
{
int height = _imageSlider.getHeight();
_imageSliderLeft = new Bitmap( _xLeftBackMargin, height );
_imageSliderCenter = new Bitmap( _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height);
_imageSliderRight = new Bitmap( _xRightBackMargin, height );
copy( _imageSlider, 0, 0, _xLeftBackMargin, height, _imageSliderLeft );
copy( _imageSlider, _xLeftBackMargin, 0, _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height, _imageSliderCenter);
copy( _imageSlider, _imageSlider.getWidth() - _xRightBackMargin, 0, _xRightBackMargin, height, _imageSliderRight);
_imageSliderFocusLeft = new Bitmap( _xLeftBackMargin, height );
_imageSliderFocusCenter = new Bitmap( _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height);
_imageSliderFocusRight = new Bitmap( _xRightBackMargin, height );
copy( _imageSliderFocus, 0, 0, _xLeftBackMargin, height, _imageSliderFocusLeft );
copy( _imageSliderFocus, _xLeftBackMargin, 0, _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height, _imageSliderFocusCenter);
copy( _imageSliderFocus, _imageSlider.getWidth() - _xRightBackMargin, 0, _xRightBackMargin, height, _imageSliderFocusRight);
}
private void copy(Bitmap src, int x, int y, int width, int height, Bitmap dest) {
int[] argbData = new int[width * height];
src.getARGB(argbData, 0, width, x, y, width, height);
for(int tx = 0; tx < dest.getWidth(); tx += width) {
for(int ty = 0; ty < dest.getHeight(); ty += height) {
dest.setARGB(argbData, 0, width, tx, ty, width, height);
}
}
}
public void setState(int newState) {
if( newState > _numStates ){
throw new IllegalArgumentException();
} else {
_currentState = newState;
invalidate();
}
}
public int getState() {
return _currentState;
}
public int getNumStates() {
return _numStates;
}
public int getColour() {
if(_backgroundSelectedColours != null) {
return _backgroundSelectedColours[getState()];
}
return 0x000000;
}
public int getPreferredWidth() {
return _totalWidth;
}
public int getPreferredHeight() {
return _totalHeight;
}
protected void layout( int width, int height ) {
if (width < 0 || height < 0)
throw new IllegalArgumentException();
_totalWidth = width;
_totalHeight = Math.max(_imageSlider.getHeight(), _imageThumb.getHeight());
setExtent( _totalWidth, _totalHeight );
}
public void paint( Graphics g )
{
int sliderHeight = _imageSlider.getHeight();
int sliderBackYOffset = ( _totalHeight - sliderHeight ) >> 1;
int backgroundColor = _defaultBackgroundColour;
if( _backgroundSelectedColours != null || _backgroundColours != null ) {
if( _selected ) {
backgroundColor = _backgroundSelectedColours != null ? _backgroundSelectedColours[getState()] : _defaultSelectColour;
} else if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {
backgroundColor = _backgroundColours != null ? _backgroundColours[getState()] : _defaultHoverColour;
} else {
backgroundColor = _defaultBackgroundColour;
}
}
g.setColor( backgroundColor );
g.fillRect( 1, sliderBackYOffset + 1, _totalWidth - 2, sliderHeight - 2 );
if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {
paintSliderBackground( g, _imageSliderFocusLeft, _imageSliderFocusCenter, _imageSliderFocusRight );
} else {
paintSliderBackground( g, _imageSliderLeft, _imageSliderCenter, _imageSliderRight );
}
int thumbXOffset = ( ( _totalWidth - _thumbWidth ) * _currentState ) / _numStates;
g.drawBitmap( thumbXOffset, ( _totalHeight - _thumbHeight ) >> 1, _thumbWidth, _thumbHeight, _imageThumb, 0, 0 );
}
private void paintSliderBackground( Graphics g, Bitmap left, Bitmap middle, Bitmap right )
{
int sliderHeight = _imageSlider.getHeight();
int sliderBackYOffset = ( _totalHeight - sliderHeight ) >> 1;
g.drawBitmap( 0, sliderBackYOffset, _xLeftBackMargin, sliderHeight, left, 0, 0 );
g.tileRop( _rop, _xRightBackMargin, sliderBackYOffset, _totalWidth - _xLeftBackMargin - _xRightBackMargin, sliderHeight, middle, 0, 0 );
g.drawBitmap( _totalWidth - _xRightBackMargin, sliderBackYOffset, _xRightBackMargin, sliderHeight, right, 0, 0 );
}
public void paintBackground( Graphics g )
{
}
protected void drawFocus( Graphics g, boolean on )
{
boolean oldDrawStyleFocus = g.isDrawingStyleSet( Graphics.DRAWSTYLE_FOCUS );
try {
if( on ) {
g.setDrawingStyle( Graphics.DRAWSTYLE_FOCUS, true );
}
paint( g );
} finally {
g.setDrawingStyle( Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus );
}
}
protected boolean touchEvent(TouchEvent message)
{
boolean isConsumed = false;
boolean isOutOfBounds = false;
int x = message.getX(1);
int y = message.getY(1);
if(x < 0 || y < 0 || x > getExtent().width || y > getExtent().height) {
isOutOfBounds = true;
}
switch(message.getEvent()) {
case TouchEvent.CLICK:
case TouchEvent.MOVE:
if(isOutOfBounds) return true;
_selected = true;
int stateWidth = getExtent().width / _numStates;
int numerator = x / stateWidth;
int denominator = x % stateWidth;
if( denominator > stateWidth / 2 ) {
numerator++;
}
_currentState = numerator;
invalidate();
isConsumed = true;
break;
case TouchEvent.UNCLICK:
if(isOutOfBounds) {
_selected = false;
return true;
}
_selected = false;
stateWidth = getExtent().width / _numStates;
numerator = x / stateWidth;
denominator = x % stateWidth;
if( denominator > stateWidth / 2 ) {
numerator++;
}
_currentState = numerator;
invalidate();
fieldChangeNotify(0);
isConsumed = true;
break;
}
return isConsumed;
}
protected boolean navigationMovement(int dx, int dy, int status, int time)
{
if( _selected )
{
if(dx > 0 || dy > 0) {
incrementState();
fieldChangeNotify( 0 );
return true;
} else if(dx < 0 || dy < 0) {
decrementState();
fieldChangeNotify( 0 );
return true;
}
}
return super.navigationMovement( dx, dy, status, time);
}
public void decrementState() {
if(_currentState > 0) {
_currentState--;
invalidate();
}
}
public void incrementState() {
if(_currentState < _numStates) {
_currentState++;
invalidate();
}
}
protected boolean invokeAction(int action) {
switch(action) {
case ACTION_INVOKE: {
toggleSelected();
return true;
}
}
return false;
}
protected boolean keyChar( char key, int status, int time ) {
if( key == Characters.SPACE || key == Characters.ENTER ) {
toggleSelected();
return true;
}
return false;
}
protected boolean trackwheelClick( int status, int time ) {
if( isEditable() ) {
toggleSelected();
return true;
}
return super.trackwheelClick(status, time);
}
private void toggleSelected() {
_selected = !_selected;
invalidate();
}
public void setDirty( boolean dirty )
{
}
public void setMuddy( boolean muddy )
{
}
}
If you use the code below, you will get your actual requirement,you can get the slider current value into your screen class by invoking getValue() method on sliderfield reference..
Implement FieldChangeListener interface and try to override fieldChanged() method.
Use HorizontalFieldManager class and setStatus() method,
if you want to display your slider bar at bottom of your screen,other wise you can display it normally.
Here the Code:
public class SliderScreen extends MainScreen implements FieldChangeListener
{
private SliderField slider;
private HorizontalFieldManager hm;
public SliderField(){
slider = new SliderField(
Bitmap.getBitmapResource("slider2_thumb_normal.png"),
Bitmap.getBitmapResource("slider2_progress_normal.png"),
Bitmap.getBitmapResource("slider2_base_normal.png"),
Bitmap.getBitmapResource("slider2_thumb_focused.png"),
Bitmap.getBitmapResource("slider2_progress_focused.png"),
Bitmap.getBitmapResource("slider2_base_focused.png"), 8, 4,
8, 8, FOCUSABLE);
slider.setChangeListener(this);
hm = new HorizontalFieldManager();
hm.add(slider);
setStatus(hm);
}
public void fieldChanged(Field field, int context) {
try {
if (field == slider) {
int value = slider.getValue();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
I have done simple example of how to use this code,Check it
public final class MyScreen extends MainScreen implements FieldChangeListener//,FocusChangeListener
{
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
SliderField slider;
slider = new SliderField(
Bitmap.getBitmapResource( "slider_thumb_normal.png" ), Bitmap.getBitmapResource( "slider_progress_normal.png" ), Bitmap.getBitmapResource( "slider_base_normal.png" ),
Bitmap.getBitmapResource( "slider_thumb_focused.png" ), Bitmap.getBitmapResource( "slider_progress_focused.png" ), Bitmap.getBitmapResource( "slider_base_focused.png"),
Bitmap.getBitmapResource( "slider_thumb_pressed.png" ), Bitmap.getBitmapResource( "slider_progress_pressed.png" ), Bitmap.getBitmapResource( "slider_base_pressed.png"),
10, 0, 12, 12, FOCUSABLE );
slider.setPadding( 20, 20, 20, 20 );
slider.setBackground( BackgroundFactory.createSolidBackground( 0xD3D3D3 ) );
slider.setChangeListener(this);
//slider.focusChangeNotify(0);
add( slider );
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if(field instanceof SliderField)
{
SliderField temp = (SliderField)field;
System.out.println("Temp value is"+temp.getValue());
}
}
}

How to custom go newline when calling drawtext()?

This is a listfield.
public class Custom_ListField extends ListField {
private String[] title, category, date, imagepath;
private int[] newsid, catsid;
private List_News newslist;
private Bitmap imagebitmap[], localimage = Bitmap
.getBitmapResource("image_base.png");
private BrowserField webpage;
private Custom_BrowserFieldListener listener;
private boolean islatest;
private Vector content = null;
private ListCallback callback = null;
private int currentPosition = 0;
public Custom_ListField(Vector content, boolean islatest) {
this.content = content;
this.islatest = islatest;
newsid = new int[content.size()];
title = new String[content.size()];
category = new String[content.size()];
date = new String[content.size()];
imagepath = new String[content.size()];
catsid = new int[content.size()];
imagebitmap = new Bitmap[content.size()];
for (int i = 0; i < content.size(); i++) {
newslist = (List_News) content.elementAt(i);
newsid[i] = newslist.getID();
title[i] = newslist.getNtitle();
category[i] = newslist.getNewCatName();
date[i] = newslist.getNArticalD();
imagepath[i] = newslist.getImagePath();
if (!imagepath[i].toString().equals("no picture")) {
imagebitmap[i] = Util_ImageLoader.loadImage(imagepath[i]);
} else {
imagebitmap[i] = localimage;
}
catsid[i] = newslist.getCatID();
}
initCallbackListening();
this.setRowHeight(localimage.getHeight() + 10);
}
private void initCallbackListening() {
callback = new ListCallback();
this.setCallback(callback);
}
private class ListCallback implements ListFieldCallback {
public ListCallback() {
setBackground(Config_GlobalFunction
.loadbackground("background.png"));
}
public void drawListRow(ListField listField, Graphics graphics,
int index, int y, int width) {
currentPosition = index;
graphics.drawBitmap(
Display.getWidth() - imagebitmap[index].getWidth() - 5,
y + 3, imagebitmap[index].getWidth(),
imagebitmap[index].getHeight(), imagebitmap[index], 0, 0);
graphics.setColor(Color.WHITE);
graphics.drawRect(0, y, width, imagebitmap[index].getHeight() + 10);
graphics.setColor(Color.BLACK);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 20));
graphics.drawText(title[index], 5, y + 3, 0, Display.getWidth()
- imagebitmap[index].getWidth() - 10);
graphics.setColor(Color.GRAY);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 15));
graphics.drawText(date[index], 5, y + 6
+ Font.getDefault().getHeight() + 3);
if (islatest) {
graphics.setColor(Color.RED);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 15));
graphics.drawText(category[index], Font.getDefault()
.getAdvance(date[index]) + 3, y + 6
+ Font.getDefault().getHeight() + 3);
}
}
public Object get(ListField listField, int index) {
return content.elementAt(index);
}
public int getPreferredWidth(ListField listField) {
return Display.getWidth();
}
public int indexOfList(ListField listField, String prefix, int start) {
return content.indexOf(prefix, start);
}
}
public int getCurrentPosition() {
return currentPosition;
}
protected boolean navigationClick(int status, int time) {
int index = getCurrentPosition();
if (catsid[index] == 9) {
if (Config_GlobalFunction.isConnected()) {
webpage = new BrowserField();
listener = new Custom_BrowserFieldListener();
webpage.addListener(listener);
MainScreen aboutus = new Menu_Aboutus();
aboutus.add(webpage);
Main.getUiApplication().pushScreen(aboutus);
webpage.requestContent("http://www.orientaldaily.com.my/index.php?option=com_k2&view=item&id="
+ newsid[index] + ":&Itemid=223");
} else
Config_GlobalFunction.Message(Config_GlobalFunction.nowifi, 1);
} else
Main.getUiApplication().pushScreen(
new Main_NewsDetail(newsid[index]));
return true;
}
}
Please look at the
graphics.setColor(Color.BLACK);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 20));
graphics.drawText(title[index], 5, y + 3, 0, Display.getWidth()
- imagebitmap[index].getWidth() - 10);
This will only draw the text one line only. I did researched and found out there isn't built in function and must custom a function make the text auto next line.
The function something like this
private int numberoflines(int availablespace){
...
return numberlines
}
The links Rupak shows are good, although one of them references the generic Java problem (and proposes a Swing result that would need to be changed for BlackBerry), and the other references an external (non stack overflow) link.
If you want another option, and don't want the algorithm to figure out where to make the line breaks, you can use this. This code assumes you put '\n' characters into your strings, where you want to split the text into multiple lines. You would probably put this code in the paint() method:
// store original color, to reset it at the end
int oldColor = graphics.getColor();
graphics.setColor(Color.BLACK);
graphics.setFont(_fieldFont);
int endOfLine = _text.indexOf('\n');
if (endOfLine < 0) {
graphics.drawText(_text, _padding, _top);
} else {
// this is a multi-line label
int top = _top;
int index = 0;
int textLength = _text.length();
while (index < textLength) {
// draw one line at a time
graphics.drawText(_text,
index, // offset into _text
endOfLine - index, // number of chars to draw
_padding, // x
top, // y
(int) (DrawStyle.HCENTER | DrawStyle.TOP | Field.USE_ALL_WIDTH), // style flags
_fieldWidth - 2 * _padding); // width available
index = endOfLine + 1;
endOfLine = _text.indexOf('\n', index);
if (endOfLine < 0) {
endOfLine = textLength;
}
top += _fieldFont.getHeight() + _top; // top padding is set equal to spacing between lines
}
}
graphics.setColor(oldColor);
And here you would initialize some of the variables I use in that. I think these are right, based on the code you posted, but you'll need to double-check:
String _text = title[index]; // text to draw
int _padding = 5; // left and right side padding around text
int _top = y + 3; // the y coordinate of the top of the text
Font _fieldFont = Font.getDefault().derive(Font.BOLD, 20);
// the total width reserved for the text, which includes room for _padding:
int _fieldWidth = Display.getWidth() - imagebitmap[index].getWidth();

Not able to show the events against same time one after other in horizontal manager in Blackberry

I am trying to get events from Blackberry Calendar. I am trying to show the events occurring at the same time one after other
like
8:00 e1
8:00 e2
as in native Calendar
But the following code shows the output as
8:00 e1 e2
in my code i have 24 hfm added to single vfm.
int size1 = 2;
horizontalFieldManager_left22 = new HorizontalFieldManager[size1];
for (int y = 0; y < size1; y++) {
horizontalFieldManager_left22[y] = new HorizontalFieldManager() {
protected boolean navigationClick(int status, int time) {
Field field = getFieldWithFocus();
Vector data = getData(listEvent);
String currentData = desc22.getText();
String currentTime = time22.getText();
if (currentData != null && currentData != "") {
UiApplication.getUiApplication().pushScreen(new EventScreen(data,currentData,currentTime));
}
return super.navigationClick(status, time);
}
protected boolean keyChar (char key, int status, int time) {
Field field = getFieldWithFocus();
return
super.keyChar(key, status, time);
}
};
int size = eventVector7.size();
LabelField[] labelField = new
LabelField[size];
for (int x = 0; x < eventVector7.size(); x++) {
labelField[x] = new
LabelField("", Field.FOCUSABLE);
String data = (String)
eventVector7.elementAt(x);
labelField[x].setText(data);
horizontalFieldManager_left22[y].add(time22);
horizontalFieldManager_left22[y].add(min22);
horizontalFieldManager_left22[y].add(new LabelField(" "));
horizontalFieldManager_left22[y].add(labelField[x]);
}
}
for (int z = 0; z < size1; z++) {
vfm.add(horizontalFieldManager_left22 [z]);
vfm.add(new SeparatorField());
}
import java.util.Hashtable;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class ListAllEvents extends MainScreen {
// -----------------------------------------------------------------
VerticalFieldManager mainManager;
VerticalFieldManager listVFM;
HorizontalFieldManager rowHFM[];
int row_height;
LabelField[] eventTimeLabel;
LabelField[] eventNameLabel;
public ListAllEvents() {
createUI();
createEventHashtable();
}
// -------------- Create UI --------------------------------
public void createUI() {
mainManager = new VerticalFieldManager(
VerticalFieldManager.VERTICAL_SCROLL
| VerticalFieldManager.VERTICAL_SCROLLBAR
| VerticalFieldManager.USE_ALL_HEIGHT
| VerticalFieldManager.FIELD_LEFT | DrawStyle.LEFT) {
protected void sublayout(int maxWidth, int maxHeight) {
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight();
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.WHITE);
g.clear();
super.paint(g);
}
};
add(mainManager);
}
// ----------------------------Create List
// ----------------------------------------
public void createList(Hashtable eventHashtable) {
listVFM = new VerticalFieldManager();
rowHFM = new HorizontalFieldManager[eventHashtable.size()];
eventTimeLabel = new LabelField[eventHashtable.size()];
eventNameLabel = new LabelField[eventHashtable.size()];
row_height = 90;
int j = 0;
int row_count = 0;
if (eventHashtable.size() > 0) {
EventItem ei = null;
for (int i = 0; i < eventHashtable.size(); i++) {
Object obj = eventHashtable.get(new Integer(i));
final EventItem item = (EventItem) obj;
if (item != null) {
String str_event_time = item.event_time;
String str_event_name = item.event_name;
rowHFM[row_count] = new HorizontalFieldManager(
HorizontalFieldManager.USE_ALL_HEIGHT) {
protected void sublayout(int maxWidth, int maxHeight) {
int displayWidth = Display.getWidth();
int displayHeight = 80;
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
rowHFM[row_count].setPadding(2, 2, 2, 2);
eventTimeLabel[row_count] = new LabelField(str_event_time) {
protected void layout(int maxWidth, int maxHeight) {
int displayWidth = (int) (Display.getWidth() / 2);
int displayHeight = maxHeight;
super.layout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
eventTimeLabel[row_count].setPadding(5, 0, 0, 2);
eventNameLabel[row_count] = new LabelField(str_event_name) {
protected void layout(int maxWidth, int maxHeight) {
int displayWidth = (int) (Display.getWidth() / 2);
int displayHeight = maxHeight;
super.layout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
eventNameLabel[row_count].setPadding(5, 0, 0, 2);
rowHFM[row_count].add(eventTimeLabel[row_count]);
rowHFM[row_count].add(eventNameLabel[row_count]);
listVFM.add(rowHFM[row_count]);
}
}
}
listVFM.setPadding(5, 2, 5, 2);
mainManager.add(listVFM);
}
public void createEventHashtable() {
String event_time1 = "8:00";
String event_time2 = "8:00";
String event_name1 = "Event 1";
String event_name2 = "Event 2";
Hashtable eventHashtable = new Hashtable();
eventHashtable.put(new Integer(0), new EventItem(event_time1,
event_name1));
eventHashtable.put(new Integer(1), new EventItem(event_time2,
event_name2));
createList(eventHashtable);
}
}
public class EventItem {
String event_time;
String event_name;
public EventItem(String event_time, String event_name) {
this.event_name = event_name;
this.event_time = event_time;
}
}

blackberry lazyloading in clumsy layout

I am using a customlistfield by extending VerticalFieldManager, and for the row I am usingf another CustoRowManager that extends Manager. The CustomRowManager has 2 TextField and a BitmapField . This list is implemented for a live xml feed. For loading the bitmapfield I am displaying placeholders which is then replaced by the actual image from background thread. I am not able to figure out how I should replace place holders with the bitmapfield. using invalidate() is one option, but on which element I should perform it.
public class CustomList extends VerticalFieldManager{
private int totalHeight = 0;
private int screenHeight = 0;
private int scrollPosition = 0;
protected void sublayout(int width, int height)
{
width = 480;
height = 230;
super.sublayout(width,height);
setExtent(width, height);
}
protected boolean navigationClick(int status, int time)
{
int index;
System.out.println("CLICKED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if ((status & KeypadListener.STATUS_FOUR_WAY) == KeypadListener.STATUS_FOUR_WAY)
{
index = this.getFieldWithFocusIndex();
UiApplication.getUiApplication().pushScreen(new TopNewsScreen(_vec, index));
}
return true;
}
Bitmap _bmp = null;
BitmapField _bmF = null;
Object _Obj = null;
TopNews _topNews = null;
String _headStr = null, _metaStr = null;
CustTextField _headNews = null, _metaData = null;
CustomRow _custRow = null;
Vector _vec;
public CustomList(Vector _vec,long _property)
{
super(_property);
this._vec = new Vector();
this._vec = _vec;
int _size = _vec.size();
int i ;
for(i = 0; i <_size; i++)
{
_headStr = new String();
_metaStr = new String();
_bmp = Bitmap.getBitmapResource("img/1.jpg");
_bmF = new BitmapField(_bmp);
_topNews = (TopNews)_vec.elementAt(i);
_headStr = _topNews.getHeadline();
_metaStr = _topNews.getMetaData();
int _newsLeng = _headStr.length(), alert = 0;
if(_newsLeng <= 35)
{
alert = 0;
}else if(_newsLeng>35&&_newsLeng<=70)
{
alert = 1;
}else {
alert = 2;
_headStr = this.truncate(_headStr,70);
}
_custRow = new CustomRow(alert);
_headNews = new CustTextField(_headStr,25,0x05235b,TextField.NON_FOCUSABLE);
_metaData = new CustTextField(_metaStr,15,0x666666,TextField.NON_FOCUSABLE);
_custRow.add(_headNews);
_custRow.add(_metaData);
_custRow.add(_bmF);
super.add(_custRow);
}
}
String truncate(String value, int length)
{
if (value != null && value.length() > length)
value = value.substring(0, length);
return value;
}
}
class CustomRow extends Manager implements FocusChangeListener{
private int _headLeng;
private NullField _focus = null;
CustomRow(int _headLeng)
{
super(Manager.FOCUSABLE|
Manager.NO_HORIZONTAL_SCROLL
|Manager.NO_VERTICAL_SCROLL);
this._headLeng = _headLeng;
_focus = new NullField(NullField.FOCUSABLE);
_focus.setFocusListener(CustomRow.this);
this.add(_focus);
}
protected void sublayout(int width, int height)
{
if(_headLeng==0)
{
layoutChild(getField(0),0,0);
setPositionChild(getField(0),0 , 0);
layoutChild(getField(1),360,20);
setPositionChild(getField(1),10 , 10);
layoutChild(getField(2),300, 20);
setPositionChild(getField(2), 10, 65);
layoutChild(getField(3),90,65);
setPositionChild(getField(3), 380, 10);
}else
{
/* layoutChild(getField(0),0,0);
setPositionChild(getField(0),0 , 0);
layoutChild(getField(1),360,20);
setPositionChild(getField(1),10 , 10);
layoutChild(getField(2),300, 20);
setPositionChild(getField(2), 10, 50);
layoutChild(getField(3),90,65);
setPositionChild(getField(3), 380, 10); */
layoutChild(getField(0),0,0);
setPositionChild(getField(0),0 , 0);
layoutChild(getField(1),360,20);
setPositionChild(getField(1),10 , 10);
layoutChild(getField(2),300, 20);
setPositionChild(getField(2), 10, 65);
layoutChild(getField(3),90,65);
setPositionChild(getField(3), 380, 10);
}
height = 80;
width = 480;
setExtent(width, height);
}
protected void paint(Graphics graphics)
{
graphics.setColor(Color.GRAY);
graphics.drawLine(10, 79, Display.getWidth()-10, 79);
super.paint(graphics);
}
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
this.getManager().invalidate();
}
protected void paintBackground(Graphics g) {
int prevBg = g.getBackgroundColor();
if (_focus.isFocus()) {
g.setBackgroundColor(Color.LIGHTBLUE);
} else {
g.setBackgroundColor(Color.WHITE);
}
g.clear();
g.setBackgroundColor(prevBg);
}
}
the below link has answer for the question, I should change the name to Blackberry lazyloading.
http://supportforums.blackberry.com/t5/Java-Development/Clumsy-layout-invalidate/m-p/1398763

2nd Line is not getting displayed in the ListField (text wrapping is not happening) ... please advice

Here is the sample code:
class MailBoxSampleListField extends MainScreen implements FolderListener, StoreListener {
private static final int COLUMN_WIDTH_STATUS = 10;
private static final int COLUMN_WIDTH_DATE = 150;
private static final int COLUMN_WIDTH_NAME = 150;
public ListField myList;
private ListCallback myCallback;
public Vector sampleList = new Vector();
public Vector sampleVector;
private class ListCallback implements ListFieldCallback {
public Vector myVector = new Vector();
public Bitmap LIST_IMAGE = Bitmap.getBitmapResource("New.PNG");
public void drawListRow (ListField list, Graphics g, int index, int y,int w) {
displayList(g,0,y,w,(( Message )myVector.elementAt( index )), LIST_IMAGE); // for drawing the list row
for( int ii = 0; ii < sampleVector.size(); ii++) {
String text = ( String )sampleVector.elementAt(ii);
int liney = y + ( ii * list.getFont().getHeight() );
g.drawText( text, LIST_IMAGE.getWidth() + 5, liney, Graphics.ELLIPSIS, w );
}
}
public Object get( ListField list, int index ) {
return myVector.elementAt(index);
}
public int indexOfList( ListField list,String p, int s ) {
return myVector.indexOf(p,s);
}
public int getPreferredWidth ( ListField list ) {
return Graphics.getScreenWidth();
}
public void insert(Message _message, int index) {
myVector.addElement(_message);
}
public void erase () {
myVector.removeAllElements();
}
}
MailBoxSampleListField() {
ListCallback myCallback = new ListCallback();
try {
Store store = null;
store = Session.getDefaultInstance().getStore();
store.addStoreListener( this );
// retrieve Folder object fow which we want to receive message notification
try {
Folder[] folders = store.list();
Folder[] f1 = store.findFolder( "inbox" );
Folder vinbox = f1[0];
for (int i =0; i < f1.length; i++) {
f1[i].addFolderListener( this );
}
Message[] vmessages = vinbox.getMessages();
for ( int j = 0; j < vmessages.length; ++j ) {
if(vmessages[j] != null){
sampleList.addElement( vmessages[j] );
}
}
myList = new ListField(); // initialize the ListField
for ( int k = 0; k < sampleList.size(); k++ ) {
myList.insert(k);
myCallback.insert(vmessages[k], k);
}
myList.setCallback( myCallback );
add( myList );
}
catch( Exception e ){
}
}
catch ( Exception se ) {
}
}
public void displayList( Graphics g, int x, int y, int width, Message _message, Bitmap LIST_IMAGE ) {
g.drawBitmap(0, y, LIST_IMAGE.getWidth(), LIST_IMAGE.getHeight(), LIST_IMAGE, 0, 0);
sampleVector = new Vector();
Date d = _message.getReceivedDate();
Calendar c = Calendar.getInstance();
c.setTime(d);
StringBuffer sb = new StringBuffer();
sb.append( c.get( Calendar.MONTH ) );
sb.append('-');
int digit = c.get( Calendar.DAY_OF_MONTH );
if ( digit < 10 ) sb.append(0);
sb.append( digit );
sb.append(' ');
sb.append( c.get( Calendar.HOUR_OF_DAY ) );
sb.append(':');
digit = c.get( Calendar.MINUTE );
if ( digit < 10 ) sb.append( 0 );
sb.append( digit );
sb.append( ' ');
x += LIST_IMAGE.getWidth()+5;
x += COLUMN_WIDTH_DATE;
try {
String name = "<noname>";
if ( _message.isInbound() ) {
Address a = _message.getFrom();
if ( a != null )
{
name = a.getName();
if ( name == null || name.length() == 0 ) name = a.getAddr();
}
}
else
{
//get the first Recipient address
Address[] set = _message.getRecipients(Message.RecipientType.TO);
if ( set != null && set.length > 0 )
{
name = set[0].getName();
if ( name == null || name.length() == 0 ) name = set[0].getAddr();
}
}
sampleVector.addElement(name +" " + sb.toString());
} catch (MessagingException e) {
System.err.println(e);
}
x += COLUMN_WIDTH_NAME;
int remainingColumnWidth = Graphics.getScreenWidth() - x;
//get the subject, or if that doesn't exist, the first line of the body
String textToDisplay = _message.getSubject();
if ( null == textToDisplay) //no subject! get the first line of the body if present
{
Object o = _message.getContent();
if ( o instanceof String )
{
textToDisplay = (String)o;
}
else if ( o instanceof Multipart )
{
Multipart mp = (Multipart)o;
int count = mp.getCount();
for (int i = 0; i < count; ++i)
{
BodyPart p = mp.getBodyPart(i);
if ( p instanceof TextBodyPart )
{
textToDisplay = (String)p.getContent();
}
}
}
}
sampleVector.addElement(textToDisplay);
} public void messagesAdded(FolderEvent e) {} public void messagesRemoved(FolderEvent e) { } public void batchOperation( StoreEvent se) { }
}
I'm not sure what you mean, could you please post a screenshot so that we can see the problem?
I'll try to help out the best I can. In my limited experience, I have noticed that in a listfield, if you have not set the row height (with setRowHeight()) to a big enough height, graphics (including text) that overflow over the size of the row will not be displayed. Have you tried setting the row height to 2 * list.getFont().getHeight() or more?
If not all rows are displayed, then I think you've missed to call myList.setSize(myVector.size());
I'm not sure what you mean by "wrapping not happening"...
The drawListRow() will be called repeatedly (for the amount of times set by the setSize() that I've suggested above).
In your current code you iterate through the whole myVector on each drawListRow() call - this is wrong.
You must use the value y which is declare in drawListRow (ListField list, Graphics g, int index, int y,int w)
like
g.drawText( text, LIST_IMAGE.getWidth() + 5, y+liney, Graphics.ELLIPSIS, w )
I am facing this issue for long time finally i got the solution.
As Alex say, you need to implement your own wrapper class, something that looks like:
TextWrapper theWrapper = new TextWrapper();
String[] wrappedText = theWrapper.textWrap(longText, wrappingWidth , 2);
//
// now draw text line by line
//
g.drawText(wrappedText[0], x, y, DrawStyle.LEFT, width);
if (wrappedText.length > 1) {
g.drawText(wrappedText[1], x, y + textFont.getHeight(), DrawStyle.LEFT | DrawStyle.ELLIPSIS, width);
}
where
public class TextWrapper {
... // put here methods used by textWrap method
//
// textWrap splits input String in lines having width as maxWidth
//
public String[] textWrap(String s, int maxWidth, int maxLines)
{
String[] result;
... // do here the wrap job on input string s
return result;
}
}

Resources