Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, April 17, 2010

Many times, I was in search of building custom components for BlackBerry and tutorials on how to make great apps. Here are some of the links that I found interesting.

Tutorial:

Create a BlackBerry Game Tutorial








Custom Components:









Charting Tools





HTTP Connection for BlackBerry

BlackBerry http connection is very much problematic. For using different connection type you have to use different ways. It should be such that http connection is automatically handled. I don't understand why they don't make it easy for developers to use http connection. This http connection systems makes life hell, specifically for BIS






Application Permission Related:




GPS Tutorial:




Performance Issues:

http://www.thinkingblackberry.com/archives/144




BB MenuItems:




Storing data in persistent Storage:

BB OS 5.0 recently introduced SQLite. Previous OS only supports Persistent Store to store data in application.


Wednesday, September 30, 2009

You might need to preverify the jar file. This is how you can preverify a jar file

Go to your JDE installation folder, for Windows XP it is usually C:\Program Files\Research In Motion\BlackBerry JDE 4.3.0\bin. If you are using eclipse then you can also find the installation directory of BlackBerry plugin.
2. Copy your jar  file to bin folder.
3. Notice the preverify.exe file. This is the tool we'll use.
4. Now open your command prompt and change your current directory to your JDE installation directory.
5. execute the following command:
preverify -classpath "JDE_PATH_HERE\lib\net_rim_api.jar" "your_jar_filename"
6. Notice that in bin directory, another folder named output has been created. Preverified jar file resides here. Copy the preverified jar file with the same name that the non-preverified jar file has.
7. Now replace the non-preverified jar file with the verified one. Use this jar in next steps

Create a new Blackberry project with any name like LibProject.
   Right-click on the project and go to Properties.
   Go to Blackberry Project Properties. Click on the Application tab.
   Under Project Type, change to Library.
   Next, go to the Java Build Path.
  go to libraries and add the jar file as an external library.
  Go to Order and Export tab here, and mark your jar file as exportable
  Click OK.

Build the library project.

Now, create your main BlackBerry project
   Keep this projects type to as you wish it to be.
   Now go to the properties of this project, In the Java Build Path, add the LibProject project as a Project dependency.

You are pretty much ready to import the jar in your code. Try to import a class and see if it works.

Alternatively, what I think that we might skip the first works of creating a new project and try to add the jar directly to our app. I think that might also work. Though I did not try it yet. Let me know if anyone was successful doing it.

That’s all for now

Saturday, July 11, 2009

In order to show GIF images in Blackberry applications you have to disable exporting all images to png format. This can be done from JDE by right clicking the project and going to properties. In resources tab select “Don’t convert image files to png”.

dontpng

Now add the gif image in the project. And add this class with your project.



/*

* AnimatedGIFField.java
*
* © <your company here>, 2003-2008
* Confidential and proprietary.
*/

import net.rim.device.api.ui.UiApplication;

import net.rim.device.api.system.GIFEncodedImage;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;

//A field that displays an animated GIF.

public class AnimatedGIFField extends BitmapField
{
private GIFEncodedImage _image; //The image to draw.
private int _currentFrame; //The current frame in the animation sequence.
private int _width; //The width of the image (background frame).
private int _height; //The height of the image (background frame).
private AnimatorThread _animatorThread;

public AnimatedGIFField(GIFEncodedImage image)
{
this(image, 0);
}

public AnimatedGIFField(GIFEncodedImage image, long style)
{
//Call super to setup the field with the specified style.
//The image is passed in as well for the field to
//configure its required size.
super(image.getBitmap(), style);

//Store the image and it's dimensions.
_image = image;
_width = image.getWidth();
_height = image.getHeight();

//Start the animation thread.
_animatorThread = new AnimatorThread(this);
_animatorThread.start();
}

protected void paint(Graphics graphics)
{
//Call super.paint. This will draw the first background
//frame and handle any required focus drawing.
super.paint(graphics);

//Don't redraw the background if this is the first frame.
if (_currentFrame != 0)
{
//Draw the animation frame.
graphics.drawImage(_image.getFrameLeft(_currentFrame), _image.getFrameTop(_currentFrame),
_image.getFrameWidth(_currentFrame), _image.getFrameHeight(_currentFrame), _image, _currentFrame, 0, 0);
}
}

//Stop the animation thread when the screen the field is on is
//popped off of the display stack.
protected void onUndisplay()
{
_animatorThread.stop();
super.onUndisplay();
}

//A thread to handle the animation.
private class AnimatorThread extends Thread
{
private AnimatedGIFField _theField;
private boolean _keepGoing = true;
private int _totalFrames; //The total number of frames in the image.
private int _loopCount; //The number of times the animation has looped (completed).
private int _totalLoops; //The number of times the animation should loop (set in the image).

public AnimatorThread(AnimatedGIFField theField)
{
_theField = theField;
_totalFrames = _image.getFrameCount();
_totalLoops = _image.getIterations();

}

public synchronized void stop()
{
_keepGoing = false;
}

public void run()
{
while(_keepGoing)
{
//Invalidate the field so that it is redrawn.
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
_theField.invalidate();
}
});

try
{
//Sleep for the current frame delay before
//the next frame is drawn.
sleep(_image.getFrameDelay(_currentFrame) * 10);
}
catch (InterruptedException iex)
{} //Couldn't sleep.

//Increment the frame.
++_currentFrame;

if (_currentFrame == _totalFrames)
{
//Reset back to frame 0 if we have reached the end.
_currentFrame = 0;

++_loopCount;

//Check if the animation should continue.
if (_loopCount == _totalLoops)
{
_keepGoing = false;
}
}
}
}
}
}

This class will create a custom field type object. You can add it with a Screen type objects.

The following code will add a GIF image with a Screen type object



AnimatedGIFField testanimated= new AnimatedGIFField((GIFEncodedImage)(GIFEncodedImage.getEncodedImageResource( "loading2.gif" )),AnimatedGIFField.FIELD_LEFT);
//add(answer);
add(testanimated);


You are done. Let me know if you found any difficulties adding it.

9530

Sunday, February 22, 2009

I was in a need to show a date picker with a java application. After some searching I came into here for a free calendar component.

Might become useful for somebody.

And to show a time picker control, you can use the jspinner itself, nothing extra is required. It amazed me

JSpinner spinner =
new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm");
spinner.setEditor(de);


You can do it in netbeans by going into the properties of jspinner and changing the Editor properties from there,

When you have a bluetooth dongle you can receive business card/files/contacts from mobile devices using your bluetooth software. Now if you want to receive contacts/file in your own software and you also don't want to install any application in your mobile device then you can continue reading.

The main thing is to open a obex receiver in your bluetooth device from your application, then other remote device can do ServiceSearch and find your dongle to send contact/vcard/business card without installing any application.

The trick is done using OBEX, to know about OBEX google please.
I am going to use Java as my source language as there is already a API made named bluecove

I tried to find an already made project and couldn't find after some searching(may be my search strings were weak)

After one/two day i came to the bluecove code repository, there i found the source of it.

So i made a netbeans project of my own and is posted at the end of this post(i think if you are interested then you are now looking into the end section for the code ;) )

Ok no rush, the original source code of bluecove people are here. Thanks god i found it.

And my code in netbeans can be found here.

To run it in windows no problem, but to run in it newer ubuntu when this post was written you had to include bluecove-gpl with the project, which is already included and you will need to install libbluetooth-dev for ubuntu 8.10 with this command
sudo apt-get install libbluetooth-dev

I hope the code works.

So basically the thing is, i want to send files to mobile devices without installing any software in mobile handset. So how can i do that? Obviously google.

You can send files to mobile device using OBEX, a file transfer protocol for bluetooth devices, it's in jsr82.

And there is a api known as bluecove which has things ready made :). Supported stack(don't ask me what it is, i know little about i) list can be found here. A list of jsr82 compatible handsets can be found here.

I work with netbeans, you can get the latest netbeans ide from here.

You will need the bluecove-api jar, and you can download from here. The jar i used was named "bluecove-2.1.0.jar", Now here is an issue, if you want your application to run in ubuntu/linux then you will also need a jar called "bluecove-gpl-2.1.0.jar" which can be found in here. So copy this jars to the netbeans project folder. And add these jar's in the project libraries, go to project properties and from libraries at left select add jar/folder and show the jars.


Now you are ready to use bluecove with your project. Do some coding things as you like.

Here I am going to make an application which will discover devices around it and send them a file.

I used real bluetooth devices and handset. There is also possible to use emulators to emulate bluetooth dongle and also mobile device. But I don't know how, you can let me know if you find a easy one.

Ok now coding time, the application has three main parts
1. UI which is shown to user
2. BluetoothBrowser: a class that discovers remote devices and put them in a list, and this class is also used to find the OBEX url for sending files to remote device.
3. A sender class which sends file to remotedevices using the OBEXUrl found previously.

Now, while starting to work first, i found some examples where connectionurl was hardcoded like
btgeop://address:9
But this was not working for me, this is a port number in remote device in which obex service is running, but this port number is not valid for all handsets. For nokia it works fine, but in Sony Ericsson the obex port number is 6, so to make the program independent a findObex function was used to query the remote device to know it's obex connection url and then it was used to send the file. So more generic way. This part almost made me to fail as I was not able to do while the port number was 9 with sony ericsson.

The other codes are there, you might find similarity with codes in the net. But what can i do , i am a google coder. So things are copy paste copy paste bla bla.

The application starts discovery first then tries to send a jpeg file from "C://a.jpg" file.

Enought talking, now the happy part, the Source Code :).
The full source can be found here. The code is not tested, i plugged my code from other projects and made a quick project. So if you find now working let me know.

By the way for linux things, you might have a look at here
For ubuntu 8.10 additional library is required, to install that library in terminal run this command
sudo apt-get install libbluetooth-dev

It will save your time, in ubuntu i was getting bluecove stack not found though my bluetooth device was there, just running the above command will solve the issue, And remember to include the bluecove-gpl-2.10.0 jar with your project. the gpl jar has to be with the same version of your main bluecove jar.

I think i am still not clear to you. what can i do i am bad at writing and explaining.

The next one i am wishing to write is "How you can receive contacts/vcard/business card" from mobile devices using obex.

First you have to install jdk by running this command in terminal
sudo apt-get install sun-java5-jdk sun-java5-plugin

for jdk 6
sudo apt-get install sun-java6-jdk sun-java6-plugin

Then download netbeans ide from here

The downloaded file will be a sh file, most probably in your desktop

Now open the terminal(from Application->Accessories)

Then go to your desktop folder or the folder in which you have downloaded the installer file

cd Desktop

Then run this command, the last portion of the command will be the name of the file you downloaded

sudo sh netbeans-6.5-ml-javase-linux.sh


That's it, your installer will start and the next processes are as usual.

More detailed instructions can be found in Netbeans Wiki page

Thursday, February 14, 2008

I am a newbie in applet programming and very bad at programming. A google programmer ;). Recently i was trying to make an applet which could upload file to a php server, i started to googling and found that there are a lot of this kind of applet and none of them are not free :(. So i wanted to write one of my own and failed immediately as i didn't know how to run an applet. Again googling and learned to write applets.
Then i started to google how to show the file system in an applet, againg googling and found a code which can show your file system in a good tree way. But it was a normal java application not an applet, but i found it was easy to add to an applet. This is the code how you can show your file system in an applet. Thanks goes to Kirill Grouchnikov.


import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;


/**
* @author Kirill Grouchnikov
*/
public class FileTreePanel extends JPanel implements TreeSelectionListener,InterfaceHttpResponse{
String serverAddress = "http://www.smdprogramming.com/shimul/fup3/";
//String serverAddress = "http://localhost/fup3/";
/**
* File system view.
*/
protected static FileSystemView fsv = FileSystemView.getFileSystemView();

/**
* Renderer for the file tree.
*
* @author Kirill Grouchnikov
*/
private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
/**
* Icon cache to speed the rendering.
*/
private Map iconCache = new HashMap();

/**
* Root name cache to speed the rendering.
*/
private Map rootNameCache = new HashMap();

/*
* (non-Javadoc)
*
* @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree,
* java.lang.Object, boolean, boolean, boolean, int, boolean)
*/
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
FileTreeNode ftn = (FileTreeNode) value;
File file = ftn.file;
String filename = "";
if (file != null) {
if (ftn.isFileSystemRoot) {
// long start = System.currentTimeMillis();
filename = this.rootNameCache.get(file);
if (filename == null) {
filename = fsv.getSystemDisplayName(file);
this.rootNameCache.put(file, filename);
}
// long end = System.currentTimeMillis();
// System.out.println(filename + ":" + (end - start));
} else {
filename = file.getName();
}
}
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
filename, sel, expanded, leaf, row, hasFocus);
if (file != null) {
Icon icon = this.iconCache.get(filename);
if (icon == null) {
// System.out.println("Getting icon of " + filename);
icon = fsv.getSystemIcon(file);
this.iconCache.put(filename, icon);
}
result.setIcon(icon);
}
return result;
}
}

/**
* A node in the file tree.
*
* @author Kirill Grouchnikov
*/
private static class FileTreeNode implements TreeNode {
/**
* Node file.
*/
public File file;

/**
* Children of the node file.
*/
private File[] children;

/**
* Parent node.
*/
private TreeNode parent;

/**
* Indication whether this node corresponds to a file system root.
*/
private boolean isFileSystemRoot;

/**
* Creates a new file tree node.
*
* @param file
* Node file
* @param isFileSystemRoot
* Indicates whether the file is a file system root.
* @param parent
* Parent node.
*/
public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
this.file = file;
this.isFileSystemRoot = isFileSystemRoot;
this.parent = parent;
this.children = this.file.listFiles();
if (this.children == null)
this.children = new File[0];
}

/**
* Creates a new file tree node.
*
* @param children
* Children files.
*/
public FileTreeNode(File[] children) {
this.file = null;
this.parent = null;
this.children = children;
}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#children()
*/
public Enumeration children() {
final int elementCount = this.children.length;
return new Enumeration() {
int count = 0;

/*
* (non-Javadoc)
*
* @see java.util.Enumeration#hasMoreElements()
*/
public boolean hasMoreElements() {
return this.count < elementCount;
}

/*
* (non-Javadoc)
*
* @see java.util.Enumeration#nextElement()
*/
public File nextElement() {
if (this.count < elementCount) {
return FileTreeNode.this.children[this.count++];
}
throw new NoSuchElementException("Vector Enumeration");
}
};

}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getAllowsChildren()
*/
public boolean getAllowsChildren() {
return true;
}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getChildAt(int)
*/
public TreeNode getChildAt(int childIndex) {
return new FileTreeNode(this.children[childIndex],
this.parent == null, this);
}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getChildCount()
*/
public int getChildCount() {
return this.children.length;
}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getIndex(javax.swing.tree.TreeNode)
*/
public int getIndex(TreeNode node) {
FileTreeNode ftn = (FileTreeNode) node;
for (int i = 0; i < this.children.length; i++) {
if (ftn.file.equals(this.children[i]))
return i;
}
return -1;
}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#getParent()
*/
public TreeNode getParent() {
return this.parent;
}

/*
* (non-Javadoc)
*
* @see javax.swing.tree.TreeNode#isLeaf()
*/
public boolean isLeaf() {
return (this.getChildCount() == 0);
}
}

/**
* The file tree.
*/
private JTree tree;

/**
* Creates the file tree panel.
*/
public FileTreePanel() {
this.setLayout(new BorderLayout());


File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(false);

final JScrollPane jsp = new JScrollPane(this.tree);
jsp.setBorder(new EmptyBorder(0, 0, 0, 0));
this.add(jsp, BorderLayout.CENTER);

tree.addTreeSelectionListener(this);


}

testapp ta;
/**
* Creates the file tree panel.
*/
public FileTreePanel(testapp ta) {
this.ta = ta;
this.setLayout(new BorderLayout());


File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(false);

final JScrollPane jsp = new JScrollPane(this.tree);
jsp.setBorder(new EmptyBorder(0, 0, 0, 0));
this.add(jsp, BorderLayout.CENTER);

tree.addTreeSelectionListener(this);


}
File currentFile= null;
public void valueChanged(TreeSelectionEvent e) {
// TODO Auto-generated method stub
FileTreeNode node = (FileTreeNode)
tree.getLastSelectedPathComponent();
System.out.println("slecte asldf "+node.isLeaf());
if(node.isLeaf())
{
currentFile = node.file;
System.out.println("File name "+currentFile.getName());
}
else
currentFile = null;


}


// public static void main(String[] args) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// JFrame frame = new JFrame("File tree");
// frame.setSize(500, 400);
// frame.setLocationRelativeTo(null);
// frame.add(new FileTreePanel());
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setVisible(true);
// }
// });
// }
}




Now to add it to my applet this was the code


import java.applet.Applet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.omg.CORBA.FREE_MEM;


public class testapp extends Applet{
JTextField field;
JButton jb;
FileTreePanel ftreePanel;
public void init() {
//Execute a job on the event-dispatching thread:
//creating this applet's GUI.

try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't successfully complete");
}

addItem(false, "initializing... ");
}

private void createGUI() {
ftreePanel = new FileTreePanel(this);
add(ftreePanel);

// File[] roots = File.listRoots();
// FileTreeNode rootTreeNode = new FileTreeNode(roots);
// this.tree = new JTree(rootTreeNode);
// this.tree.setCellRenderer(new FileTreeCellRenderer());
// this.tree.setRootVisible(false);
// add(tree);

//Create the text field and make it uneditable.
field = new JTextField();
field.setEditable(false);
field.setAutoscrolls(true);
jb= new JButton("Upload");
jb.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
uploadJob();
}

});
jb.setSize(50, 50);
//add(jb);
JPanel jp = new JPanel();
jp.add(jb);
add(jp);
//Set the layout manager so that the text field will be
//as wide as possible.
setLayout(new java.awt.GridLayout(1,0));

//Add the text field to the applet.
add(field);



//new FileTreePanel();
}

public void start() {
addItem(false, "starting... ");
}

public void stop() {
addItem(false, "stopping... ");
}

public void destroy() {
addItem(false, "preparing for unloading...");
cleanUp();
}

private void cleanUp() {
//Execute a job on the event-dispatching thread:
//taking the text field out of this applet.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
remove(field);
}
});
} catch (Exception e) {
System.err.println("cleanUp didn't successfully complete");
}
field = null;
}

private void addItem(boolean alreadyInEDT, String newWord) {
if (alreadyInEDT) {
addItem(newWord);
} else {
final String word = newWord;
//Execute a job on the event-dispatching thread:
//invoking addItem(newWord).
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
addItem(word);
}
});
} catch (Exception e) {
System.err.println("addItem didn't successfully complete");
}
}
}

//Invoke this method ONLY from the event-dispatching thread.
private void addItem(String newWord) {
String t = field.getText();
System.out.println(newWord);
field.setText(t + newWord);
}

void uploadJob(){
addItem("Upload button clicked");
ftreePanel.uploadFile();
}

void showMessage(String message)
{

field.setText(message);
}

}



you will some code are missing in previous FileTreePanel which will be added later on. The next thing came to my mind is how to get the node which is clicked in the file tree. It was very easy,u have to just implement the addTreeSelectionListener. For uploading part i used the java code which was posted previously during android file upload time. This function was added with FileTreePanel.java

public void uploadFile()
{
if(currentFile!= null)
{
ta.showMessage("Uploading file"+currentFile.getAbsolutePath());
System.out.println("Current file"+currentFile.getAbsolutePath());
String fileName = null;
try {
FileInputStream fis = new FileInputStream(currentFile);
fileName = currentFile.getName();
HttpFileUploader htfu = new HttpFileUploader(serverAddress+"test2.php","pngData", "", null,this);
System.out.println("File Name "+serverAddress+"test2.php");
htfu.doStart(fis,fileName);
ta.showMessage("Please wait");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ta.showMessage("File not found exception");
}
//ta.showMessage("Done Uploading file u can check at "+serverAddress+"uploads/"+fileName);

}
else
ta.showMessage("Not a file");

}


Now after completing everything the applet was running smoothly through Eclipse ide. But when i tried to run in browser the applet was not showing the file tree. I was in a problem then , I found that to access client pc resources you need to sign your applet with lengthy process. This link came great great help to me.

How to sign an applet

So after signing the applet it started to show it's face in the browser. The whole process took me 3 long days,damn i'm the slowest learner. You can check it here I don't know how long it will be available here. Whatever i am a happy monkey now. :D. You can find uploaded files here

[edited later]
The quest was not over yet, i was using jdk6 with jre6, so my applet was not showing into my friends pc whose jre was jre5.0. So i had to chnage the settings in eclipse and then remake the jar and the whole process.