Blackberry screen renew with new data - blackberry

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);
}
}
});

Related

Vaadin upload with PipedInputStream & PipedOutputStream example

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.

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

Suspended (exception IlegalStateException) blackberry 6.0

Following is the code which is showing the above exception on debugging :
Firstly I am trying to call a class HTTPConnection from the below menu item.
protected MenuItem _SelectDealerItem = new MenuItem("Select Dealer",100,10)
{
public void run()
{
new HTTPConnection();
}
};
In HTTPConnection Class I am checking the connection type and calling another Class TSelectDealerScreen:
public class HTTPConnection {
ConnectionFactory _factory = new ConnectionFactory();
public HTTPConnection()
{
int[] _intTransports = {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_WAP2,
TransportInfo.TRANSPORT_TCP_CELLULAR
};
for(int i=0;i<_intTransports.length;i++)
{
int transport = _intTransports[i];
if(!TransportInfo.isTransportTypeAvailable(transport)||!TransportInfo.hasSufficientCoverage(transport))
{
Arrays.removeAt(_intTransports,i);
}
}
TcpCellularOptions tcpOptions = new TcpCellularOptions();
if(!TcpCellularOptions.isDefaultAPNSet())
{
tcpOptions.setApn("My APN");
tcpOptions.setTunnelAuthUsername("user");
tcpOptions.setTunnelAuthPassword("password");
}
if(_intTransports.length>0)
{
_factory.setPreferredTransportTypes(_intTransports);
}
_factory.setTransportTypeOptions(TransportInfo.TRANSPORT_TCP_CELLULAR, tcpOptions);
_factory.setAttemptsLimit(5);
Thread t = new Thread(new Runnable()
{
public void run()
{
ConnectionDescriptor cd = _factory.getConnection("http://excellentrealtors.info/Smart-Trace/get_dealer.php");
if(cd!=null)
{
Connection c = cd.getConnection();
displayContent(c);
}
}
});
t.start();
}
private void displayContent(final Connection conn)
{
UiApplication.getUiApplication().pushScreen(new TSelectDealerScreen(conn));
}
}
In TSelectDealerScreen class i am simply trying to read the stream, but it is showing illegal state exception whenever i try to debug, I am not much familiar to blackberry programming, kindly advice.
public class TSelectDealerScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public TSelectDealerScreen(Connection conn)
{
_rtfOutput.setText("Retrieving Data.Please Wait");
add(_rtfOutput);
ContentReaderThread t = new ContentReaderThread(conn);
t.start();
}
private final class ContentReaderThread extends Thread {
private Connection _connection;
ContentReaderThread(Connection conn)
{
_connection = conn;
}
public void run()
{
String result = "";
OutputStream os = null;
InputStream is = null;
try
{
OutputConnection outputConn = (OutputConnection)_connection;
os = outputConn.openOutputStream();
String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
os.write(getCommand.getBytes());
os.flush();
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) _connection;
is = inputConn.openInputStream();
byte[] data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
result = new String(data, "US-ASCII");
// is.close();
System.out.print(result);
}
catch(Exception e)
{
result = "ERROR fetching content: " + e.toString();
}
finally
{
// Close OutputStream
if(os != null)
{
try
{
os.close();
}
catch(IOException e)
{
}
}
// Close InputStream
if(is != null)
{
try
{
is.close();
}
catch(IOException e)
{
}
}
// Close Connection
try
{
_connection.close();
}
catch(IOException ioe)
{
}
}
// Show the response received from the web server, or an error message
showContents(result);
}
}
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
In your HTTPConnection class, you do:
Thread t = new Thread(new Runnable()
{
public void run()
{
ConnectionDescriptor cd = _factory.getConnection("http://excellentrealtors.info/Smart-Trace/get_dealer.php");
if(cd!=null)
{
Connection c = cd.getConnection();
displayContent(c);
}
}
});
t.start();
That runs everything inside run() on a background thread. But, inside displayContent(c), you do:
UiApplication.getUiApplication().pushScreen(new TSelectDealerScreen(conn));
which is a UI operation.
Trying to modify the UI from a background thread normally causes an IllegalStateException.
I believe you just need to wrap the call to pushScreen() with this:
private void displayContent(final Connection conn) {
final UiApplication app = UiApplication.getUiApplication();
app.invokeLater(new Runnable() {
public void run() {
// this code is run on the UI thread
app.pushScreen(new TSelectDealerScreen(conn));
}
});
}
Also, if you're an Android developer, and you want help doing normal background/UI thread stuff, you might check out this other answer I wrote on "porting" AsyncTask to BlackBerry Java

How to determine the state of the GPS in BlackBerry?

i want to know how determine the state of the GPS, soo if the state is different to AVAILABLE i don't create the Listener to save battery.
But in execution always enter for the else create the LocationListener and not for the if.
Here is my code
public class UpdateGPS extends Thread{
public void run(){
while (true){
try{
getGPS();
sleep(30000); //Update GPS for each 30secs
}
catch(Exception e){}
}
}
}
public void getGPS() {
String state = "RUNNING";
BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);
try {
locationProvider = LocationProvider.getInstance(myCriteria);
if (locationProvider != null) {
if (locationProvider.getState() != locationProvider.AVAILABLE) {
state= "STOP";
}
else {
locationProvider.setLocationListener(
new LocationListenerImplementacion(),valor_reintento, -1, -1);
}
}
}
catch(Exception e) {}
}
private class LocationListenerImplementacion implements LocationListener {
public void locationUpdated(LocationProvider provider,Location location) {
if (location.isValid()) {
//GET DATA
}
else {}
public void providerStateChanged(LocationProvider provider, int newState){
}
}

How to save captured image in a folder in blackberry?

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?

Resources