Tuesday, December 21, 2010
Command Line Debugging in Java ::: JDB
In the world of java you can do it easliy by using jdb command line action provided by Java.. lets write down a simple program to perform command line debugging in java.
Lets write down a simple program to add two numbers in java.
import java.io.*;
public class Sum
{
public static void main(String arfs[])
{
int i,j;
i=10;
j=25;
System.out.println(" I = " + i + " J = " + j);
int sum=i+j;
System.out.println("Sum = " + sum);
}
}
Now compile the above code by using
javac -g Sum.java
Here -g option is used to inject the debug information into the generated class files, This can easily be viewed by checking the file size using with and without "g" option.
Start the Execution of this program by using following command
>java -Xdebug -agentlib:jdwp=transport=dt_shmem,address=9999,server=y,suspend=y Sum
the message "Listening for transport dt_shmem at address: 9999" is generated showing that the debugger is started with this program and ready to listen the request on the port no 9999.
Open a separate window and type the following at the command prompt.
> jdb -attach 9999
Following output will be generated
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
> VM Started: No frames on the current call stack
main[1]
Now the debugger is ready to start debugging the program. We just need to pass the jdb specific commands to the debugger.
main[1]: This represents the current call stack on the heap where the execution is.
Now assume main[1] will be your command prompt for the time being.
1. Type cont
main[1] cont (PRESS ENTER)
output will be:
> Set deferred breakpoint Sum.main
Breakpoint hit: "thread=main", Sum.main(), line=10 bci=0
10 i=10;
main[1]
2. Now Type "Stop at Sum:12" to instruct the debugger to stop the execution of the program at the 12 line.
main[1] Stop at Sum:12
Output will be: Set breakpoint Sum:12
3. Now Type "cont" to continue with the execution of the code.
4. Now as per the program i and j has been initialized, so use the following command to view the values present in i and j.
main[1] print i
output >> i = 10
Similarly u can inspect the value of other variables that are being initialized till the execution of the line, otherwise you will get null
5. Now type "cont" to continue the execution.
It will simply exit the debugger and will fall on to the main prompt.
so "cont" is being used to continue with the execution of the program
"Stop at Sum:12" to stop the execution of program at a particular line.
I hope it would be helpful for beginners, to understand how to debug your program through command line.
Following are the screenshots attached.
http://4.bp.blogspot.com/_M_Jj-0uEvJU/TRBsqUGytgI/AAAAAAAADWg/ycX0nA3lMNQ/s1600/1..JPG
http://1.bp.blogspot.com/_M_Jj-0uEvJU/TRBsuOrMOTI/AAAAAAAADWk/WjSj2xOzat8/s1600/2.JPG
For this tutorial i had used the tutorial from the following awesome links:
http://www.herongyang.com/jtool/jdb.html
http://cscarioni.blogspot.com/2010/12/understanding-how-java-debug-works.html
Monday, May 17, 2010
Blackberry Knowledge Base
A single application can create up to 16 threads. The total number of threads that can exist on a BlackBerry device from all applications is 128. So if you you try to create 17 thread or 129 then it will throw TooManyThreadsError.
2. Process [ApplicationName] killed due to message queue overflow
An application is blocking the main event thread.
The main event thread processes system messages. Blocking this thread prevents system messages from being processed and can lead to a message queue overflow.
3. TooManyProcessesError
The Java Virtual Machine (JVM), implemented for BlackBerry devices, has a maximum number of 48 concurrent processes. If the JVM finds itself in a state where an additional process would exceed the number of maximum processes, you receive the JVM 200 error (TooManyProcessesError).
Many developers experience this issue on startup especially if their application (or multiple applications) is set to Auto run on startup.
To alleviate this problem, enable one library to serve as the only item that runs on startup. In the library libMain method, the implementation performs all of the startup initialization required from within the library. If some of the libraries are optional, the main initialization library should use the Class.forName() construct to continue maintaining the initialization code inside one library.
4. Error Starting [Application Name]: Unsigned module '[Module Name]' may not contain classes in com.rim(except com.rim.samples), net.rim,net.blackberry, java or javax.
Cause
The error is caused by the package name restrictions that are implemented in BlackBerry Device Software 3.8 and later.
Resolution
For third-party and custom application, package names cannot contain any of the following:
com.rim
net.rim
net.blackberry
java
javax
Note: The one exception to this list is that third-party applications are able to use the com.rim.samples package name.
What is the Use of CustomItem in J2me
A CustomItem is customizable by subclassing to introduce new visual and interactive elements into
Forms.Say if you want the scrolling bar on to form u can use CustomItem for this purpose. CustomItem is very much like using low level into high level.Help full in J2me Application development.CustomItem have methods as
getMinContentHeight()Implemented by the subclass to return the minimum height of the content area, in pixels.
getPrefContentHeight(int width)Implemented by the subclass to return the preferred height of the content area, in pixels.
hideNotify()keyPressed(int keyCode)paint(Graphics g, int w, int h)repaint()traverseOut()Called by the system when traversal has occurred out of the item.
And much more....
Hope fully you can get the idea about CustomItem.
Working code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SimpleItemMIDlet extends MIDlet
implements CommandListener {
public void startApp() {
Form form = new Form("SimpleItemMIDlet");
form.append(new SimpleItem("SimpleItem"));
Command c = new Command("Exit", Command.EXIT, 0);
form.addCommand(c);
form.setCommandListener(this);
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT)
notifyDestroyed();
}
}
class SimpleItem extends CustomItem {
public SimpleItem(String title) { super(title); }
public int getMinContentWidth() { return 100; }
public int getMinContentHeight() { return 60; }
public int getPrefContentWidth(int width) {
return getMinContentWidth();
}
public int getPrefContentHeight(int height) {
return getMinContentHeight();
}
public void keyPressed(int key){
}
public void paint(Graphics g, int w, int h) {
g.drawRect(0, 0, w - 1, h - 1);
g.setColor(0x000000ff);
int offset = 0;
for (int y = 4; y < h; y += 12) {
offset = (offset + 12) % 24;
for (int x = 4; x < w; x += 24) {
g.fillTriangle(x + offset, y,
x + offset - 3, y + 6,
x + offset + 3, y + 6);
}
}
}
}
Above code is from
http://www.java2s.com/Code/Java/J2ME/SimpleItemMIDlet.htm
Interface Vs Inheritance
Interface Vs Inheritance
Interface: Like contract, which you must have to follow.
Inheritance: Like hierarchy of functionality.
Now where to use is important, And it totally depend upon situation
Which is appropriate to use depends on circumstances.
From my view:
Interface: If you want same behavior across unrelated classes.
Inheritance: Use when classes have same functionality.
Example:
Let’s say we have a class Singer that represents a human singer. Now, singer can also be a bird or a musical instrument like Piano etc too. If we make a Singer a class then we have to take care of the issue that inheriting Piano from Singer might not work as both classes don’t lie in the same category. Singer is a human (living being) whereas Piano is a non-living thing. So, instead of inheritance we can make an interface say Singable and we can implement it on Piano, Human, Bird etc.
OR
Bear extends Animal
Bird extends Animal
TeddyBear extends Bear implements Pet
Canary extends Bird
TweetyBird extends Canary implements Pet
A Pet is a set of defined behaviours, doesn't provide that behaviour as it will differ widely between your TeddyBear and your TweetyBird (TeddyBear might be cuddly but doesn't sing).
---------------------------------------------------------------
Benefits of inner classes in java
- Encapsulation
- Inner classes can access private fields and methods of the enclosing class. If you need a new class that has access to otherwise private data of an existing class, and you don't want to make that data available to the rest of the package (by removing the "private"), you can grant access to one other class by making that class in inner class of the class with the private data or method.
inner class is a class defined inside some other class (but you knew that). Inner classes are able to access the private members of their outer class instance.
A static inner class does not have this ability to access the privates of his outer class. This makes a static inner class very much like a regular class, and in many cases, using one of those mainly adds confusion over using a regular class without giving any real benefits.
Anonymous inner classes are often used because they save you having to explicitly define a class type. It's a shorthand, designed to save time while writing the code. Again, use with caution, cause they can make the code hard to understand.
Adding Command Action for Devices whose left / right Soft key is not working
When to use static Mehod and When to use non static
This is important to understand that when to use static method and when to use instance method:
Thumb rule for Static and Non Static is:
Use Static Method when your method is independent of state of the instance object.
Use Non Static when your method is depending upon state of the instance object.
Let’s understand this by example that is good for all of us:
public class MrHappyObject {
private String _mood = _HAPPY;
private final static String _HAPPY = "happy";
private final static String _ANNOYED = "annoyed";
private final static String _ANGRY = "angry";
private static int _instantiations;
public static void main( String [] args ) {
MrHappyObject obj1 = new MrHappyObject();
MrHappyObject obj2 = new MrHappyObject();
obj1.printMood();
obj2.printMood();
obj1.receiveHug();
obj2.receivePinch();
obj1.printMood();
obj2.printMood();
}
public void printMood() {
System.out.println( "I am " + _mood );
}
public void receivePinch() {
if( _mood.equals( _HAPPY ) ) {
_mood = _ANNOYED;
} else {
_mood = _ANGRY;
}
}
public void receiveHug() {
if( _mood.equals( _ANGRY ) ) {
_mood = _ANNOYED;
} else {
_mood = _HAPPY;
}
}
public MrHappyObject() {
_instantiations++;
}
public static int instances() {
return _instantiations;
}
}
First we will look when to use non static method.
In above example we have 2 object obj1, obj2.
Both are born happy.
Now we call receiveHug() by obj1, and receivePinch() by obj2.Both receiveHug() and receivePinch() are non static method and they depends upon state of the object.
So the final output is:
I am happy
I am happy
I am happy
I am annoyed
That is what we want as Hugging the MrHappyObject`s Object make him happy and
Pinching it make it annoyed. We got the desired result because receiveHug(), and receivePinch() are depend upon state of object and they are non static Method.
Now Comple and run same class by making receiveHug(), and receivePinch() method Static .
public class MrHappyObject {
private final static String _HAPPY = "happy";
private static String _mood = _HAPPY;
private final static String _ANNOYED = "annoyed";
private final static String _ANGRY = "angry";
private static int _instantiations;
public static void main( String [] args ) {
MrHappyObject obj1 = new MrHappyObject();
MrHappyObject obj2 = new MrHappyObject();
obj1.printMood();
obj2.printMood();
obj1.receiveHug();
obj2.receivePinch();
obj1.printMood();
obj2.printMood();
}
public void printMood() {
System.out.println( "I am " + _mood );
}
public static void receivePinch() {
if( _mood.equals( _HAPPY ) ) {
_mood = _ANNOYED;
} else {
_mood = _ANGRY;
}
}
public static void receiveHug() {
if( _mood.equals( _ANGRY ) ) {
_mood = _ANNOYED;
} else {
_mood = _HAPPY;
}
}
public MrHappyObject() {
_instantiations++;
}
public static int instances() {
return _instantiations;
}
}
And the output is
I am happy
I am happy
I am annoyed
I am annoyed
This is not our desired result.
Now this makes clear when to use Static method and when to use non static method.
How to create OTA server?
For creating OTA server you need HTTP server (Web server i.e tomcat50-jwsdp).
Now create new folder under web apps like C:\tomcat50-jwsdp\webapps\counter
Counter contains 2 folder ==>WEB-INF (it contains web.xml), images (or any other name ,it contains JAD n JAR)
Put MIME Type of JAD and JAR.
jad
text/vnd.sun.j2me.app-descriptor
jar
application/java-archive
And access this jad file from your mobile browser it will automatically invoke AMS.
Or can see it from your PC browser
http://localhost:8080/counter/images/
As images folder contains JAD and JAR file. Change locathost to your actual address.
Write Hindi font in mobile
And then read it using :
StringBuffer sb = new StringBuffer();
public void readMe(){
InputStream is = null;
try
{
is = getClass().getResourceAsStream("/name.utx");
Reader r = new InputStreamReader(is, "UTF-8");
int c = 0;
while (true) {
c = r.read();
if (c == -1) {
break;
}
sb.append( (char) c);
}
}
catch (Exception i)
{
System.out.println("Error in Read ME ");
}
}
Some IMP Link for Device Properties
http://www.jbenchmark.com/index.jsp
http://www.club-java.com/TastePhone/J2ME/MIDP_mobile.jsp
http://developers.samsungmobile.com/Developer/index.jsp
http://www.forum.nokia.com/devices/matrix_all_1.html
http://developer.sonyericsson.com/site/global/docstools/phonespecs/p_phonespecs.jsp
http://developer.motorola.com/products/handsets/
http://www.gsmarena.com/
http://www.mobref.com/home/
-----------------------------------------------------------------------------------------------
