I am developing application which has camera functionality. i want to save that captured image in my project folder.Can any one help me please.
thanx in advance.
This below code may help you:
Add this to Main Screen which you want to show the camera:
captureImage=new MenuItem("Capture Images",10,100)
{
public void run()
{
synchronized (Application.getEventLock())
{
captureImage();
}
}
};
addMenuItem(captureImage);
The code for captureImage() method is:
private void captureImage()
{
try
{
player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
player.realize();
_videoControl = (VideoControl) player.getControl("VideoControl");
if (_videoControl != null)
{
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
_videoControl.setVisible(true);
player.start();
if(videoField != null)
{
add(videoField);
}
}
}
catch(Exception e)
{
if(player!=null)
{
player.close();
}
Dialog.alert(e.toString());
}
}
The below code is save the image into the sdcard or device card. Override the invokeAction(int action) Method
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if(SdcardTest.SdcardAvailabulity())//I am checking here that the sdcard is there of or not.....?
{
//PATH = "file:///SDCard/BlackBerry/pictures/"+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
}
else
{
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled)
{
if(action == ACTION_INVOKE)
{
try
{
byte[] rawImage = _videoControl.getSnapshot(null);
fileconn=(FileConnection)Connector.open(PATH);
if(fileconn.exists())
{
fileconn.delete();
}
fileconn.create();
OutputStream os=fileconn.openOutputStream();
os.write(rawImage);
fileconn.close();
os.close();
Status.show("Image is Captured",200);
if(player!=null)
player.close();
}
catch(Exception e)
{
if(player!=null)
{
player.close();
}
if(fileconn!=null)
{
try
{
fileconn.close();
}
catch (IOException e1)
{
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
try this for image snap
Note: you can not store in resource folder you can only store in SDcard
class screen extends MainScreen implements FieldChangeListener
{
private VideoControl vc;
private String encoding;
private Player p;
private Field viewFinder;
private BitmapField bitmapField;
private ButtonField btn;
public screen() {
btn=new ButtonField("snap",Field.FOCUSABLE);
btn.setChangeListener(this);
add(btn);
}
public void fieldChanged(Field field, int context) {
if(field==btn)
{
try{
p = Manager.createPlayer("capture://video");
p.realize();
p.prefetch();
p.start();
vc = (VideoControl) p.getControl("VideoControl");
viewFinder = (Field)vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
vc.setVisible(true);
final String imageType = "encoding=jpeg&width=640&height=480&quality=superfine";
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
byte[] image = vc.getSnapshot(imageType);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/pictures/"+System.currentTimeMillis()+".jpeg", Connector.READ_WRITE);
conn.create();
OutputStream out = conn.openOutputStream();
out.write(image);
out.flush();
out.close();
conn.close();
Bitmap image1 = Bitmap.createBitmapFromBytes(imageBytes, 0, imageBytes.length, 4);
bitmapField.setBitmap(image1);
add(bitmapField);
}
});
} catch (Exception me){
}
}
}
}
for more operations please use this
http://supportforums.blackberry.com/rim/attachments/rim/java_dev#tkb/226/1/SnapshotSample.zip
if you want to save an image from camera to your device you can use the following code.
try
{
focusControl.startAutoFocus();
byte[] image = videoControl.getSnapshot(null);
String message = "Captured "+image.length+" bytes of JPG data";
debug(message);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/pictures/"+(new Date()).getTime()+".jpg", Connector.READ_WRITE);
conn.create();
OutputStream out = conn.openOutputStream();
out.write(image);
out.flush();
out.close();
conn.close();
Dialog.alert(message);
}
catch (Exception e) {
Dialog.alert("Capture failed due to: "+e.getMessage());
}
If you want to save the images in your Project/res or Project/src during runtime, you cant do that.
You can save image in SDcard/device.
Why would you want to save it in your project source?
Related
I just started learning Vaadin 8 and my first example is Upload button. I was stuck with an issue where I could not solve the problem for many hours and hours.
Here it is,
I am returning PipedOutputStream in the receiveUpload method,
Here is the code for receiveUpload method,
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
pipedInputStream = new PipedInputStream(pipedOutputStream);
if (filename == null || filename.trim().length() == 0) {
upload.interruptUpload();
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
return pipedOutputStream;
}
In the uploadSucceeded method, I need to take the pipedinputstream and send it another method to load the stream into the database
public void uploadSucceeded(SucceededEvent event) {
try {
fileUploadOperation.upload(pipedInputStream); --> I need to push all the stream data in one go into a method to generate a file at the business layer
} catch (Exception e) {
e.printStackTrace();
}
}
When I was running the application, it hangs out for a long time and I could not figure out where it is. Later I could notice that both piped input and piped output streams should be created in separate threads or at least one of them in a separate thread but don't know how to handle it.
Any help
I am pasting the complete class for more information,
public class WebCommunityView implements Receiver, FailedListener, SucceededListener, StartedListener, FinishedListener {
private PipedOutputStream pipedOutputStream = null;
private PipedInputStream pipedInputStream = null;
private Upload upload = null;
private String fileName = null, mimeType = null;
private Grid<FileListProperties> fileListGrid = null;
public final static WebCommunityView newInstance(WebContentScreen screen) {
vw.initBody();
return vw;
}
protected void initBody() {
VerticalLayout verticalLayout = new VerticalLayout();
fileListGrid = new Grid<FileListProperties>();
fileListGrid.addColumn(FileListProperties::getCreatedDate).setCaption("Date");
fileListGrid.addColumn(FileListProperties::getFileName).setCaption("File Name");
fileListGrid.addColumn(FileListProperties::getUserName).setCaption("User Name");
fileListGrid.addComponentColumn(this::buildDownloadButton).setCaption("Download");
fileListGrid.setItems(loadGridWithFileInfo());
upload = new Upload("", this);
upload.setImmediateMode(false);
upload.addFailedListener((Upload.FailedListener) this);
upload.addSucceededListener((Upload.SucceededListener) this);
upload.addStartedListener((Upload.StartedListener) this);
upload.addFinishedListener((Upload.FinishedListener) this);
Label fileUploadLabel = new Label("Label"));
verticalLayout.addComponent(currentListLabel);
verticalLayout.addComponent(fileListGrid);
verticalLayout.addComponent(fileUploadLabel);
verticalLayout.addComponent(upload);
mainbody.addComponent(verticalLayout);
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
//Model Layer
fileUploadOperation.upload(pipedInputStream);
fileUploadOperation.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void uploadFailed(FailedEvent event) {
if (event.getFilename() == null) {
Notification.show("Upload failed", Notification.Type.HUMANIZED_MESSAGE);
}
try {
//Model Layer
fileUploadOperation.abort();
} catch (Exception e) {
e.printStackTrace();
}
}
public OutputStream receiveUpload(String filename, String mimeType) {
this.fileName = filename;
this.mimeType = mimeType;
try {
pipedOutputStream = new PipedOutputStream();
new Thread() {
public void run() {
try {
System.out.println("pipedInputStream Thread started");
pipedInputStream = new PipedInputStream(pipedOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
if (filename == null || filename.trim().length() == 0) {
screen.displayMessage("Please select a file to upload !", WebContentScreen.MESSAGE_TYPE_WARNING);
upload.interruptUpload();
} else {
Properties properties = new Properties();
properties.setProperty("NAME", fileName);
properties.setProperty("MIME_TYPE", mimeType);
//Model Layer
fileUploadOperation.initialize(properties);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("pipedOutputStream:"+pipedOutputStream);
return pipedOutputStream;
}
private List<FileListProperties> loadGridWithFileInfo() {
List<FileListProperties> list = null;
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
try {
list = new ArrayList<FileListProperties>(1);
Collection<FileInfo> fileInfoList = fileCommandQuery.lstFilesForDownload();
for (Iterator iterator = fileInfoList.iterator(); iterator.hasNext();) {
FileInfo fileInfo = (FileInfo) iterator.next();
Properties properties = fileInfo.getProperties();
Collection<String> mandatoryParameters = fileInfo.getMandatoryProperties();
FileListProperties fileListProperties = new FileListProperties();
for (Iterator iterator2 = mandatoryParameters.iterator(); iterator2.hasNext();) {
String key = (String) iterator2.next();
String value = properties.getProperty(key);
if (key != null && key.equalsIgnoreCase("NAME")) {
fileListProperties.setFileName(value);
} else if (key != null && key.equalsIgnoreCase("USER_NAME")) {
fileListProperties.setUserName(value);
} else if (key != null && key.equalsIgnoreCase("CREATED_DATE")) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1550566760000L);
fileListProperties.setCreatedDate(dateFormat.format(calendar.getTime()));
}
}
if (fileListProperties != null) {
list.add(fileListProperties);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dateFormat = null;
}
return list;
}
private Button buildDownloadButton(FileListProperties fileListProperties) {
Button button = new Button("...");
button.addClickListener(e -> downloadFile(fileListProperties));
return button;
}
private void downloadFile(FileListProperties fileListProperties) {
}
}
The problem in your example is that you need to do the actual file handling in a separate thread. The Viritin add-on contains a component called UploadFileHandler that simplifies this kind of usage a lot. It will provide you InputStream to consume. The integration test for the component contains this kind of usage example.
Also, my recent blog entry about the subject might help.
How to get camera captured images after native camera app exits ?
How to create an Bitmap image from the already existing SD card Jpeg image ?
I want to add this Bitmap to the screen.
ButtonField btn_Take_Pic = new ButtonField("Take a pic",Field.FIELD_HCENTER|FOCUSABLE)
{
protected boolean navigationClick(int status, int time) {
// TODO Auto-generated method stub
InvokeCameraScreen screen = new InvokeCameraScreen(CaptureImage.this);
screen.addCam();
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
//Perform screen changes here.
//Calling invalidate() on your screen forces the paint
//method to be called.
CaptureImage deal_Screen = new CaptureImage();
deal_Screen.invalidate();
}
});
return true;
}
};
Add body part of ImagePath() method
public void ImagePath(String path) {
try
{
Img_path = path;
EncodedImage.createEncodedImage(imgarr,0,imgarr.length);
Bitmap setimage = resizeBitmap(getBitmapFromFile(info.getImg_Path()),(int) (ScreenWidth *0.20),(int) (ScreenHeight *0.20));
Img_Field.setBitmap(setimage);
}
catch (Exception e) {
// TODO: handle exception
Dialog.alert("Ex path: " + e.toString());
}
}
implements ImagePath interface
public interface ImagePath {
public void ImagePath(String path);
}
public class InvokeCameraScreen implements FileSystemJournalListener {
private long lastUSN;
private String resultData, imagepath;
private VerticalFieldManager addToSCreen;
private boolean isAlreadeyExcuted = true;
private byte[] imageData;
private ImagePath pathImage;
public InvokeCameraScreen(ImagePath path) {
this.pathImage = path;
}
public void addCam() {
isAlreadeyExcuted = true;
getAddToSCreen().deleteAll();
startCam();
}
private void startCam() {
lastUSN = FileSystemJournal.getNextUSN();
UiApplication.getUiApplication().addFileSystemJournalListener(this);
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
});
} catch (Exception e) {
System.out.println("CheckinFormScreen Exception: " + e.toString());
}
}
private void closeCamera() {
System.out.println("Closing Cam");
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 25);
inject.post();
try {
Thread.sleep(500);
} catch (Exception e) {
}
UiApplication.getUiApplication().removeFileSystemJournalListener(this);
System.out.println("Done with closing cam");
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public void fileJournalChanged() {
try {
closeCamera();
} catch (Exception e) {
}
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
String path = entry.getPath();
if (path != null && path.indexOf(".jpg") != -1) {
if (isAlreadeyExcuted) {
isAlreadeyExcuted = false;
resultData = "file://" + path;
pathImage.ImagePath(resultData);
// ShowUploadImage(resultData);
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0, 25);
inject.post();
inject.post();
if (Display.getWidth() == 480
&& Display.getHeight() == 360
|| Display.getWidth() == 360
&& Display.getHeight() == 480) {
try {
Thread.sleep(500);
inject.post();
} catch (Exception e) {
}
}
}
}
return;
}
}
}
public VerticalFieldManager getAddToSCreen() {
if (addToSCreen == null) {
addToSCreen = new VerticalFieldManager();
addToSCreen.setPadding(10, 10, 10, 10);
}
return addToSCreen;
}
public void setAddToSCreen(VerticalFieldManager addToSCreen) {
this.addToSCreen = addToSCreen;
}
private void ShowUploadImage(String path) {
}
}
try this,
CAll Below Class Like:
EncodedImage result = NcCamera.getInstance().getPictureTaken();
//
This is class in which you can get Camera images.
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class NcCamera extends MainScreen
{
private VideoControl videoControl;
private Field videoField;
public static EncodedImage pictureTaken = null;
private boolean initialized = false;
private boolean result;
public static boolean CAPTURING_DONE = true;
public static boolean CAPTURING_CANCELED = false;
private VerticalFieldManager main;
private static NcCamera instance;
CommonFunction cmn_fun;
public static byte[] raw;
public NcCamera()
{
super(NO_VERTICAL_SCROLL);
main = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
{
// I wan't to force the backgound to black
public void paintBackground(Graphics g)
{
g.setBackgroundColor(0x000000);
g.clear();
}
};
super.add(main);
}
public void add(Field field)
{
main.add(field);
}
public EncodedImage getPictureTaken()
{
return pictureTaken;
}
public Screen getThisScreen()
{
return this;
}
public void reset()
{
pictureTaken = null;
result = CAPTURING_CANCELED;
}
public boolean showDialog()
{
result = CAPTURING_CANCELED;
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushModalScreen(getThisScreen());
if (pictureTaken != null)
result = CAPTURING_DONE;
}
});
return result;
}
public static NcCamera getInstance()
{
if (instance == null)
instance = new NcCamera();
return instance;
}
public void onDisplay() {
if (!initialized)
{
initializeCamera();
if (videoField!=null) add(videoField);
else {
LabelField sorry = new LabelField("Sorry, we cannot use camera right now.") {
// I need to force the label to be white colored to be visible above
// it's underlying manager (that is black).
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xffffff);
super.paint(g);
g.setColor(color);
}
};
add(sorry);
}
initialized = true;
}
}
private void initializeCamera()
{
try {
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
if (videoControl != null)
{
videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
}
player.start();
} catch (Exception e)
{
}
}
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if (!handled)
{
switch (action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void takePicture()
{
try {
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
raw = videoControl.getSnapshot(null);
// SaveImageSdcard(raw);
Bitmap img= Bitmap.createBitmapFromBytes(raw, 0, raw.length,3);
Constants.PICTURE_TAKEN=cmn_fun.resizeBitmap(img, 150, 150);
// save the picture taken into pictureTaken variable
pictureTaken = EncodedImage.createEncodedImage(raw, 0, raw.length);
result = CAPTURING_DONE;
close();
} catch (Exception e)
{
}
}
}
public boolean keyDown(int keycode,
int time) {
if (keycode == 1769472)
{ // escape pressed
reset();
close();
return true;
}
return super.keyDown(keycode, time);
}
}
Please anybody let me know how to work with this code, I want to display the Contact Photo on screen. getting null from getPhoto() method. I searched a lot but got nothing apart from this code from Contact Interface. but its not working for me.....!!!
public class PhotoExample {
private Contact _contact;
public PhotoExample(Contact contact) throws PIMException {
ContactList contactList = (ContactList)
PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);
_contact = contactList.createContact();
/*_contact = contact;*/
}
public void setPhoto() throws IOException {
byte[] photo = getSamplePhoto();
byte[] photoEncoded = Base64OutputStream.encode(photo, 0, photo.length, false, false);
if (_contact.countValues(Contact.PHOTO) > 0) {
_contact.setBinary(Contact.PHOTO, 0, PIMItem.ATTR_NONE, photoEncoded, 0, photo.length);
} else {
_contact.addBinary(Contact.PHOTO, PIMItem.ATTR_NONE, photoEncoded, 0, photo.length);
}
}
public byte[] getPhoto() throws IOException {
if (_contact.countValues(Contact.PHOTO) > 0) {
byte[] photoEncoded = _contact.getBinary(Contact.PHOTO, 0);
return Base64InputStream.decode(photoEncoded, 0, photoEncoded.length);
} else {
return null;
}
}
private static byte[] getSamplePhoto() {
return null;
// return the raw bytes of the photo to use
}
/*public static void main(String[] args) throws Throwable {
PhotoExample example = new PhotoExample();
example.setPhoto();
example.getPhoto();
}*/
}
I am using the above code like this: -
try {
_photo = new PhotoExample(_contact);
b = _photo.getPhoto();
} catch (PIMException e) {
System.out.println(e+"===>");
e.printStackTrace();
} catch (IOException e) {
System.out.println(e+"===>");
e.printStackTrace();
}
After a long time , I tried this task again after a few searching, now i got success and want to share as this code may be useful for many.
BlackBerryContactList contactList = (BlackBerryContactList)BlackBerryPIM.getInstance().openPIMList(BlackBerryPIM.CONTACT_LIST, BlackBerryPIM.READ_WRITE);
Enumeration contactListItems = contactList.items();
while (contactListItems.hasMoreElements()) {
BlackBerryContact contact = (BlackBerryContact)contactListItems.nextElement();
byte[] imageBytesBase64 = contact.getBinary(BlackBerryContact.PHOTO, 0);
byte[] imageBytes = null;
try {
imageBytes = Base64InputStream.decode(imageBytesBase64, 0, imageBytesBase64.length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EncodedImage encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
Bitmap bitmap = encodedImage.getBitmap();
bitmaps.addElement(bitmap);
BitmapField fd= new BitmapField(bitmap, Field.FIELD_HCENTER);
add(fd);
Hi i made one small application to show all sdcard images should display in my application as Thumbnail view .my program is like following
Here problem is that in simulator it loads fast and accurate where as phone it take lots of time. it is loaded some of 30MB around not getting problem. whare it is 80MB around it is not showing images on my screen.
Note: This is perfectly working in simulator but Not device
and my images path is "file:///SDCard/images/"
My code is:
this is my application starter class
public class StartUp extends UiApplication{
public static void main(String[] args) {
StartUp start=new StartUp();
start.enterEventDispatcher();
}
public StartUp() {
pushScreen(new ViewerMainScreen());
}
}
this is my ViewerMainScreen.java
public class ViewerMainScreen extends MainScreen implements FieldChangeListener{
private ObjectListField fileList;
private String currentPath = "file:///";
public VerticalFieldManager vert_manager=null;
private BitmapField before[]=null,next[]=null;
private int size=0;Border b1,b2;
TableLayoutManager colFMgr=null;
private Vector img_data=null;
private int count=0;
public ViewerMainScreen() {
super();
setTitle("Browse to image...");
initGUI();
}
public void initGUI() {
try {
// add(getFileList());
img_data=getAllList("file:///SDCard/images");
b1=BorderFactory.createSimpleBorder(new XYEdges(3,3,3,3),new XYEdges(Color.RED, Color.RED, Color.RED, Color.RED),Border.STYLE_SOLID);
b2=BorderFactory.createSimpleBorder(new XYEdges(0,0,0,0));
size=img_data.size();
before=new BitmapField[size];
next=new BitmapField[size];
vert_manager=new VerticalFieldManager(VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(),Display.getHeight());
}
};
colFMgr = new TableLayoutManager(new int[] {
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
}, Manager.HORIZONTAL_SCROLL|VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
for(int i= 0;i < size;i++)
{
EncodedImage load_img=EncodedImage.getEncodedImageResource("loading.jpg");
before[i] = new BitmapField(load_img.getBitmap(),Field.FOCUSABLE){
protected boolean navigationClick(int status,int time) {
fieldChangeNotify(0);
return super.navigationClick(status, time);
}
protected void onFocus(int direction)
{
this.setBorder(b1);
invalidate();
}
protected void onUnfocus()
{
this.setBorder(b2);
invalidate();
}
};
colFMgr.add(before[i]);
}
add(colFMgr);
Thread t=new Thread(){
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
callImageThread();
}
};
t.start();
} catch (Exception e) {
Dialog.alert(e.getMessage());
}
}
private void callImageThread() {
for(int i=0;i<size;i++)
{
if(count==6){
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageThread th=new ImageThread(this, "file:///SDCard/images/"+img_data.elementAt(i), i);
th.start();
count++;
}
}
public void ReplaceImage(EncodedImage img,int index)
{
before[index].setBitmap(img.getBitmap());
before[index].setChangeListener(this);
count--;
System.out.println("Thread count: ========================"+Thread.activeCount()+"============================================="+count);
}
public void fieldChanged(Field field, int context) {
for(int i=0;i<size;i++)
{
if(field==before[i])
{
synchronized (UiApplication.getEventLock()) {
EncodedImage img=null;
img=loadFile("file:///SDCard/images/"+img_data.elementAt(i));
int displayWidth = Fixed32.toFP(Display.getWidth()-100);
int imageWidth = Fixed32.toFP(img.getWidth());
int scalingFactorX = Fixed32.div(imageWidth, displayWidth);
int displayHeight = Fixed32.toFP(Display.getHeight()-100);
int imageHeight = Fixed32.toFP(img.getHeight());
int scalingFactorY = Fixed32.div(imageHeight, displayHeight);
EncodedImage scaledImage = img.scaleImage32(scalingFactorX, scalingFactorY);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(scaledImage));
}
}
}
}
public void displayMessage(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform(message);
}
});
}
private Vector getAllList(String path){
Vector data=new Vector();
FileConnection fileConnection=null;
try{
fileConnection = (FileConnection) Connector.open(path);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list();
while (directoryEnumerator.hasMoreElements()) {
data.addElement(directoryEnumerator.nextElement());
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return data;
}
private EncodedImage loadFile(String path) {
FileConnection fileConnection =null;
InputStream inputStream =null;
EncodedImage encodedImage=null;
try {
fileConnection = (FileConnection) Connector.open(path);
if(fileConnection.exists()){
inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int)fileConnection.fileSize()];
inputStream.read(imageBytes);
encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (IOException e) {
Dialog.alert("Insert an SD Card.");
}
return encodedImage;
}
}
This is my ImageThread.java
public class ImageThread extends Thread{
private ViewerMainScreen screen;
private String path;
private int index;
private EncodedImage scaledImage=null;
public ImageThread(ViewerMainScreen screen,String path,int index) {
this.screen=screen;
this.path=path;
this.index=index;
}
public void callMainScreen(EncodedImage eimg,int Rindex) {
screen.ReplaceImage(eimg, Rindex);
}
public void run() {
FileConnection fileConnection =null;
InputStream inputStream =null;
EncodedImage encodedImage=null;
try {
fileConnection = (FileConnection) Connector.open(path);
if(fileConnection.exists()){
inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int)fileConnection.fileSize()];
inputStream.read(imageBytes);
encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
int displayWidth = Fixed32.toFP(100);
int imageWidth = Fixed32.toFP(encodedImage.getWidth());
int scalingFactorX = Fixed32.div(imageWidth, displayWidth);
int displayHeight = Fixed32.toFP(100);
int imageHeight = Fixed32.toFP(encodedImage.getHeight());
int scalingFactorY = Fixed32.div(imageHeight, displayHeight);
scaledImage = encodedImage.scaleImage32(scalingFactorX, scalingFactorY);
callMainScreen(scaledImage, index);
}
} catch (IOException e) {
Dialog.alert("Insert an SD Card.");
}
finally
{
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
please help me how to increase performance of my code
I would load images only when user scrolls screen. For example load first two screens on screen start (in different thread) and load next when user is moving down. So set ScrollListener to your manager and use field postion and height to determine which is on the screen and which is going to be on screen soon.
Also use limited size thread pool and queue for images loading. Unfortunately java concurrent is not par of j2me. But there are several similar pattern implementations, like ThreadPool.
And It would be super if you also remember case when user scrolls fast - cancel scheduled loading if it's not required. For every loading task remember BitmapField position and size. Before task starts file loading check if BitmapField is visible (going to be visible) with current scroll position.
Also be aware about threads count. I see that you try to sleep main loading thread when count is 6. But there is still small possibility that 400 ms is not enough to finish work for current threads and you can easily start to create more threads.
Also minor things - use Bitmap.scaleInto (If you target is 5.0+), use synchronization around size field, next is never used, use a little better names like nextImages, threadsCount, etc.
I am developing a Blackberry Application. I have a map in a screen. I want to refresh map's data with new data which i am getting from my web service. I am using BlockingSenderDestination in a Thread. When i request "get data" its return new data. no problem. I am using invokelater function to call my maprefresh function with passing arguments but i got illegalargumentexception.
Any suggestion to solve my problem or any better way to do this?
Here is my code:
public class MyMainScreen extends MainScreen {
RichMapField map;
MyClassList _myclassList;
private String _result2t;
public MyMainScreen(JSONArray jarray)
{
map = MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
private void GetTerminals(String companyNo){
final String companyNoR= companyNo;
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://webservice";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("o", URI.create(uriStr));
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("o"),
URI.create(uriStr)
);
}
response = bsd.sendReceive();
if(response != null)
{
BSDResponse(response,companyNoR);
}
}
catch(Exception e)
{
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
private void BSDResponse(Message msg,final String companyNo)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result2t = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result2t = new String(data);
}
}
try {
final JSONArray jarray= new JSONArray(_result2t);
final String username=_userName;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("The Toolbar i");
Yenile(jarray);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Yenile(JSONArray jarray){
MapDataModel mapDataModel = map.getModel();
mapDataModel.remove("1");
map.getMapField().update(true);
_terminalList = new TerminalList();
map= MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray_terminaller.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
}
To refresh the screen: do like this:
public class LoadingScreen extends MainScreen{
LoadingScreen()
{
createGUI();
}
public void createGUI()
{
//Here you write the code that display on screen;
}}
we know that this is the actual way of creating a screen;
Now if you want to refresh the screen write like below:
deleteAll();
invalidate();
createGUI();//here it creates the screen with new data.
Instead of writing in InvokeLater method better to write the above three lines in run method after Thread.sleep(10000);
If you have any doubts come on stackOverFlow chat room name "Life for Blackberry" for clarify your and our doubts.
I found a solution to my question.
After getting the data i was sending it via new run method:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
MyFunction(jarray);
}});
But i was need to synchronize with main thread. So the solution:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized(Application.getEventLock()) {
Yenile(jarray);
}
}
});