Set an OnClickListener for an SVG element - blackberry

Say I have an SVG element, as follows. How do I add an onClickListener?
solved, see below.

I'm going to guess you're meaning a FieldChangeListener rather than an OnClickListener (wrong platform ;). SVGImage isn't part of the RIM-developed objects, so unfortunately you won't be able to. Anything that is going to be able to have a FieldChangeListner has to be a subclass of the net.rim.device.api.ui.Field class.

Just in case someone's interested in how it's done...
try {
InputStream inputStream = getClass().getResourceAsStream("/svg/sphere1.svg");
_image = (SVGImage)SVGImage.createImage(inputStream, null);
_animator = SVGAnimator.createAnimator(_image, "net.rim.device.api.ui.Field");
_document = _image.getDocument();
_svg123 = (SVGElement)_document.getElementById("123");
}
catch (IOException e) { e.printStackTrace(); }
Field _svgField = (Field)_animator.getTargetComponent();
_svgField.setBackground(blackBackground);
add(_svgField);
_svg123.addEventListener("click", this, false);
_svg123.addEventListener("DOMFocusIn", this, false);
_svg123.addEventListener("DOMFocusOut", this, false);
}
public void handleEvent(Event evt) {
if( _svg123 == evt.getCurrentTarget() && evt.getType() == "click" ){ Dialog.alert("You clicked 123"); }
if( _svg123 == evt.getCurrentTarget() && evt.getType() == "DOMFocusIn" ) { ((SVGElement) _document.getElementById("outStroke123")).setTrait("fill", "#FF0000"); }
if( _svg123 == evt.getCurrentTarget() && evt.getType() == "DOMFocusOut" ) { ((SVGElement) _document.getElementById("outStroke123")).setTrait("fill", "#2F4F75"); }
}

Related

manipulate JavaCamera2View to set Parameters for Camera Device - OpenCV in Android

Software: Android 4.1.1, OpenCV 4.5.0
To briefly summarize my project. i want to continuously monitor the 'frequency' of a flickering led light source using the rolling shutter effect based on a cmos camera of an android smartphone. in the video/'image stream' a light dark stripe pattern should be visible, which i want to analize with opencv.
if you are interested in the method, you can find more information here:
RollingLight: Light-to-Camera Communications
now the actual problem: i need to set the camera parameters to fixed values before i start analizing with opencv. the exposure time should be as short as possible, the iso (sensitivity) should get a medium value and the focus should be set as close as possible.
for this i made the following changes (marked as comments //) in the methods initializeCamera() and createCameraPreviewSession() from the opencv's JavaCamera2View.java file.
initializeCamera() - from JavaCamera2View.java
public int minExposure = 0;
public int maxExposure = 0;
public long valueExposure = minExposure;
public float valueFocus = 0;
public int minIso = 0;
public int maxIso = 0;
public int valueIso = minIso;
public long valueFrameDuration = 0;
protected boolean initializeCamera() {
Log.i(LOGTAG, "initializeCamera");
CameraManager manager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
try {
String camList[] = manager.getCameraIdList();
if (camList.length == 0) {
Log.e(LOGTAG, "Error: camera isn't detected.");
return false;
}
if (mCameraIndex == CameraBridgeViewBase.CAMERA_ID_ANY) {
mCameraID = camList[0];
} else {
for (String cameraID : camList) {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID);
if ((mCameraIndex == CameraBridgeViewBase.CAMERA_ID_BACK &&
characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) ||
(mCameraIndex == CameraBridgeViewBase.CAMERA_ID_FRONT &&
characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT)
) {
mCameraID = cameraID;
break;
}
}
}
if (mCameraID != null) {
Log.i(LOGTAG, "Opening camera: " + mCameraID);
//I added this code to get the parameters---------------------------------------------------------------------------
CameraManager mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraID);
valueFocus = mCameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
Range<Integer> rangeExposure = mCameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
minExposure = rangeExposure.getLower();
maxExposure = rangeExposure.getUpper();
Range<Integer> rangeIso = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
minIso = rangeIso.getLower();
maxIso = rangeIso.getUpper();
valueFrameDuration = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_MAX_FRAME_DURATION);
} catch (CameraAccessException e) {
Log.e(LOGTAG, "calcPreviewSize - Camera Access Exception", e);
} catch (IllegalArgumentException e) {
Log.e(LOGTAG, "calcPreviewSize - Illegal Argument Exception", e);
} catch (SecurityException e) {
Log.e(LOGTAG, "calcPreviewSize - Security Exception", e);
}
//end of code-------------------------------------------------------------------------------------------------------
manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler);
} else { // make JavaCamera2View behaves in the same way as JavaCameraView
Log.i(LOGTAG, "Trying to open camera with the value (" + mCameraIndex + ")");
if (mCameraIndex < camList.length) {
mCameraID = camList[mCameraIndex];
manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler);
} else {
// CAMERA_DISCONNECTED is used when the camera id is no longer valid
throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED);
}
}
return true;
} catch (CameraAccessException e) {
Log.e(LOGTAG, "OpenCamera - Camera Access Exception", e);
} catch (IllegalArgumentException e) {
Log.e(LOGTAG, "OpenCamera - Illegal Argument Exception", e);
} catch (SecurityException e) {
Log.e(LOGTAG, "OpenCamera - Security Exception", e);
}
return false;
}
createCameraPreviewSession() - from JavaCamera2View.java
private void createCameraPreviewSession() {
final int w = mPreviewSize.getWidth(), h = mPreviewSize.getHeight();
Log.i(LOGTAG, "createCameraPreviewSession(" + w + "x" + h + ")");
if (w < 0 || h < 0)
return;
try {
if (null == mCameraDevice) {
Log.e(LOGTAG, "createCameraPreviewSession: camera isn't opened");
return;
}
if (null != mCaptureSession) {
Log.e(LOGTAG, "createCameraPreviewSession: mCaptureSession is already started");
return;
}
mImageReader = ImageReader.newInstance(w, h, mPreviewFormat, 2);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image == null)
return;
// sanity checks - 3 planes
Image.Plane[] planes = image.getPlanes();
assert (planes.length == 3);
assert (image.getFormat() == mPreviewFormat);
JavaCamera2Frame tempFrame = new JavaCamera2Frame(image);
deliverAndDrawFrame(tempFrame);
tempFrame.release();
image.close();
}
}, mBackgroundHandler);
Surface surface = mImageReader.getSurface();
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_MANUAL);
mPreviewRequestBuilder.addTarget(surface);
mCameraDevice.createCaptureSession(Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession cameraCaptureSession) {
Log.i(LOGTAG, "createCaptureSession::onConfigured");
if (null == mCameraDevice) {
return; // camera is already closed
}
mCaptureSession = cameraCaptureSession;
try {
//I added this code to set the parameters---------------------------------------------------------------------------
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);
mPreviewRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, valueFocus);
mPreviewRequestBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, valueExposure);
mPreviewRequestBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, valueIso);
mPreviewRequestBuilder.set(CaptureRequest.SENSOR_FRAME_DURATION, valueFrameDuration);
//end of code-------------------------------------------------------------------------------------------------------
mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
Log.i(LOGTAG, "CameraPreviewSession has been started");
} catch (Exception e) {
Log.e(LOGTAG, "createCaptureSession failed", e);
}
}
#Override
public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
Log.e(LOGTAG, "createCameraPreviewSession failed");
}
},
null
);
} catch (CameraAccessException e) {
Log.e(LOGTAG, "createCameraPreviewSession", e);
}
}
unfortunately, the above editing does not work. console shows:
java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference
maybe not the only problem i guess.
i have already read numerous posts about the interaction between opencv and androids camera 2 (camerax) api. regarding my question, however, this post unfortunately sums it up: "OpenCV will not work with android.camera2" but, the post is a few years old and i hope there is a workaround for the problem by now.
1.) do you know how i can set fix camera parameters and then do an analysis in opencv? could you explain the steps to me?
2.) are there any existing available projects as reference?
3.) i need the highest possible frame rate of the camera. otherwise i would have thought that i could work with getbitmap(); and forward the image to opencv. but the frame rate is really bad and besides i'm not sure here either how to set the camera parameters fix before taking the photo. or do you know any alternatives?
thanks in advance for your support. if you need more info, i will be happy to share it with you.
--
2021 arpil: the questions are still unanswered. if someone doesn't answer them in detail but has links that could help me, i would really appreciate it.

How to add text input field in cocos2d.Android cocos sharp?

I am trying to get CCTextFieldTTF to work in cocos sharp with Xamarin for an android application. But can't get hold of this for the life of me. Could not find any documentation on cocos sharp API either. Does anyone know how to use this class to render a text area in an android application? The reason I am asking is in a xamarin forum I saw someone saying that this does not work in the API yet. Any help would be highly appreciated. Thanks in advance.
I have this working in android
Here is the sample code:
Create a node to track the textfield
CCTextField trackNode;
protected CCTextField TrackNode
{
get { return trackNode; }
set
{
if (value == null)
{
if (trackNode != null)
{
DetachListeners();
trackNode = value;
return;
}
}
if (trackNode != value)
{
DetachListeners();
}
trackNode = value;
AttachListeners();
}
}
//create the actual input textfield
var textField = new CCTextField(string.Empty, "Somefont", 25, CCLabelFormat.SystemFont);
textField.IsColorModifiedByOpacity = false;
textField.Color = new CCColor3B(Theme.TextWhite);
textField.BeginEditing += OnBeginEditing;
textField.EndEditing += OnEndEditing;
textField.Position = new CCPoint (0, 0);
textField.Dimensions = new CCSize(VisibleBoundsWorldspace.Size.Width - (160 * sx), vPadding);
textField.PlaceHolderTextColor = Theme.TextYellow;
textField.PlaceHolderText = Constants.TextHighScoreEnterNamePlaceholder;
textField.AutoEdit = true;
textField.HorizontalAlignment = CCTextAlignment.Center;
textField.VerticalAlignment = CCVerticalTextAlignment.Center;
TrackNode = textField;
TrackNode.Position = pos;
AddChild(textField);
// Register Touch Event
var touchListener = new CCEventListenerTouchOneByOne();
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchEnded = OnTouchEnded;
AddEventListener(touchListener);
// The events
bool OnTouchBegan(CCTouch pTouch, CCEvent touchEvent)
{
beginPosition = pTouch.Location;
return true;
}
void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent)
{
if (trackNode == null)
{
return;
}
var endPos = pTouch.Location;
if (trackNode.BoundingBox.ContainsPoint(beginPosition) && trackNode.BoundingBox.ContainsPoint(endPos))
{
OnClickTrackNode(true);
}
else
{
OnClickTrackNode(false);
}
}
public void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
if (!isKeyboardShown)
{
isKeyboardShown = true;
TrackNode.Edit();
}
}
else
{
if (TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
private void OnEndEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollDown);
Console.WriteLine("OnEndEditing text {0}", text);
}
private void OnBeginEditing(object sender, ref string text, ref bool canceled)
{
//((CCNode)sender).RunAction(scrollUp);
Console.WriteLine("OnBeginEditing text {0}", text);
}
void AttachListeners()
{
// Attach our listeners.
var imeImplementation = trackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide += OnKeyboardDidHide;
imeImplementation.KeyboardDidShow += OnKeyboardDidShow;
imeImplementation.KeyboardWillHide += OnKeyboardWillHide;
imeImplementation.KeyboardWillShow += OnKeyboardWillShow;
imeImplementation.InsertText += InsertText;
}
void DetachListeners()
{
if (TrackNode != null)
{
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide -= OnKeyboardDidHide;
imeImplementation.KeyboardDidShow -= OnKeyboardDidShow;
imeImplementation.KeyboardWillHide -= OnKeyboardWillHide;
imeImplementation.KeyboardWillShow -= OnKeyboardWillShow;
imeImplementation.InsertText -= InsertText;
}
}
This is all taken from the link below but needed a bit of additional work to get it working on each platform.
https://github.com/mono/cocos-sharp-samples/tree/master/TextField

how to avoid uitableview cell refresh flicker when reload cell

I used the monotouch.dialog to develop one PrivateMsg talk screen. But when I reload the cell , the cell flicker, how to avoid it ?
add new pm msg accross 2 step: 1. append a element cell: State.Insert(msg is sending)=> 2. reload the element cell status: State.Updated(msg send sucessced)
Pls find the attachment:screen recording file and the source code:
void HandleOnPMChanged(object sender, PMChangedEventArgs e)
{
if (e.PMSID != this.mPMSession.PMSID)
return;
this.BeginInvokeOnMainThread(() =>
{
if (e. State == State.Insert) //step1
{
element = this.GetNewPMElement(itemData);
pmSection.Add(element);
this.ScrollToBottomRow();
} else if (e.State == State.Update && e.PM != null) //step2
{
var element = FindElement(e.PM.Guid.GetHashCode());
if (element != null)
{
var indexPaths = new NSIndexPath [] { element.IndexPath };
this.TableView.ReloadRows(indexPaths, UITableViewRowAnimation.None); //this line will flicker
//remark: this.ScrollToBottomRow();
}
}
else if (e. State == State.Insert)
{
element = this.GetNewPMElement(itemData);
pmSection.Add(element);
this.ScrollToBottomRow(); //step1
}
});
}
public void ScrollToBottomRow()
{
try
{
if (pmSection.Count < 1)
return;
NSIndexPath ndxPath = pmSection[pmSection.Count - 1].IndexPath;
if (ndxPath != null)
this.TableView.ScrollToRow(ndxPath, UITableViewScrollPosition.Bottom, false); //Bottom, false);
}
catch (Exception ex)
{
Util.ReportMsg("PMDVC ScrollToBottomRow Exception:", ex.Message);
}
}
issue has been fixed.
EstimatedHeight return bigger than actual value.

LocationUpdate method getting called too frequently on Blackberry

I have a 3 GSM phones and a 3 verizon (CDMA) phones. I have a BB application in which the location listener is set to a 5 minute interval.
For 2 of the verizon phones the application's location update method gets called frequently. For the rest, the location listener gets called at a regular 5 minute interval.
What could be causing this difference in behavior?
public synchronized void locationUpdated(LocationProvider locationProvider, Location location) {
if (enabled) {
if (blackberryProvider != null) {
try {
constructCriteria(GPSInfo.GPS_MODE_CELLSITE);
gpsUpdate();
} catch (LocationException e) {
log stuff//
}
}
}
}
private void gpsUpdate() throws LocationException, InterruptedException {
try {
String gpsMode = null;
if (bbCriteria.getMode() == GPSInfo.GPS_MODE_CELLSITE) {
gpsMode = "cellsiteMode";
}
if (gpsMode == "cellsiteMode" && gpsMode.length() > 0 && bbProvider != null) {
// variable declaration
try {
bbLocation = (BlackBerryLocation) bbProvider.getLocation(10);
} catch (LocationException e) {
bbLocation = null;
}
if (bbLocation != null) {
// do stuff
// store location in the database
}
}
}
}
}
}
private void constructCriteria(final int mode) {
blackberryCriteria = null;
blackberryProvider = null;
blackberryCriteria = new BlackBerryCriteria();
blackberryCriteria.setSatelliteInfoRequired(true, false);
if (mode == GPSInfo.GPS_MODE_CELLSITE) {
setCriteraForCellSite();
}
try {
blackberryProvider = (BlackBerryLocationProvider) LocationProvider.getInstance(blackberryCriteria);
if (iLocationListner == null) {
iLocationListner = new ILocationListner();
blackberryProvider.setLocationListener(iLocationListner, locationInterval == 0 ? 300 : locationInterval, -1, -1);
} else {
blackberryProvider.setLocationListener(iLocationListner, locationInterval == 0 ? 300 : locationInterval, -1, -1);
}
} catch (LocationException lex) {
Logger.log("LocationEventSource constructor", lex);
return;
}
}
You are setting your criteria to update every 300 seconds if locationInterval == 0 or at the default rate (once per second) otherwise. Is this really what you want? Where is locationInterval initialized? How does its value change as the program runs?

ScriptBundle not including other script depending on the ordering

I'm trying to combine all scripts into one.. I have two folders, the main folder 'scripts' and the other 'scripts/other'.
When I try:
BundleTable.Bundles.Add(new ScriptBundle("~/scripts/all").Include("~/Scripts/*.js", "~/Scripts/other/*.js"));
scripts from 'scripts/other' are not included.
but when I invert the order:
BundleTable.Bundles.Add(new ScriptBundle("~/scripts/all").Include("~/Scripts/other/*.js", "~/Scripts/*.js"));
it works!!
Someone can tell me why?
Can you try calling the IncludeDirectory methods directly and seeing if you see the same issue?
ScriptBundle("~/scripts/all").IncludeDirectory("~/Scripts", "*.js").IncludeDirectory("~/Scripts/other", "*.js"));
If this works, then it's possible we have a bug here.
I don't know what is happening, but this is the code inside the System.Web.Optimization.Bundle:
// System.Web.Optimization.Bundle
public Bundle Include(params string[] virtualPaths)
{
for (int i = 0; i < virtualPaths.Length; i++)
{
string text = virtualPaths[i];
Exception ex = Bundle.ValidateVirtualPath(text, "virtualPaths");
if (ex != null)
{
throw ex;
}
if (text.Contains('*'))
{
int num = text.LastIndexOf('/');
string text2 = text.Substring(0, num);
if (text2.Contains('*'))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, OptimizationResources.InvalidPattern, new object[]
{
text
}), "virtualPaths");
}
string text3 = "";
if (num < text.Length - 1)
{
text3 = text.Substring(num + 1);
}
PatternType patternType = PatternHelper.GetPatternType(text3);
ex = PatternHelper.ValidatePattern(patternType, text3, "virtualPaths");
if (ex != null)
{
throw ex;
}
this.IncludeDirectory(text2, text3);
}
else
{
this.IncludeFile(text);
}
}
return this;
}

Resources