I have written following piece of code. It is used to create camera player. I tested it on nokia phones. It's working fine and I am able to see camera and use its functionality.
But the issue is that when the code is tested on samsung phone it throws Media exception and eventually have to make an exit from the application. Due to this code, my inbuilt camera functionality (i.e. on samsung phone) also stops working. So what's the reason to it?
public void startCamera()
{
try
{
try
{
// if player==null
player = createPlayer();
}
catch (Exception ex)
{
ex.printStackTrace();
ErrorDialog.show(ex, "We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
try
{
player.realize();
player.prefetch();
}
catch (MediaException ex)
{
ex.printStackTrace();
ErrorDialog.show(ex, "We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
//Grab the video control and set it to the current display.
videoControl = (VideoControl)(player.getControl("VideoControl"));
if (videoControl == null)
{
//discardPlayer();
stopCamera();
ErrorDialog.show("Unsupported:\n"+
"Can't get video control\n"+
"We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
mediaComponent = new MediaComponent(player);
mediaComponent.setFocusable(false);
m_cameraScreen.showCamera(mediaComponent);
start();
}
catch(Exception ex)
{
ex.printStackTrace();
//discardPlayer();
stopCamera();
ErrorDialog.show("Sorry,Resources unavailable.\nWe are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
}
private Player createPlayer()throws MediaException, Exception
{
Player mPlayer = null;
// try capture://image first for series 40 phones
try
{
mPlayer = Manager.createPlayer("capture://image");
}
catch (Exception e)
{
e.printStackTrace();
}
catch (Error e)
{
e.printStackTrace();
}
// if capture://image failed, try capture://video
if (mPlayer == null)
{
try
{
mPlayer = Manager.createPlayer("capture://video");
}
catch (Exception e)
{
e.printStackTrace();
throw new MediaException("Sorry,Resources unavailable.");
}
}
if(mPlayer == null)
throw new Exception("Sorry,Resources unavailable.");
return mPlayer;
}
First things first, you have to realize that printStackTrace() is pretty much useless outside of the emulator unless you are using a Symbian phone.
You can also use java.lang.Throwable instead of separating Exception and Error
You can figure out exactly what happens by gathering information as a String and appending it to a simple lcdui Form while you are testing:
try {
// do something that could potentially fail
} catch (Throwable th) {
myDebugLcduiForm.append("potential failure number xx." + th + th.getMessage());
// if necessary, throw a new RuntimeException
}
You might want to update/repost your question once you know exactly what line of code throws what exception.
Related
We are developing normal bar code scanner app for windows surface tablets. In onNavigatedTo method of page we are invoking camera..
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
await App.camera.InitializeAsync(new MediaCaptureInitializationSettings
{
VideoDeviceId = devices[1].Id
});
cap.Source = App.camera;
cap.Visibility = Visibility.Visible;
await App.camera.StartPreviewAsync();
It is working fine.
Now App goes to background and comes back to foreground. But we are unable to invoke camera
again on resume using same code
await App.camera.StartPreviewAsync();
How to do it?
You need to use events such as Activated and VisibilityChanged :
private MediaCapture m_mediaCaptureMgr;
public MainPage()
{
this.InitializeComponent();
Window.Current.Activated+=Current_Activated;
Window.Current.VisibilityChanged+= Current_VisibilityChanged;
}
And then Initialize and StartPreview your camera on Current_Activated :
private async void Current_Activated(object sender, WindowActivatedEventArgs e)
{
try
{
m_mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
await m_mediaCaptureMgr.InitializeAsync();
cap.Source = m_mediaCaptureMgr;
await m_mediaCaptureMgr.StartPreviewAsync();
}
catch (Exception exception)
{
new MessageDialog("Unable to start the video capture.").ShowAsync();
}
}
And Stop Camera on Current_VisibilityChanged :
private async void Current_VisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
try
{
await m_mediaCaptureMgr.StopPreviewAsync();
}
catch (Exception exception)
{
}
}
I have a panel with a JTabbedpane and in every tab you can set parameters to execute a query. When one query is busy retrieving his data from the database, you can already open a new tab to set the new parameters. To avoid overload on the database only one query may be executed at once. But when you click execute the program must remember which queries to execute in the right order. During the execution a loader icon is shown and the GUI may not be frozen, because there is a stop button you can click to stop the execution.
I used a swingworker to avoid the GUI from blocking while executing the query and that works fine. But now I want to prevent the next query to start before the previous has finished. In a model, common for the whole panel, I initialized a semaphore: private final Semaphore semaphore = new Semaphore(1, true);
This is the code which starts the swingworker (I've added println commands to see which is started, stopped or finished)
private void doStoredQuery() {
try {
semaphore.acquire();
System.out.println(queryName + "started");
worker.execute();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
And this is my swingworker (initializeWorker() is called from the constructor of the main class):
private SwingWorker<StoredQueryDataModel, Integer> initializeWorker() {
worker = new SwingWorker<StoredQueryDataModel, Integer>() {
#Override
protected StoredQueryDataModel doInBackground() throws Exception {
try {
StoredQueryDataModel dataModel = null;
publish(0);
try {
dataModel = new StoredQueryDataModel(queryRunner, ldbName, queryName, params);
} catch (S9SQLException e) {
//
} catch (Throwable e) {
showErrorMessage(e);
}
return dataModel;
}
finally {
semaphore.release();
System.out.println(queryName + "finished");
}
}
#Override
protected void process(List<Integer> chunks) {
//ignore chunks, just reload loader icon
panel.repaint();
}
#Override
protected void done() {
String error;
try {
result = get();
error = null;
} catch (Exception e) {
error = e.getMessage();
}
if(result == null) {
semaphore.release();
System.out.println(queryName + " stopped");
}
if(error == null) {
// process result
}
else {
showErrorMessage(new Throwable(error));
}
}
};
return worker;
}
I've tried putting the acquire and release on other positions in the code, but nothing seems to work. I am bot in Swingworker and sempahores quite new... Can someone help?
I have found the problem: the semaphore had to be a static variable. In my code there were as many semaphores as there are tabs, which caused them to run at the same time instead of sequentially.
I have problem restart sound in J2ME. I want to create player in constructor, then call playExplosion() to play it, but it only plays once. I'm using Wireless Toolkit.
Sound class
public class Sound () {
private Player playerExplosion;
public Sound() throws IOException, MediaException {
// Explosion
InputStream is = getClass().getResourceAsStream("/explosion.mid");
playerExplosion = Manager.createPlayer(is, "audio/midi");
playerExplosion.realize();
playerExplosion.setLoopCount(1);
}
public void playExplosion() {
try {
System.out.println(playerExplosion.getState());
playerExplosion.start();
} catch (MediaException ex) {
ex.printStackTrace();
}
}
}
MyMIDlet class
public class MyMIDlet extends MIDlet() {
public Sound sound;
public MyMIDlet() {
// Init sound object
try {
sound = new Sound(this);
} catch (Exception ex) {
ex.printStackTrace();
}
// Test
System.out.println("Start");
for (int i = 0; i < 5; i++) {
sound.playExplosion();
// My sound is less than 1 second.
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("End");
}
}
Output
Start
200
300
300
300
300
End
For the 1st time, playerExplosion state before start() is 200 (REALIZED).
For the 2nd, 3rd, 4th, 5th times, playerExplosion state before start() is 300 (PREFETCH).
At the moment, I have to create playerExplosion again in playExplosion() method, but it's too slow in a real device.
Try after removing
playerExplosion.setLoopCount(1);
Realizing a Player can be a resource and time consuming process havint to create playerExplosion would mean calling playerExplosion.realize(); again that is why the process takes so much time
When your player is in PREFETCHED State what you need to do is just call playerExplosion.start(); but its not paying again because there is a general limitation on the number of times its should pay
Remove
playerExplosion.setLoopCount(1);
And you would be able to pay your file several times
Thanks
:)
I am developping a BlackBerry application which communicates with the server via HTTP requests(javax.microedition.io.HttpConnection). On device, user clicks some UI items, and device sends the requests to server, when the response comes, UI changes. Communication takes place under new thread, while UI thread pushes and pops ProgressDialogScreen.
The problem is sometimes, when response comes and ProgressDialogScreen is popped, UI does not change but after couple seconds UI changes. If you have requested in between when ProgressDialogScreen is popped and when new Screen is pushed, there comes the mess. First oldest new Screen is pushed, and the newest new Screen is pushed. And this situation can be observed like server responsing wrong requests. This problems occur on simulator and device.
The other problem is, sometimes two same response returns for one request. I was able to see these two problems on simulator at the logs, but i have not able to see this issue on device since i can not see the logs.
EDIT:
String utf8Response;
HttpConnection httpConn = null;
try{
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("Content-Type", "text/html; charset=UTF8");
if(sessionIdCookie != null){
//may throw IOException, if the connection is in the connected state.
httpConn.setRequestProperty("Cookie", sessionIdCookie);
}
}catch (Exception e) {
//...
}
try{
httpConn.getResponseCode();
return httpConn;
}catch (IOException e) {
// ...
}
byte[] responseStr = new byte[(int)httpConn.getLength()];
DataInputStream strm = httpConn.openDataInputStream();
strm.readFully(responseStr);
try{
strm.close();
}catch (IOException e) {
// ....
}
utf8Response = new String(responseStr, "UTF-8");
If this code successfully run, this piece of code runs and new screen is pushed:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Vector accounts = Parser.parse(utf8Response,Parser.ACCOUNTS);
if (accounts.size() == 0){
DialogBox.inform(Account.NO_DEPOSIT);
return;
}
currentScreen = new AccountListScreen(accounts);
changeScreen(null,currentScreen);
}
});
public void changeScreen(final AbstractScreen currentScreen,final AbstractScreen nextScreen) {
if (currentScreen != null)
UiApplication.getUiApplication().popScreen(currentScreen);
if (nextScreen != null)
UiApplication.getUiApplication().pushScreen(nextScreen);
}
EDITv2:
private static void progress(final Stoppable runThis, String text,boolean cancelable) {
progress = new ProgressBar(runThis, text,cancelable);
Thread threadToRun = new Thread() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try{
UiApplication.getUiApplication().pushScreen(progress);
}catch(Exception e){
Logger.log(e);
}
}
});
try {
runThis.run();
} catch (Throwable t) {
t.printStackTrace();
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
UiApplication.getUiApplication().popScreen(progress);
} catch (Exception e) { }
}
});
}
};
threadToRun.start();
}
By the way ProgressBar is extended from net.rim.device.api.ui.container.PopupScreen and Stoppable is extended from Runnable
I preferred to pop progress bar after new Screen is prepared and pushed. This way there will be no new request between request and response.
Why not do:
private static void progress(final Stoppable runThis, String text,boolean cancelable) {
progress = new ProgressBar(runThis, text,cancelable);
UiApplication.getUiApplication().pushScreen(progress);
[...]
Seems like you are parsing on the UI Thread. Please remove Vector accounts = Parser.parse(utf8Response,Parser.ACCOUNTS); from ui thread and do it in a separate thread.
I created a audio player using following code.
try {
InputStream is = getClass().getResourceAsStream("bell.wav");
player = Manager.createPlayer(is, "audio/X-wav");
player.realize();
player.prefetch();
player.start();
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (MediaException ex) {
ex.printStackTrace();
}
This code works on the simulator without any problem. But it is not working in the phone.
MediaException is thrown. I think phone does not support for this player.
Have there any solutions for this ?
It might help to check what mime types are supported by the device by checking
Manager.getSupportedContentTypes(String protocol);
and
Manager.getSupportedProtocols(String content_type);
You can also try using an URL instead of InputStream
Manager.createPlayer(String url);