onActivityResult crashes when custom location for video (MediaStore.EXTRA_OUTPUT, URI) is set - output

So this is my setup for the 'intent':
Intent cameraACTION_VIDEO_CAPTURE = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
tempUri = accessLocalStorage.getThisAppsStorageUriPath();
//Crashed for tempUri = "/data/user/0/hardy.android.go/app_files/test.mp4"
//Crashed for tempUri = "/data/user/0/hardy.android.go/app_files/"
cameraACTION_VIDEO_CAPTURE.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
cameraACTION_VIDEO_CAPTURE.setFlags(cameraACTION_VIDEO_CAPTURE.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(cameraACTION_VIDEO_CAPTURE,
Integer.parseInt( DataModel.SETVIDEORECORDING.toString()));
Video intent starts as expected and crashes once I finish recording - it doesn't even make it to 'onActivityResult'. Error is:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
Don't know why there is a Bitmap floating around in there?
Anywayz, so in an attempt to try and pinpoint the issue, I comment out the following and go again:
cameraACTION_VIDEO_CAPTURE.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
and it works :( - video is stored here:
/storage/emulated/0/DCIM/Camera/VID_20181004_213440310_HDR.mp4

Ok, I have a partial answer. In terms of the application not crashing, I made progress by using FileProvider to generate the Uri.
tempUri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + ".provider",
new File(accessLocalStorage.getThisAppsStorageUriPath().getPath())
);
However, the video File saved at the path in the Uri was of size/length 0 () and I didn't have time to work through this and so, this story ends here :( - hope this is of some help for others!

Related

Starting a websocket in a function (Binance Websocket)

I have been working with binance websocket. Worked well if the start/stop command is in the main programm. Now I wanted to start and stop the socket through a GUI. So I placed the start/stop command in a function each. But it doesn't work. Just no reaction while calling the function. Any idea what's the problem?
Here the relevant parts of my code (I am quite new to python, any hints to this code are welcome):
def start_websocket(conn_key):
bm.start()
def stop_websocket(conn_key):
bm.close()
def process_message(msg):
currentValues['text']= msg['p']
# --- main ---
PUBLIC = '************************'
SECRET = '************************'
client = Client(api_key=PUBLIC, api_secret=SECRET)
bm = BinanceSocketManager(client)
conn_key = bm.start_trade_socket('BNBBTC', process_message)
# create main window and set its title
root = tk.Tk()
root.title('Websocket')
# create variable for displayed time and use it with Label
label = tk.Label(root)
label.grid(column=5, row=0)
#root.geometry('500x500')
bt_start_socket = tk.Button(root, text="Start Websocket", command=start_websocket(conn_key))
bt_start_socket.grid (column=1, row=1)
bt_stop_socket = tk.Button(root, text="Sop Websocket", command=stop_websocket(conn_key))
bt_stop_socket.grid (column=1, row=10)
I figured out how to do this.
The start and stop command should be in one function. The function is called with a parameter to start or stop.
Interestingly the conn_key has to be global. Otherwise a new Websocket is opened if the function is called again for closing.
As I told earlier: I am quite new to python. So, no guarantee that this is the best way to du it. It just worked ;-)
def start_stop_websocket(switch):
global conn_key
if switch == 'on':
bm.start()
print('started')
if switch == 'off':
bm.stop_socket(conn_key)
bm.close()
print('stoped')
I recommend not using global vars.
I know its not the answer you was asking for, but you can use unicorn-binance-websocket-api for python which allready has those methods ready for you:
https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api
start a stream: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api/unicorn_binance_websocket_api.html#unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager.BinanceWebSocketApiManager.create_stream
stop a stream: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api/unicorn_binance_websocket_api.html#unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager.BinanceWebSocketApiManager.stop_stream
The lib offers a lot of examples and is easy to learn:
https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/example_stream_management_extended.py

cocos2d-js: Error: Invalid Native Object using setPhysicsBody

I'm trying to implement chipmunk physics engine for a cocos2d-js game. I'm getting the following error when i run it.
jsb: ERROR: File Y:\Documents\cocos\PrebuiltRuntimeJs\frameworks\js-bindings\bindings\auto\jsb_cocos2dx_auto.cpp: Line: 2143, Function: js_cocos2dx_Node_setPhysicsBody
Invalid Native Object
JS: D:/PROJECTS/cocos/Sliderule/runtime/win32/../../src/app.js:32:Error: Invalid Native Object
Here is the code i'm working with
`init:function () {
this._super();
var size = cc.winSize;
this.rect1 = new cc.Sprite(res.null_png,cc.rect(0,0, 200, 25));
this.rect1.setColor(cc.color(255,50,50,1));
this.rect1.setPosition(size.width/2, size.height-12.5);
this.rect1._setAnchorX(0.5);
this.rect1._setAnchorY(0.5);
this.rectbody1 = new cp.Body(1,cp.momentForBox(1,this.rect1.getContentSize().width, this.rect1.getContentSize().height));
this.rectbody1.p = cc.p(size.width/2, size.height-12.5);
this.space.addBody(this.rectbody1);
this.rectshape1 = new cp.BoxShape(this.rectbody1, this.rect1.getContentSize().width - 14, this.rect1.getContentSize().height);
this.space.addShape(this.rectshape1);
this.rect1.setPhysicsBody(this.rectbody1);
this.addChild(this.rect1,1);
`
I get the problem when setting the body to the sprite. Thanks in Advance.
This error message usually appears because of a missing retain(). You have to explicitly set sprites to be kept by the native system (Android, iOS) otherwise it's not valid after some time. And then, if you don't need it anymore: release it.
Try:
this.rect1.retain()
after you created the sprite. And then
this.rect1.release()
when you don't need it anymore.

Issues while upgrading from Microsoft.WindowsAzure.StorageClient 1.7 to Microsoft.WindowsAzure.Storage 4.2

I had this code previously working while using the StorageClient.dll:
CloudBlobContainer container = new CloudBlobContainer(courseName.ToLower(), blobClient);
container.CreateIfNotExist();
When upgrading to the Storage.dll and using the Storage.Blob I am unable to call the CreateIfNotExists method with empty parameters. I have looked at the documentation here http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.blob.cloudblobcontainer.createifnotexists.aspx
There are now 2 constructors:
CloudBlobContainer.CreateIfNotExists (BlobContainerPublicAccessType, BlobRequestOptions, OperationContext)
CloudBlobContainer.CreateIfNotExists (BlobRequestOptions, OperationContext)
I have attempted to creat the BlobRequestOptions and OperationContext and pass them in as follows but without joy:
CloudBlobContainer container = blobClient.GetContainerReference(courseName.ToLower());
var bro = new BlobRequestOptions();
var oc = new OperationContext();
container.CreateIfNotExist(bro,oc);
Any idea of what I am doing wrong here?
You can still call it as CreateIfNotExists(), since those arguments have default values. Also please note that GetContainerReference requires a name to be passed in, not a URL.

Rx 2.1: How to subscribe and observe on Dispatcher correctly

First of all, I'm using the most recent of Rx, that is 2.1. As far as I understand, lots of things have changed when Rx turned 2, so I'm really looking forward to receive an up-to-date answer. Thanks in advance.
I'm implementing a classic task for Rx: observing text of TextBox (AutoCompleteBox from WPToolkit to be exact), in order to provide a list of suggestions to user. Suggestions are fetched from the network, and I want to use these ordinary Rx goodies, like Throttle, DistinctUntilChanged, etc.
I'm also using recently released portable HttpClient for Windows Phone 8, since it provides task-based asynchronous API, which is nice.
The problem I'm having is the cross-thread access while reading the Text value of 'AutoCompleteBox`. Here is the code:
var http = new HttpClient();
var searchFunc = Observable.FromAsync<HttpResponseMessage>(() =>
http.GetAsync(FormatUrl(SEARCH_URL, "DE", new GeoCoordinate(51, 13), searchBox.Text /* <-- causes exception */, 10, "")));
var uithread = new SynchronizationContextScheduler(SynchronizationContext.Current);
var textChange = Observable.FromEventPattern<RoutedEventArgs>(searchBox, "TextChanged")
.Throttle(TimeSpan.FromMilliseconds(800))
.DistinctUntilChanged()
.SubscribeOn(uithread)
.SelectMany(searchFunc)
.Select(async (resp) => SearchResultsParser.ParseSearchResults(await resp.Content.ReadAsStreamAsync(), new GeoCoordinate(51, 13)))
.Select(async (results) => searchBox.ItemsSource = await results)
.ObserveOn(uithread)
.Subscribe();
Exception happens when searchFunc is executed. I see from VS that it executes on a Worker Thread, despite I use SubscribeOn.
Here's the example using SynchronizationContextScheduler, but I've also tried just SubscribeOnDispatcher, with the same result. Looks like I'm missing something important with this ObserveOn stuff, or maybe regarding Observable.FromAsync. Could you kindly point me to my mistake?
SubscribeOn is almost never what you want - you might think it means "Where my Subscribe method runs", but it actually means "Where the actual wiring to the IDisposable (and disposal) runs" - ObserveOn is the equivalent for "This is where I want my actual Subscribe code to execute"
Ref: Observable.SubscribeOn and Observable.ObserveOn

How to browse mobile directory in flex?

I have captured 3 videos on my mobile which is by default stored on the phone gallery (Gallery/videos/). I have to play these 3 videos in one of my flex mobile application. How can I get the videos to the flex project? if I need to browse the mobile directory means kindly help me with some code to do so.
I too am looking for an answer to this question. Right now, based on other Stackoverflow discussions, exhaustive perusal of tutorials and Adobe documentation, and comments to both (often the more useful resource), I'm coming to the conclusion that it's not possible.
you can use CameraRoll.browseForImage() and open the iOS gallery of photos to see all entities of MediaType.IMAGE, but it will not show you MediaType.VIDEO
you can use CameraUI to launch the system camera by delegation and that returns a MediaPromise, but as far as I can tell, it does not save the video you capture anywhere, and I cannot find a way to access the captured video using the MediaPromise (at least using the Loader class)
Here's my code as a hint in that direction. The second code block is using the CameraRoll to browseForImage() but there is no browseForVideo() in the API.
if(CameraUI.isSupported)
{
camera = new CameraUI();
camera.addEventListener(MediaEvent.COMPLETE, videoMediaEventComplete);
camera.addEventListener(Event.CANCEL, cameraCanceled);
camera.addEventListener(ErrorEvent.ERROR, cameraError);
camera.launch(MediaType.VIDEO);
}
else
{
statusText.text = "Camera not supported on this device.";
startTimer();
}
if (CameraRoll.supportsBrowseForImage)
{
roll = new CameraRoll();
roll.addEventListener(MediaEvent.SELECT, cameraRollEventComplete);
roll.addEventListener(Event.CANCEL, cameraCanceled);
roll.addEventListener(ErrorEvent.ERROR, cameraError);
roll.browseForImage();
}
else
{
statusText.text = "Camera roll not supported on this device.";
startTimer();
}
I've since found that Videos captured using the delegated system camera are stored in a temporary storage location that iOS -DOES!- allow access to. (I was pleasantly shocked.)
The Captured video is not added to the device's Camera Roll as other videos captured using the iOS System Camera app, so it's not enough to capture video and expect to be able to access it later (if, for instance, CameraRoll.browseForVideo() is ever added to the API.
Therefore, you have to 'get while the getting is good' and move the file from the temporary storage location to some non-volatile location such as ApplicationStorageDirectory or the user's Documents directory (The only options in iOS I think).
The MediaPromise... I think... is completely useless for accessing the video via any direct progressive loader/streamer method, but still provides the location/url/path/filename of the temporary file so you can perform File operations on it.
Ironic that there are tutorials for getting around the lack of a file location/url/path/filename in the MediaPromise when using CameraRoll.browseForImage()... and that method is to use a loader class to load the image content (which you can then write out to a file), but when taking video, the video content is not accessible, and instead a file location/url/path/filename is provided. Ironic that there are nearly no resources I was able to find to help with this also. grumble
I'm going to include some code chunks w/o really editing them to strip out extraneous bits because it's way past when I need to be in bed, but I wanted you to have this. I may come clean it up later.
This section is in a Spark SkinnablePopUpContainer and I use the same click event for several buttons, thus the below 'case' is in the switch-case in that event handler function.
In case you are not familiar, the 'close(true, data)' is the method to close the SkinnablePopUpContainer, tell the parent/owner that the container was closed purposefully and that it should look for the data object being shared back (i.e., there are changes to be 'commit'ed).
case "cameraVideo":
{
if(CameraUI.isSupported)
{
camera = new CameraUI();
camera.addEventListener(MediaEvent.COMPLETE, videoMediaEventComplete);
camera.addEventListener(Event.CANCEL, cameraCanceled);
camera.addEventListener(ErrorEvent.ERROR, cameraError);
camera.launch(MediaType.VIDEO);
}
else
{
statusText.text = "Camera not supported on this device.";
startTimer();
}
break;
}
protected function cameraCanceled(event:Event):void
{
statusText.text = "Camera access canceled by user.";
startTimer();
}
protected function cameraError(event:ErrorEvent):void
{
statusText.text = "There was an error while trying to use the camera.";
startTimer();
}
protected function videoMediaEventComplete(event:MediaEvent):void
{
statusText.text="Preparing captured video...";
camera.removeEventListener(MediaEvent.COMPLETE, videoMediaEventComplete);
camera.removeEventListener(Event.CANCEL, cameraCanceled);
camera.removeEventListener(ErrorEvent.ERROR, cameraError);
var media:MediaPromise = event.data;
data.MediaType = MediaType.VIDEO;
data.MediaPromise = media;
data.source = "camera video";
close(true,data)
}
This section is the Actionscript in the close handler of the parent/owner of the SkinnablePopUpContainer (truncated once the useful code is included)
private function choosePictureLightboxClosed(event:PopUpEvent):void
{
imageButtonsActive = false;
if(event.commit)
{
this.data = event.data as Object;
filters = new Array();
selection = true;
switch(data.MediaType)
{
case MediaType.VIDEO:
{
mediaType = "video";
trace(data.MediaPromise.file.url + " - " + data.MediaPromise.relativePath + " - " +data.MediaPromise.mediaType);
var sourceFile:File = new File(data.MediaPromise.file.url);
var destinationFile:File = File.applicationStorageDirectory.resolvePath("User" +parentApplication.userid);
if(destinationFile.exists && !destinationFile.isDirectory)
{
destinationFile.deleteFile();
}
destinationFile.createDirectory();
destinationFile = destinationFile.resolvePath("Videos");
if(destinationFile.exists && !destinationFile.isDirectory)
{
destinationFile.deleteFile();
}
destinationFile.createDirectory();
destinationFile = destinationFile.resolvePath(parentApplication.userid+"Video"+new Date().getTime()+".mov");
trace(destinationFile.nativePath);
sourceFile.moveTo(destinationFile,true);
break;
}
I sure do hope this helps. This has been a very frustrating (and costly in terms of our project being government grant funded and having deadlines we utterly failed to meet), and I very much hope that these hard-won solutions might help others avoid the same experience.