Getting cross thread exception in windows phone 8 using map controls - windows-phone-8

I am working on a map control in windows phone 8. I have declared a MapPolyLine field variable
private MapPolyline _line;
After initializing my Main Page I add this to my Map control.
_line = new MapPolyline();
_line.StrokeColor = Colors.Red;
_line.StrokeThickness = 5;
Map.MapElements.Add(_line);
On the PositionChanged event I check for this condition.
if (_line.Path.Count > 0)
and then update the Map accordingly with this line.
i.e.
var previousPoint = _line.Path.Last();
var distance = coord.GetDistanceTo(previousPoint);`
var coord = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
Map.Center = coord;
_line.Path.Add(coord);
But I get Unauthorized Access, cross thread exception.
So I tried to put all my code including the 'if' condition under this
Dispatcher.BeginInvoke(() =>
{
// Update Map
});
Now the exception is not thrown, but when I hover my mouse over _line.Path.Count, it still throws an exception, but the only difference is that it is not thrown.
Is it because I have not yet moved or changed my location?. Dont know but any help on the same please, anyone?.
Thanks In Advance.

Related

cocos2d-js: b2DebugDraw can't be initialized. element.getContext("2d") returns null

I tried to use b2DebugDraw and I couldn't initialize it, because I get a null returned from getContext function. I know that this is not a cocos2d element, but it works fine in other contexts.
I created a new empty hello world project with "cocos new -l js", and placed following code at the end of the ctor function of the HelloWorldLayer:
var b2Vec2 = Box2D.Common.Math.b2Vec2,
b2World = Box2D.Dynamics.b2World,
b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
this.world = new b2World(new b2Vec2(0, -5), true);
var debugDraw = new b2DebugDraw();
var element = document.getElementById("gameCanvas"),
context = element.getContext("2d"); // context is null so
debugDraw.SetSprite(context); // sprite is not set
debugDraw.SetDrawScale(20.0);
debugDraw.SetFillAlpha(0.5);
debugDraw.SetLineThickness(1.0); // and crashes in SetLineThickness
What is wrong?
Engine version is 3.0a2
I'm trying to pass from using box2d + ease.js to cocos2d v3.0 with box2d and it is giving me the same troubles;
I finally solved adding a more canvas to the main "gameCanvas" (i put it before it in my index.html) and calling it in my b2DebugDraw method in place of the cocos2d related one:
draw:function (ctx) {
this.world.DrawDebugData();
this._super(ctx);
},
debugDraw: function(){
var myDebugDraw = new b2DebugDraw();
myDebugDraw.SetSprite(document.getElementById("debug").getContext("2d"));
//debug instead of gameCanvas
myDebugDraw.SetDrawScale(scale);
myDebugDraw.SetFillAlpha(0.8);
myDebugDraw.SetLineThickness(1.0); // no need to change this anymore
myDebugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(myDebugDraw);
}
nothing more than this. No need either to change the SetLineThickness, the error was probably related to the null context.
Hope this helps

Invalid pointer at Nokia.Graphics.Imaging.BitmapRender.RenderAsync()

I'm working on an imaging app using the nokia imaging SDK 1.1. A task seeming fairly simple (let the user choose an image and apply some filters to it) currently blocks me, for 2 days now.
I've written hundreds of lines and reviewd all the Nokia Dev Samples (which, most of the time, are very well-strcutured, but too complex for an imaging SDK starter like me) but I always get the following exception:
{System.NullReferenceException: Invalid pointer at Nokia.Graphics.Imaging.BitmapRenderer.RenderAsync()
This is the code (I've reduced the part where the filters are passed so just an empty FilterEffect is passed on for simplicity):
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += async (result,choosen) =>
{
Stream stream = choosen.ChosenPhoto;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
WriteableBitmap bitmap = new WriteableBitmap(bitmapImage);
WriteableBitmapRenderer renderer = new WriteableBitmapRenderer(new FilterEffect(), bitmap, OutputOption.PreserveAspectRatio);
await renderer.RenderAsync();
};
task.ShowCamera = true;
task.Show();
So if I understood everything well, the app is crashing because some kind of invalid pointer is passed on, but the bitmap it valid - or at least the size of it is correct, so I guess, the data has been passed on, as well.
Anyway, here is the stacktrace
at Nokia.Graphics.Imaging.BitmapRenderer.RenderAsync()
at Nokia.Graphics.Imaging.WriteableBitmapRenderer.<<RenderAsync>b__0>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at RealtimeFilterDemo.MainPage.<<ShutterButton_Tap>b__1a>d__1c.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
You're not setting a source image for the FilterEffect, and instead passing the source stream directly into the target WriteableBitmap for some reason.
When you kick off the RenderAsync operation, the FilterEffect Source property is null, and this is what causes the exception. You should pass an image source into either the FilterEffect constructor, or set its Source property.
I recommend a StreamImageSource since you've got a System.IO.Stream with the image data.
Conceptually, this is how to think of it:
chosen photo stream -> StreamImageSource -> FilterEffect -> WriteableBitmapRenderer -> the writeable bitmap
And more concretely:
using(var streamSource = new StreamImageSource(stream))
using(var filterEffect = new FilterEffect(streamSource, filters))
using(var writeableBitmapRenderer = new WriteableBitmapRenderer(filterEffect, writeableBitmap))
{
await writeableBitmapRenderer.RenderAsync();
....
}

ScrollViewer ChangeView - AccessViolationException one out of the thousand times

I have FlipView (it's virtualized with Mode="Standard") with ScrollViewer, Image (inside ScrollViewer as DataTemplate). I set ImageOpened event handler on Image with such code:
private void Image_ImageOpened(object sender, RoutedEventArgs e)
{
var image = sender as Image;
double width = image.ActualWidth;
double height = image.ActualHeight;
var sv = image.Parent as ScrollViewer;
if (sv != null && width != 0 && height != 0)
{
var properZoom = ZoomUtilities.CalculateZoomFactor(width, height);
sv.MinZoomFactor = 0.3f;
sv.ChangeView(null, null, properZoom);
sv.MinZoomFactor = properZoom;
}
}
properZoom is always correct value. One out of the thousand times when I change item (swipe) or load page with this FlipView application crash with breakpoint on sv.ChangeView(..) and AccessViolationException exception is thrown. Does anyone know what could be the reason of such behaviour? Are there any restriction when I can call ChangeView method?
EDIT:
Forgot to mention - there is also DoubleTapped event handler on ScrollViewer which also calls ChangeView
I had the same AccessViolationException using .ChangeView(..). I noticed the exception was thrown when the ScrollViewer I wanted to manipulate had focus. For example when a user was dragging through the list or controlling the scrollbar with his mouse.
Disabling animations solved my problems. If you want to keep the animations you should look for a way to remove focus on the controls before changing the view. I guess the animated ChangeView tries to change a property that is locked because of the user input.
Hope this helps.
I had the same problem.
Solution to me: call inverse, from image object to parent got error.
Call normal path: objectscroolviewer.changeview, works no error.
Then:
var sv = image.Parent as ScrollViewer;
change to
var sv = ScrollViewerObject;
Get object to variable externally, not by internal reference of parent, and ignores sender parameter.

Handling Bitmap loading and disposing probably

I'm a newbie to monodroid and I have two killers here I wish someone can help me to resolve:
I have a monodrid app which uploads an image to a web service, the images comes from the device camera or the Pictures gallery.
First thing is I use the following code to take a picture from the device camera:
var intent = new Intent(MediaStore.ActionImageCapture);
var availableActivities = this.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
if (availableActivities != null && availableActivities.Count > 0)
{
var dir = new Java.IO.File(
Android.OS.Environment.GetExternalStoragePublicDirectory(
Android.OS.Environment.DirectoryPictures), "myapp");
if (!dir.Exists())
{
dir.Mkdirs();
}
_file = new Java.IO.File(dir, String.Format("image-{0}.jpg", Guid.NewGuid()));
StaticDataHolder.ImageUri = Android.Net.Uri.FromFile(_file);
intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_file));
StartActivityForResult(intent, RESULT_CAMERA_CAPTURE);
}
And this code to read scaled Bitmap from StaticDataHolder.ImageUri into an ImageView control so the user can confirm weather to use the selected image or not:
Bitmap largeBitmap = null;
try
{
image.SetImageBitmap(null);
if (Bitmap != null)
{
Bitmap.Recycle();
Bitmap.Dispose();
}
largeBitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, StaticDataHolder.ImageUri);
Bitmap = GetScaledImage(largeBitmap);
SetImageFromBitmap(image, Bitmap);
return true;
}
catch (Java.Lang.OutOfMemoryError)
{
return false;
}
finally
{
if (largeBitmap != null)
{
largeBitmap.Recycle();
largeBitmap.Dispose();
}
}
The second issue is when the user confirm the selected image weather its taken from the camera or picked from the gallery, I create a new Bitmap to be compressed and sent to a web service which I host using the following code:
byte[] buffer = null;
MemoryStream ms = null;
Bitmap bmp = null;
ms = new MemoryStream();
bmp = MediaStore.Images.Media.GetBitmap(ContentResolver, StaticDataHolder.ImageUri);
bmp.Compress(Bitmap.CompressFormat.Jpeg, 60, ms);
buffer = ms.GetBuffer();
ms.Dispose();
bmp.Recycle();
bmp.Dispose();
and then I pass the buffer to the web service method.
This code will work perfectly the first time I start the app, But when I try to load a second image I get OutOfMemoryError exception and the image is not loaded.
How i can load a Bitmap and dispose it probably so I can avoid this exception?.
Please note that every step here is managed via separate activities:
1.Take or choose a photo activity.
2.Confirm the selected photo activity.
3.Load the selected photo and send it to the web service activity.
As far as I know the activity is disposed when finished so by default all resources used in it will also be disposed but in my case its appears to be not!.
I have searched it for 3 days with no luck, any help would be much appreciated.
Bitmaps in general are a pain on Android since they live in the native heap and are not directly garbage collected, well in Android < 2.3.x at least. Have you tried using BitmapFactory?
For example:
var opts = new BitmapFactory.Options() { InPurgeable = true, InInputShareable = true };
var bitmap = BitmapFactory.DecodeFile (pathToBitmap, opts);
Will cause the result bitmap to be purgeable from memory when needed (http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html)

AS3 - nulling elements within a Vector structure

I'm using a Vector structure in ActionScript 3 to store references to a custom class. My Vector is fixed length for performance reasons, and also because it needs to map 1:1 to another data structure.
I'm trying to figure out how I "remove" an element from this fixed list. I don't want the length of the Vector to change, I just want the value of that element to be "null". Or more specifically, when I test for the truth of that element (eg: if (myVector[index]) { // do something... }), I want that test to fail for that element, since it's "empty".
So naturally, I've tried:
myVector[index] = null;
but that throws a TypeError, as does
myVector[index] = Vector.<MyClass>([]);
So what's the process for "emptying" an element of a Vector?
There must be something wrong with your index variable because
myVector[0] = null;
does not throw a TypeError when I try that. Is index an int or uint?
if you're receiving:
TypeError: Error #1009: Cannot access
a property or method of a null object
reference
than you probably haven't added your class to the object you are trying to manage (IE: you haven't added your Display objects to the stage that you are trying to nullify)
posting more code could help, but something like the following should work for you:
var spriteA:Sprite = new Sprite();
var spriteB:Sprite = new Sprite();
var spriteC:Sprite = new Sprite();
var spritesVector:Vector.<Sprite> = new <Sprite>[spriteA, spriteB, spriteC];
spritesVector.fixed = true;
trace(spritesVector); //[object Sprite],[object Sprite],[object Sprite]
spritesVector[1] = null;
trace(spritesVector); //[object Sprite],null,[object Sprite]