50% OFF!!!

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, June 22, 2010

lwuit | j2me link control (component)

Here is an implemantation of a LINK component for the LWUIT enviroment under J2ME (Java ME).
This code creates a lwuit link component based on the lwuit button which not have a border and is transparent! also have an appropriate color (blue) and font style (underline).
hope it is helpful:

code example:

Button btn = new Button("LINK1");
//btn.getStyle().setBorder(Border.createEmpty());
btn.getUnselectedStyle().setBorder(Border.createEmpty());
btn.getSelectedStyle().setBorder(Border.createEmpty());

//btn.getStyle().setBgTransparency(100);
btn.getUnselectedStyle().setBgTransparency(100);
btn.getSelectedStyle().setBgTransparency(100);

//btn.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_MEDIUM));
btn.getUnselectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED, Font.SIZE_MEDIUM));
btn.getSelectedStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_UNDERLINED | Font.STYLE_BOLD, Font.SIZE_MEDIUM));

//btn.getStyle().setFgColor(0x0000ff);
btn.getUnselectedStyle().setFgColor(0x0000ff);
btn.getSelectedStyle().setFgColor(0x0000ff);



Enjoy!

Sunday, May 23, 2010

J2ME | read BlackBerry device name, device id (under MIDP)

Hello to all.

I searched the web and not found any implemantaion of reading device name or device id using J2ME MIDP for blackberry.

There exists an RIM api: "net.rim.device.api.system.DeviceInfo.getDeviceName()" which allow you to read the blackberry device information, but on when creating a global application for all MIDP devices, this api will not work for other devices like Sony-Ericsson, NOKIA, Samsung, Motorola, HTC and so...

The solution is to dynamicly load an outer JAR (dynamic library = dll) only when a blackberry device detected and read all data.
NOTE: if we will access to this library (JAR) without validating the RIM device, an excaption will be thrown!!

So, the solution is:
Step 1:
Create a new project: Mobile Class Library.
Name it: BlackberryInfo

Step 2:
create new Class named: DeviceInfo
with the following code:

Code for step 2:
package BlackberryInfo;

public class DeviceInfo
{
   static public String getDeviceName()
   {
      return net.rim.device.api.system.DeviceInfo.getDeviceName();
   }

   static public String getManufacturerName()
   {
      return net.rim.device.api.system.DeviceInfo.getManufacturerName();
   }

   static public int getDeviceId()
   {
      return net.rim.device.api.system.DeviceInfo.getDeviceId();
   }

   static public String getPlatformVersion()
   {
      return net.rim.device.api.system.DeviceInfo.getPlatformVersion();
   }
}

Step 3:
Build project and get JAR and JAD named: BlackberryInfo.jar
Note: build this JAR using Blackberry BlackBerry JDE (I used 5.0.0) (BlackBerry JDE downloads)
if you want, i can upload this library to the blog...

Step 4:
In your application (J2ME MIDP), just add BlackberryInfo.jar as library.

Step 5:
Now, all you have to do, is just to validate that this is RIM Blackberry device, and the read all device info.

Code for step 5:
static public boolean isBlackberryPlatform()
{
    try
    {
        Class.forName("net.rim.blackberry.api.browser.Browser");
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

// some func for read device information (device name, device id, device
 if (isBlackberryPlatform() == true)
{
            System.out.println("Blackberry platform:");
            System.out.println(BlackberryInfo.DeviceInfo.getDeviceName());
            System.out.println(BlackberryInfo.DeviceInfo.getManufacturerName());
            System.out.println(BlackberryInfo.DeviceInfo.getPlatformVersion());
            System.out.println(BlackberryInfo.DeviceInfo.getDeviceId() + "");
}



Notice that, the JAR is loaded only when trying to access it, so other devices expect RIM blackberry will NOT get to this line so they won't try to load unavailable api of rim blackberry.

reference to DeviceInfo implemantation (5.0.0)
http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/system/DeviceInfo.html

hope i could help someone outthere...
p.s.
this method can work for every OUTER/UNKNOWN API in J2ME.

Monday, May 17, 2010

J2ME | determine BlackBerry device (OS)

Here is a code for determine whether a J2ME application is running over Blackberry device.

The idea is to check for a class that exists only in Blackberry platform and not on J2ME MIDP Operation system.
here I choose to determine using "net.rim.blackberry.api.browser.Browser" which exists only in Blackberry OS (NOT in other OSs).

The code using Class.forClass method (link) which returns the Class object associated with the class or interface with the given string name. if the class exists (so we in Blackberry) the method return an object, otherwise throws an exception.

here is a simple code:
static public boolean isBlackberryPlatform()
{
        try
        {
            Class.forName("net.rim.blackberry.api.browser.Browser");
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
}

enjoy, and post replies...

J2ME | identify MIDP runner over Android OS

Here is a good code for determine whether a J2ME application is running over MIDP runner over Android OS.

The idea is to check for a class that exists only in Android platform and not on J2ME MIDP Operaion system.
here I choose to determine using "android.Manifest" which exists in Android OS and NOT in other OSs.

The code using Class.forClass method (link) which returns the Class object associated with the class or interface with the given string name. if the class exists (so we in Android) the method return an object, otherwise throws an exception.

here is a simple code:
static public boolean isAndroidPlatform()
{
        try
        {
            Class.forName("android.Manifest");
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
}

enjoy, and post replies...

Thursday, September 3, 2009

J2ME | Binary search algorithem


Binary search algorithem method/function for j2me platform.
Use is with sorted String array!!!
Enjoy... this works great with my example on J2ME | String array sort. link here.



public static int binarySearch(String[] p_arraySorted, String p_key)
{
return binarySearch(p_arraySorted, 0, p_arraySorted.length, p_key);
}



public static int binarySearch(String[] p_arraySorted, int p_first, int p_upto, String p_key)
{
int compare, mid;
while (p_first < p_upto)
{
// Compute mid point.
mid = (p_first + p_upto) / 2;

compare = p_key.compareTo(p_arraySorted[mid]);
if (compare < 0) // p_key < p_arraySorted[mid]
{
// repeat search in bottom half
p_upto = mid;
}
else if (compare > 0) // p_key > p_arraySorted[mid]
{
// Repeat search in top half
p_first = mid + 1;
}
else
{
// Found it. return position
return mid;
}
}

// Failed to find key
return -1;
}


Sort it and search it wisely...

J2ME | String array sort

Here is a good function for sorting string arrays.
The algorithem is BUBBLE-SORT algorithm.
The algorithem sorts the string array (dictionary comparison)


static void bubbleSort(String[] p_array) throws Exception
{
boolean anyCellSorted;
int length = p_array.length;
String tmp;
for (int i = length; --i >= 0;)
{
anyCellSorted = false;
for (int j = 0; j < i; j++)
{
if (p_array[j].compareTo(p_array[j + 1]) > 0)
{
tmp = p_array[j];
p_array[j] = p_array[j + 1];
p_array[j + 1] = tmp;
anyCellSorted = true;
}

}
if (anyCellSorted == false)
{
return;
}
}
}



if you want i will upload more SORT algorithems...

Friday, August 28, 2009

J2ME String Split method

Here is my code for splitting a string under Java - J2ME.
this is very helpfull for using a string array instead of string manipulation.

This is the best & fastest splitting method

Code:

public static String[] split(String p_text, String p_seperator)
{
Vector vecStrings = new Vector();

int index;
int prevIdx = 0;

while ((index = p_text.indexOf(p_seperator, prevIdx)) > -1)
{
vecStrings.addElement(p_text.substring(prevIdx, index));
prevIdx = index + 1;
}
vecStrings.addElement(p_text.substring(prevIdx));

String[] result = new String[vecStrings.size()];
vecStrings.copyInto(result);

return result;
}

Tuesday, June 16, 2009

J2ME | Analog Clock control - custom item



Here is an example for anlogic clock control (extends CustomItem) which may be added to Form class and also in Canvas class.
for Form class just add it as and item,
and for Canvas class and its paint method, provide graphics to AnalogClock's paint method.

Here is Code for the analog clock:


package CustomItems;

import javax.microedition.lcdui.*;
import java.util.Calendar;

public class AnalogClock extends CustomItem implements Runnable
{

private double diam = 0.38;
private double LineLengthSeconds = 0.90;
private double LineLengthMinutes = 0.75;
private double LineLengthHour = 0.50;
private double LineLengthTicks = 0.08;
private double TextPositionRelativeR = 1.22;
//
/***
* Represents control's width
*/
private int Width = 100;
/***
* Represents control's height
*/
private int Height = 100;
/***
* Represents clock's radius
*/
private int _raduis;
/***
* Represents clock's center point - X
*/
private int _circleCenterX;
/***
* Represents clock's center point - Y
*/
private int _circleCenterY;
/***
* Represents clock's current date&time
*/
private Calendar _now;
/***
* Represents the thread which implement the clock's ticks
*/
private Thread _thread = null;
/***
* Represents a flag which describe if the thread is running or not
*/
private boolean _threadIsRunning = false;
//
/***
* Represents the background color of the clock
*/
public int BackColor = 0xffffff;
/***
* Represents the color of the clock (text & lines)
*/
public int ClockColor = 0x000000;
/***
* A flag which represent whether or not display the date inside the clock
*/
public boolean ShowDate = false;
/***
* Represents the font of the text drawn
*/
public Font Font;

/** Creates a new instance of AnalogClock */
public AnalogClock(String p_label, int p_size)
{
super(p_label);
if (p_size <= 0)
{
sizeChanged(Width, Height);
}
else
{
sizeChanged(p_size, p_size);
}
Font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
}

protected int getMinContentWidth()
{
return 10;
}

protected int getMinContentHeight()
{
return 10;
}

protected int getPrefContentWidth(int p_height)
{
return Width;
}

protected int getPrefContentHeight(int p_width)
{
return Height;
}

protected void sizeChanged(int p_w, int p_h)
{
Height = p_h;
Width = p_w;
int size = Math.min(Width, Height);
_raduis = (int) (diam * (double) size);
_circleCenterX = size / 2;
_circleCenterY = size / 2;
_now = Calendar.getInstance();
}

private int pointX(double minute, double radius, int _circleCenterX)
{
double angle = minute * Math.PI / 30.0;
return (int) ((double) _circleCenterX + radius * Math.sin(angle));
}

private int pointY(double minute, double radius, int oy)
{
double angle = minute * Math.PI / 30.0;
return (int) ((double) oy - radius * Math.cos(angle));
}

public void updateTime()
{
_now = Calendar.getInstance();
repaint();
}

public void updateTime(Calendar p_currtime)
{
_now = p_currtime;
repaint();
}

protected void paint(Graphics g, int w, int h)
{
// clear background
g.setColor(BackColor);
g.fillRect(0, 0, Width - 1, Height - 1);
g.setColor(ClockColor);

// draw circle
g.drawArc(_circleCenterX - _raduis, _circleCenterY - _raduis, _raduis * 2, _raduis * 2, 0, 360);

// set text's font
g.setFont(Font);
int textH = Font.getHeight();

// draw date (if allowed)
if (ShowDate == true)
{
String strDate = getDateString(_now, "-");
int strDateWidth = Font.stringWidth(strDate);
g.drawRect(_circleCenterX - strDateWidth / 2, _circleCenterY, strDateWidth, textH);
g.drawString(strDate, _circleCenterX, _circleCenterY, Graphics.TOP | Graphics.HCENTER);
}

// draw ticks & digits
int textW;
for (int hour = 1; hour <= 12; hour++)
{
double angle = hour * 60.0 / 12.0;
g.drawLine(
pointX(angle, _raduis * (1 - LineLengthTicks), _circleCenterX),
pointY(angle, _raduis * (1 - LineLengthTicks), _circleCenterY),
pointX(angle, _raduis, _circleCenterX),
pointY(angle, _raduis, _circleCenterY));

// texts
textW = Font.stringWidth("" + hour);
g.drawString("" + hour,
(int) pointX(angle, _raduis * TextPositionRelativeR, _circleCenterX) - textW / 2,
(int) pointY(angle, _raduis * TextPositionRelativeR, _circleCenterY) - textH / 2,
0);
}

double hour = _now.get(Calendar.HOUR) * 60.0 / 12.0;
double minute = _now.get(Calendar.MINUTE);
double second = _now.get(Calendar.SECOND);

// draw hour line
g.drawLine(_circleCenterX, _circleCenterY,
pointX(hour + (double) minute / 12.0, _raduis * LineLengthHour, _circleCenterX),
pointY(hour + (double) minute / 12.0, _raduis * LineLengthHour, _circleCenterY));

// draw minutes line
g.drawLine(_circleCenterX, _circleCenterY,
pointX(minute + second / 60.0, _raduis * LineLengthMinutes, _circleCenterX),
pointY(minute + second / 60.0, _raduis * LineLengthMinutes, _circleCenterY));

// draw seconds line
g.drawLine(_circleCenterX, _circleCenterY,
pointX((double) second, _raduis * LineLengthSeconds, _circleCenterX),
pointY((double) second, _raduis * LineLengthSeconds, _circleCenterY));
}

public synchronized void startTicking()
{
if (_thread == null)
{
_thread = new Thread(this);

_threadIsRunning = true;
_thread.start();
}
}

public synchronized void stopTicking()
{
if (_thread != null)
{
_threadIsRunning = false;
try
{
_thread.join();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}

public void run()
{
while (_threadIsRunning == true)
{
this.updateTime();

try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}

private String getDateString(Calendar p_calendar, String p_delimiter)
{
int day = p_calendar.get(Calendar.DAY_OF_MONTH);
int month = p_calendar.get(Calendar.MONTH) + 1;
int year = p_calendar.get(Calendar.YEAR);

String strDay = (day < 10) ? "0" + day : String.valueOf(day);
String strMonth = (month < 10) ? "0" + month : String.valueOf(month);
String strYear = String.valueOf(year);

StringBuffer sb = new StringBuffer();
sb.append(strDay);
sb.append(p_delimiter);
sb.append(strMonth);
sb.append(p_delimiter);
sb.append(strYear);

return sb.toString();
}
}


Usage sample:

package Test;

import CustomItems.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class StartMidlet extends MIDlet implements CommandListener
{
public void startApp()
{
Form f = new Form("My Clock Test");
int w = f.getWidth();
int h = f.getHeight();

AnalogClock cl = new AnalogClock(null, (int) (w * 0.8));
cl.setLayout(Item.LAYOUT_2 | Item.LAYOUT_CENTER);
cl.startTicking();
f.append(cl);

Command cmd = new Command("Back", Command.BACK, 0);
f.addCommand(cmd);

cmd = new Command("Next", Command.OK, 1);
f.addCommand(cmd);

f.setCommandListener(this);

Display.getDisplay(this).setCurrent(f);
}

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command arg0, Displayable arg1)
{ }
}




The contorl have 2 methods for managing clock timer.
startTicking - for start ticking the timer (this calls repaint...)
stopTicking- for stop the timer



Use it smartly...

Monday, June 8, 2009

J2ME | String Replace method



I found a good string replace function/method.
J2ME do not contain string replace (only char replace),
so this method is very helpful!!!



public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();

// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();

// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}

// Create string
sb.append(_text.substring(startPos,_text.length()));

return sb.toString();
}





found at http://forums.sun.com/thread.jspa?threadID=734604&tstart=5431