Fail to connect to camera service at sometimes - android-fragments

Am calling my camera function as separate fragment during first 2 times of calling the class camera is opening but if am calling the class third time app is crashing.
private int findFrontFacingCamera() {
int cameraId = 0;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(getActivity().getApplicationContext(), "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
logcat
01-19 10:56:15.164 11477-11477/com.example.siva.prep E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.siva.prep, PID: 11477
java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.native_setup(Native Method)
at android.hardware.Camera.<init>(Camera.java:393)
at android.hardware.Camera.open(Camera.java:347)
at com.example.siva.prep.Selfie.onResume(Selfie.java:146)
It's showing error on the following line in "onResume()" method:
mCamera = Camera.open(findFrontFacingCamera());
Here is the full my code am using:
public class Selfie extends Fragment implements OnClickListener {
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private Button capture, switchCamera;
private Context myContext;
private LinearLayout cameraPreview;
private boolean cameraFront = false;
Bitmap bmp;
ImageView iv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_selfie, container, false);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
iv=(ImageView) view.findViewById(R.id.image);
myContext = getActivity().getApplicationContext();
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
cameraPreview = (LinearLayout) view.findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
ImageView capture = (ImageView) view.findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
ImageView switchCamera = (ImageView) view.findViewById(R.id.button_ChangeCamera);
switchCamera.setOnClickListener(switchCameraListener);
ImageView button1 = (ImageView) view.findViewById(R.id.back);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FreeFragment fragment2 = new FreeFragment();
FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.commit();
}
});
getSupportActionBar().hide();
return view;
}
private ActionBar getSupportActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
#Override
public void onClick(View v) {
}
private int findFrontFacingCamera() {
int cameraId = 0;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(getActivity().getApplicationContext(), "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
private void finish() {
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber >= 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
// if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId <= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else
{
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
public void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
iv.setImageURI(Uri.fromFile(pictureFile));
//Intent intent = new Intent(AndroidCameraExample.this,Fina.class);
String stringUri;
stringUri = pictureFile.toString();
//intent.putExtra("imagePath", stringUri);
//startActivity(intent);
FreeFragment ldf = new FreeFragment ();
Bundle args = new Bundle();
args.putString("Image", stringUri);
ldf.setArguments(args);
Log.d("Passing image", String.valueOf(args));
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
}
};
return picture;
}
//make picture and save to a folder
public static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
};
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}

Irrespective of the reason, not obtaining Camera handle is a case that needs to be handled with proper error handling. In the current case in your Pause handler, is the Camera instance being released ? Check for proper usage at http://developer.android.com/training/basics/activity-lifecycle/pausing.html

Related

How to save current location?

I have a question. I am working on mobile app where my user can store experience from trip by loggin current location.
I am connected to SQLite fo now and I am just exploring the Geolocator nuget from James Monemagno. SO far I can get the pin on map with current location, but I am unsure how to store the location in databse. I guess it wont be"position" and it must be Latitude and Longitude but then how will i get again the picture with the pin displayed under my post? Do you guys have some experience?
Public clas NoteViewMode : BaseViewModel
{
/////
private string _location;
public string Location
{
get { return _location; }
set
{
_location = value;
OnPropertyChanged();
}
}
public double _latitude;
public double Latitude
{
get { return _latitude; }
set
{
_latitude = value;
OnPropertyChanged();
}
}
private double _longitude;
public double Longitude
{
get { return _longitude; }
set
{
_longitude = value;
OnPropertyChanged();
}
}
}
public Map()
{
InitializeComponent();
GetPremissions();
BindingContext = ViewModel = new AdLogEntryViewModel();
}
private async void GetPremissions()
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
{
await DisplayAlert("We need location", "", "Ok");
}
var result = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (result.ContainsKey(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
status = result[Plugin.Permissions.Abstractions.Permission.LocationWhenInUse];
}
if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
locationsMap.IsShowingUser = true;
hasLocationPermission = true;
GetLocation();
}
else
{
await DisplayAlert("Location denied", "", "");
}
}
catch (Exception ex)
{
await DisplayAlert("erroe", ex.Message, "ok");
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
locator.PositionChanged += Locator_PositionChanged;
await locator.StartListeningAsync(TimeSpan.Zero, 100);
}
GetLocation();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= Locator_PositionChanged;
}
void Locator_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
MoveMap(e.Position);
}
private async void GetLocation()
{
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
MoveMap(position);
}
}
private async void MoveMap(Position position)
{
var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var span = new Xamarin.Forms.Maps.MapSpan(center, 1, 1);
locationsMap.MoveToRegion(span);
}
you can programmatically add a Pin to a Map
Pin pin = new Pin
{
Label = "Santa Cruz",
Address = "The city with a boardwalk",
Type = PinType.Place,
Position = new Position(36.9628066, -122.0194722)
};
map.Pins.Add(pin);

How do you print TextArea to a USB Thermal Printer 58mm?(JAVAFX)

So I'm trying to make a billing system in which I want to print a receipt.I was able to do it with some code that I found online,but the font size is too big to print in the 58mm wide paper.I'm not able to adjust the font size.Any kind of help with this issue will be highly appreciated.Thank You.
Here is The Code :
public class PrinterService implements Printable {
public List<String> getPrinters(){
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printServices[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
List<String> printerList = new ArrayList<String>();
for(PrintService printerService: printServices){
printerList.add( printerService.getName());
}
return printerList;
}
#Override
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/*
* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Now we perform our rendering */
g.setFont(new Font("Roman", 0, 8));
g.drawString("Hello world !", 0, 10);
return PAGE_EXISTS;
}
public void printString(String printerName, String text) {
// find the printService of name printerName
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printService[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
PrintService service = findPrintService(printerName, printService);
DocPrintJob job = service.createPrintJob();
try {
byte[] bytes;
// important for umlaut chars
bytes = text.getBytes("CP437");
Doc doc = new SimpleDoc(bytes, flavor, null);
job.print(doc, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printBytes(String printerName, byte[] bytes) {
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printService[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
PrintService service = findPrintService(printerName, printService);
DocPrintJob job = service.createPrintJob();
try {
Doc doc = new SimpleDoc(bytes, flavor, null);
job.print(doc, null);
} catch (Exception e) {
e.printStackTrace();
}
}
private PrintService findPrintService(String printerName,
PrintService[] services) {
for (PrintService service : services) {
if (service.getName().equalsIgnoreCase(printerName)) {
return service;
}
}
return null;
}
}
#FXML
public void printit(ActionEvent actionEvent)
{
PrinterService printerService = new PrinterService();
System.out.println(printerService.getPrinters());
//print some stuff
printerService.printString("POS-58-Series", area.getText());
}

refresh adapter with recyclerview using D-pad holding focus

I am stuck on a complex situation, when I am refreshing my adapter of recyclerview by notifyDataSetChanged, while it having focus on particular cell (with D-PAD), is being loss. After refresh focus is not showing
private void refreshedData() {
flag1 = true;
// new MyAsycTas().execute();
focusedElement();
// select();
runnable = new Runnable() {
#Override
public void run() {
Log.e(TAG, "Data refreshed starrt.......");
// isRefreshedData = true;
fetchXmlFromUrl = new FetchDataFromUrl(Demo2Activity.this, 0, Demo2Activity.this);
handler.removeCallbacks(runnable);
select();
handler.postDelayed(runnable, 9000);
}
};
// handler.postDelayed(runnable,
// Integer.valueOf(MyStaticClass.refreshTime) * 60000);
handler.postDelayed(runnable, 9000);
}
...
public void select() {
if (verticalListView != null) {
View view = verticalListView.getChildAt(vertical_position);
if (view != null) {
view = verticalListView.getChildAt(vertical_position);
recyclerView = (RecyclerView) view.findViewById(R.id.horizontal_recyclerview);
if (recyclerView != null) {
verticalListView.scrollToPosition(vertical_position);
((View) recyclerView.getChildAt(horizontal_position)).findViewById(R.id.cat_button_thumabnail)
.requestFocus();
} else {
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.home_fragment_menu_container);
linearLayout.getChildAt(horizontal_position).requestFocus();
}
}
}
// refreshedData();
}
..
public void focusedElement() {
if (verticalListView != null) {
View view = verticalListView.getLayoutManager().getFocusedChild();
if (view != null) {
recyclerView = (RecyclerView) view.findViewById(R.id.horizontal_recyclerview);
if (recyclerView != null) {
vertical_position = (Integer) recyclerView.getTag();
horizontal_position = recyclerView.getChildAdapterPosition(recyclerView.getFocusedChild());
} else {
LinearLayout ll = (LinearLayout) view.findViewById(R.id.home_fragment_menu_container);
horizontal_position = ll.indexOfChild(ll.getFocusedChild());
}
}
}
}

Unable to run second WebClient request after timed out and aborting request

I have a desktop app which is downloading 1 or more small files (jpg with less than 400KB in size and no more than 20 at a time) simultaneously using a CustomWebClient object and calling OpenReadAsync(). The download process is working just fine if there is no problem in the process. I want to limit the response to a certain time (15 sec) so I have introduced a timeOut handling which is Aborting the request. Even the timeout is working and after that my “OpenReadCompletedEventHandler” method is receiving System.Net.WebException: The request was aborted: The request was canceled (which is the right behaviour).
Now, my problem is that I want to allow the user to try re-loading the picture(s). So the next webClient request(s) are failing with the same WebException. Below is my code.
Here is my Custom WebClient class (used in order to have more than 2 async connections at a time):
internal class ExtendedWebClient : WebClient
{
private Timer _timer;
public int ConnectionLimit { get; set; }
public int ConnectionTimeout { get; set; }
public ExtendedWebClient()
{
this.ConnectionLimit = 2;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address) as HttpWebRequest;
if (request != null){_timer = new Timer(TimeoutRequest, request, ConnectionTimeout, Timeout.Infinite);
request.ServicePoint.ConnectionLimit = this.ConnectionLimit;
request.ServicePoint.MaxIdleTime = 5000;
request.ServicePoint.ConnectionLeaseTimeout = 5000;
}
return request;
}
private void TimeoutRequest(object state)
{
_timer.Dispose();
_timer = null;
((WebRequest)state).Abort();
}
protected override void Dispose(bool disposing)
{
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
base.Dispose(disposing);
}
}
Here is the code to download the files using my custom WebClient class:
internal struct PageWaitHandleState
{
public int WaitHandleIndexInPage;
public bool ImageIsLoaded;
public string ErrMessage;
}
public Image[] downloadedImages;
private PageWaitHandleState[] waitHandlesInPage;
private OpenReadCompletedEventHandler[] downloadComplete;
private EventWaitHandle[] pagesEWH = null;
private EventWaitHandle[] downloadImageEvent;
private int availableImages = 1; // Set here to simplify, but as I stated in my description, it may be more than 1.
int downloadTimeOut = 15000;
int maxSimultaneousDownloads = 20;
private void DownloadImages(int pageIndex = 0, string[] imageUrl)
{
if (pagesEWH[pageIndex] != null)
{
ReloadImages(pageIndex, imageUrl); // Executed in the second request
return;
else
{
pagesEWH[pageIndex] = new EventWaitHandle[availableImages];
downloadedImages = new Image[availableImages];
downloadComplete = new OpenReadCompletedEventHandler[availableImages];
downloadImageEvent = new EventWaitHandle[availableImages];
waitHandlesInPage = new PageWaitHandleState[availableImages];
// Set the downloadComplete deletages
for (int i = 0; i < availableImages; i++)
{
downloadComplete[i] = ProcessImage;
}
}
for (int imgCounter = 0; i < availableImages; i++)
{
waitHandlesInPage[imgCounter] = new PageWaitHandleState() { ImageIsLoaded = false, WaitHandleIndexInPage = imgCounter, ErrMessage = null };
downloadImageEvent[imgCounter] = GrabImageAsync(imageUrl[imgCounter], downloadComplete[imgCounter], imgCounter, downloadTimeOut, maxSimultaneousDownloads);
pagesEWH[imgCounter] = downloadImageEvent[imgCounter];
}
offenderIndex++;
}
}
private static EventWaitHandle GrabImageAsync(string url, OpenReadCompletedEventHandler openReadCompletedEventHandler, int imgCounter, int downloadTimeOut, int maxSimultaneousDownloads)
{
var myClient = new ExtendedWebClient();
myClient.ConnectionLimit = maxSimultaneousDownloads;
myClient.ConnectionTimeout = downloadTimeOut;
myClient.OpenReadCompleted += openReadCompletedEventHandler;
var iewh = new ImageEventWaitHandle() { ewh = new EventWaitHandle(false, EventResetMode.ManualReset), ImageIndex = imgCounter };
myClient.OpenReadAsync(new Uri(url), iewh);
return iewh.ewh;
}
internal void ProcessImage(object sender, OpenReadCompletedEventArgs e)
{
ImageEventWaitHandle iewh = (ImageEventWaitHandle)e.UserState;
bool disposeObject = false;
try
{
if (e.Cancelled)
{
this.waitHandlesInPage[iewh.ImageIndex].ImageIsLoaded = false;
this.waitHandlesInPage[iewh.ImageIndex].ErrMessage = "WebClient request was cancelled";
}
else if (e.Error != null)
{
this.waitHandlesInPage[iewh.ImageIndex].ImageIsLoaded = false;
this.waitHandlesInPage[iewh.ImageIndex].ErrMessage = e.Error.Message;
iewh.ewh.Set();
this.downloadImageEvent[iewh.ImageIndex].Close();
}
else
{
using (Stream inputStream = e.Result)
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
int totalReadBytes = 0;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length); // Exception fired here with the second request
ms.Write(buffer, 0, bytesRead);
totalReadBytes += bytesRead;
} while (inputStream.CanRead && bytesRead > 0);
this.downloadedImages[iewh.ImageIndex] = Image.FromStream(ms);
this.waitHandlesInPage[iewh.ImageIndex].ImageIsLoaded = true;
this.waitHandlesInPage[iewh.ImageIndex].ErrMessage = null;
}
disposeObject = true;
}
}
catch (Exception exc)
{
this.downloadedImages[iewh.ImageIndex] = null;
}
finally
{
// Signal the wait handle
if (disposeObject)
{
iewh.ewh.Set();
((WebClient)sender).Dispose();
}
}
}
private void ReloadImages(int pageIndex, string[] imageUrl)
{
for (int imgCounter = 0; imgCounter < availableImages; imgCounter++)
{
this.downloadComplete[imgCounter] = this.ProcessImage;
this.waitHandlesInPage[imgCounter] = new PageWaitHandleState() { ImageIsLoaded = false, WaitHandleIndexInPage = imgCounter, ErrMessage = null };
this.downloadImageEvent[imgCounter] = GrabImageAsync(ImageUrl[imgCounter],this.downloadComplete[imgCounter], imgCounter, downloadTimeOut, maxSimultaneousDownloads);
this.pagesEWH[imgCounter] = this.downloadImageEvent[imgCounter];
}
}
Finally, when I want to access the images I check if they are ready by using:
private bool ImagesInPageReady(int pageIndex, int recordsInCurrentPage)
{
if (_PagesEWH[pageIndex] != null)
{
int completedDownloadsCount = 0;
bool waitHandleSet;
// Wait for the default images first (imgCounter = 0). When moving page or asking for more pictures, then wait for the others.
for (int ewhIndexInPage = 0; ewhIndexInPage < recordsInCurrentPage; ewhIndexInPage++)
{
if (this.pagesEWH[ewhIndexInPage].WaitOne(this.downloadTimeOut))
{
if (this.WaitHandlesInPage[ewhIndexInPage].ImageIsLoaded)
{
completedDownloadsCount++;
}
}
else
{
this.pagesEWH[ewhIndexInPage].Set();
}
}
return (completedDownloadsCount > 0);
}
return false;
}
#usr, thanks for pointing me in the right direction. HttpClient was the solution. So I basically encapsulated my HttpClient object in a new class, together with the ProcessImage() method and exposing and event fired by the same method.

BlackBerry - Exception when sending SMS

The code below should send a text message to a mobile number. It currently fails to work properly.
When the program attempts a message, the following error is reported:
Blocking operation not permitted on event dispatch thread
I created a separate thread to execute the SMS code, but I am still observing the same exception.
What am I doing wrong?
class DummyFirst extends MainScreen {
private Bitmap background;
private VerticalFieldManager _container;
private VerticalFieldManager mainVerticalManager;
private HorizontalFieldManager horizontalFldManager;
private BackGroundThread _thread;
CustomControl buttonControl1;
public DummyFirst() {
super();
LabelField appTitle = new LabelField("Dummy App");
setTitle(appTitle);
background = Bitmap.getBitmapResource("HomeBack.png");
_container = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL
| Manager.NO_VERTICAL_SCROLLBAR) {
protected void paint(Graphics g) {
// Instead of these next two lines, draw your bitmap
int y = DummyFirst.this.getMainManager()
.getVerticalScroll();
g.clear();
g.drawBitmap(0, 0, background.getWidth(), background
.getHeight(), background, 0, 0);
super.paint(g);
}
protected void sublayout(int maxWidth, int maxHeight) {
int width = background.getWidth();
int height = background.getHeight();
super.sublayout(width, height);
setExtent(width, height);
}
};
mainVerticalManager = new VerticalFieldManager(
Manager.NO_VERTICAL_SCROLL |
Manager.NO_VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
int width = background.getWidth();
int height = background.getHeight();
super.sublayout(width, height);
setExtent(width, height);
}
};
HorizontalFieldManager horizontalFldManager =
new HorizontalFieldManager(Manager.USE_ALL_WIDTH);
buttonControl1 = new CustomControl("Send", ButtonField.CONSUME_CLICK,
83, 15);
horizontalFldManager.add(buttonControl1);
this.setStatus(horizontalFldManager);
FieldListener listner = new FieldListener();
buttonControl1.setChangeListener(listner);
_container.add(mainVerticalManager);
this.add(_container);
}
class FieldListener implements FieldChangeListener {
public void fieldChanged(Field f, int context) {
if (f == buttonControl1) {
_thread = new BackGroundThread();
_thread.start();
}
}
}
private class BackGroundThread extends Thread {
public BackGroundThread() {
/*** initialize parameters in constructor *****/
}
public void run() {
// UiApplication.getUiApplication().invokeLater(new Runnable()
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
MessageConnection msgConn =
(MessageConnection) Connector
.open("sms://:0");
Message msg = msgConn
.newMessage(
MessageConnection.TEXT_MESSAGE);
TextMessage txtMsg = (TextMessage) msg;
String msgAdr = "sms://+919861348735";
txtMsg.setAddress(msgAdr);
txtMsg.setPayloadText("Test Message");
// here exception is thrown
msgConn.send(txtMsg);
System.out.println("Sending" +
" SMS success !!!");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} // run
});
}
}
public boolean onClose() {
System.out.println("close event called, request to be" +
" in the backgroud....");
UiApplication.getUiApplication().requestBackground();
return true;
}
}
Dec 14, 2009 Stella answered their own question:
I resolved this issue by creating a separate thread and then not using Port etc.
Here it is:
SMSThread smsthread = new SMSThread("Some message",mobNumber);
smsthread.start();
class SMSThread extends Thread {
Thread myThread;
MessageConnection msgConn;
String message;
String mobilenumber;
public SMSThread( String textMsg, String mobileNumber ) {
message = textMsg;
mobilenumber = mobileNumber;
}
public void run() {
try {
msgConn = (MessageConnection) Connector.open("sms://+"+ mobilenumber);
TextMessage text = (TextMessage) msgConn.newMessage(MessageConnection.TEXT_MESSAGE);
text.setPayloadText(message);
msgConn.send(text);
msgConn.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}

Resources