Titanium Android : Facebook dialog image URL not properly formatted - android

I developing an Android application using Titanium Appcelerator. I had tried to Post text and Image via facebook feed dialog
.. But error while load my local image URL..
var fileimg = Titanium.Filesystem.getFile(backupDir.nativePath, "myimg.jpg");
var fb_data1 = {
description : "Some good text",
picture : fileimg.nativePath,
link : "www.googlee.com",
};
facebook_qfav.dialog("feed", fb_data1, showRequestResult);
function showRequestResult(e) {
var s = '';
if (e.success) {
s = "SUCCESS";
if (e.result) {
s += "; " + e.result;
}
if (e.data) {
s += "; " + e.data;
}
if (!e.result && !e.data) {
s = '"success",but no data from FB.I am guessing you cancelled the dialog.';
}
} else if (e.cancelled) {
s = "CANCELLED";
} else {
s = "FAILED ";
if (e.error) {
s += "; " + e.error;
alert("facebook Share " + s);
}
}
}
ERROR: "Image URL not properly formatted"
File path will be like this: file:///storage/sdcard0/myimg.jpg
But if i pass the remote URL to the picture property , the image is shown in the dialog...
what happens to the local URL..?

I think the only issue is that nativepath has capital P in it. so, its : nativePath
so instead of picture : fileimg.nativepath, It Should be picture : fileimg.nativePath,
Documentation.
Hope it helps.

Related

Uno Plataform Android and UWP: how copy file to local folder?

I'm trying to pick pictures files and copy them to app local folder, and save path as string in database to display images, the code works fine on UWP but does not on Android (I'm using Uno Platform):
string SImag = string.Empty;
private async Task<string> MediaxPicAsync()
{
Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".gif");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
try
{
Windows.Storage.StorageFile temp = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("TempFile." + file.FileType);
await file.CopyAndReplaceAsync(temp);
return temp.Path;
}
catch (Exception ex)
{
await new Windows.UI.Popups.MessageDialog("Could not open image!", "Error image loading").ShowAsync();;
}
}
return string.Empty;
}
Xaml Code:
<Image>
<Image.Source>
<BitmapImage UriSource="{x:Bind SImag, Mode=OneWay,Converter={StaticResource appClsConvStr2Imag}}" />
</Image.Source>
</Image>
Converter:
public class ClsConvStr2Imag : Windows.UI.Xaml.Data.IValueConverter
{
object Windows.UI.Xaml.Data.IValueConverter.Convert(object value, Type targetType, object parameter, string language)
{
if (string.IsNullOrEmpty(value as string))
{
return null;
}
else
{
string sPath = (string)value;
if (sPath.Contains("/") | sPath.Contains("\\"))
{
}
else
{
if (parameter == null)
{
sPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\" + sPath;
}
else
{
sPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\" + parameter + "\\" + sPath;
}
}
return new Uri(sPath);
}
}
object Windows.UI.Xaml.Data.IValueConverter.ConvertBack(object value, Type targetType, object parameter, string language)
{
return value;
}
}
On Visual studio output during Android debug it shows error as:
[BitmapFactory] Unable to decode stream: java.io.FileNotFoundException: /data/user/0/Sale.Sale/files/TempFile.png (No such file or directory)
Any help to overcome this issue is most welcome, I did research for 3 days and could not find clean solution for this issue. Many thanks in advance for time and expertise.

Xamarin Microsoft Oxford Vision problem with text recognize

I have a problem with text recognition from receipts using Microsoft Oxford Vision with Xamarin.Forms.
Here is a code:
private async void BtnTake_Clicked(object sender, EventArgs e)
{
try
{
var photo = await TakePic();
Image = ImageSource.FromStream(() => photo.GetStream());
var result = client.RecognizeTextAsync(photo.GetStream()).Result;
var words = from r in result.Regions
from l in r.Lines
from w in l.Words
select w.Text;
OutputText = string.Join(" ", words.ToArray());
await Navigation.PushAsync(new TextFromPhoto(OutputText, Image));
}
catch (Exception ex)
{
OutputText = "Ops! Something wrong!" + ex.ToString();
await Navigation.PushAsync(new TextFromPhoto(OutputText, Image));
}
}
private async Task<MediaFile> TakePic()
{
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
SaveToAlbum = true,
PhotoSize = PhotoSize.Medium
});
return file;
}
Code is perfectly working with normal text, like book photo page what i was took in application, but when i'm trying to use this to scan text from receipt program doesn't know what to do and on output we can see "513nlkm nlmnl l1mk 531" or something like that.
Photo when i have "normal" text:
Photo when i have receipt text:
Are there any proven ways to fix this?

SVM model fails to load in Android Application

I have a problem with load() method in SVM module. For example if I run code:
try {
Uri uri = Uri.fromFile(new File("file:///android_asset/SVM_Bills.xml"));
mySvm.load(uri.getPath());
int in = mySvm.get_support_vector_count();
if (in != 0) {
Toast.makeText(context,"done loading : " + uri.getPath(), Toast.LENGTH_SHORT).show();
value = (int)mySvm.predict(matOfDescriptor);
}
else {
Toast.makeText(context,"error while loading : " + uri.getPath(), Toast.LENGTH_SHORT).show();
}
It give me the error toast message (i.e it goes to else part and show the toast message).
Of course SVM was previously trained.
Any help please?

How to remove file from list after successful upload?

This is my first question on StackOverflow so please bear with my noobness.
I am writing a Cordova app with Ionic Framework and I am trying to upload multiple files from the camera to a server while displaying the uploaded files in a list and showing the progress for each of them. But I can't seem to figure out how to delete the files from the display list after a successful upload. I am trying to use the ID of the File I get after I push it to the array, but those seem to be incorrect sometimes. E.g. the ID in the progress event is different than in the success event and therefore I am removing the wrong file from the list or sometimes no file.
$scope.choosePic = function() {
window.imagePicker.getPictures(
function(results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
onSuccess(results[i]);
}
}, function (error) {
console.log('Error: ' + error);
}
);
}
$scope.delete = function ( item ) {
$scope.items.splice($scope.items.indexOf(item), 1);
}
var onSuccess = function(FILE_URI) {
console.log(FILE_URI);
$scope.picData = FILE_URI;
var filename = $scope.makeid();
var length = $scope.items.push({name: filename, image: $scope.picData, progress:0 });
$scope.$apply();
send($scope.picData,filename,length);
};
var onFail = function(e) {
console.log("On fail " + e);
}
send = function(imagedata,filename,length) {
var options = new FileUploadOptions();
var url = window.localStorage['URL'];
options.fileKey="file";
options.chunkedMode = false;
options.mimeType="image/jpeg";
options.headers = {Connection: "close"};
var params = {};
params.APIKEY = window.localStorage['APIKEY'];
params.DEVICEID = device.uuid;
options.params = params;
var ft = new FileTransfer();
var ID = length -1;
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
if(!(typeof $scope.items[ID] == 'undefined')){
$scope.items[ID].progress=perc;
$scope.$apply();
console.log($scope.items[ID].name + "Upload progress: " + perc);
}
} else {
}
};
function onUploadSuccess(r) {
//alert("ID = " + ID + " Code = " + r.responseCode + "Response = " + r.response + "Sent = " + r.bytesSent);
//alert($scope.items[ID].name);
console.log("ID = " + ID + " Code = " + r.responseCode + "Response = " + r.response + "Sent = " + r.bytesSent);
$scope.items.splice(ID, 1); // remove uploaded image from list
$scope.$apply();
}
function onUploadFail(error) {
alert("An error has occurred: Code = " + error.code);
//console.log("upload error source " + error.source);
// console.log("upload error target " + error.target);
}
options.fileName=filename+".jpg";
ft.upload(imagedata, encodeURI(url), onUploadSuccess, onUploadFail, options);
}
});
I know this code probably rather clumsy but this the first time I am working with AngularJS and Cordova and the likes of it. Thanks for your help in advance.

How to download and save a file using phonegap/cordova on Android

I am at my whit's end.
I will try to keep it brief.
Using Cordova/Phonegap 3.0 (and get the same results on 2.8.0).
Android version 4.0.4.
Code works on BlackBerry10 (Q10 and Z10).
On Android it errors with a JSON Error (no, I'm not parsing JSON, this seems to come out of cordova's bowels). I will paste the JSON.stringified error object at the end of this.
So, on to code then:
First a filesystem success function:
function onFSSuccess(fileSystem) {
if (fileSystem == null) {
window.alert("fileSystem is null");
}
var root = fileSystem.root;
root.getDirectory("com.app.id",{create:true},gotDir,onError);};
Then a function to handle success with directory retrieval:
function gotDir(d){
DATADIR = d;
doTheDl (d.fullPath + "/update.sql",fileTransfer);
};
Then the actual call to get the filesystem:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, null);
Then a function to download the file:
function doTheDl (localPath,fileTransfer) {
try {
window.alert ("Downloading to '" + localPath + "'");
fileTransfer.download (
uri,
localPath,
function (entry) {
try {
$("#dbDownloadProgressContainer").text("File saved to " + entry.name + ". Applying script to database...");
dbInitObj.applyUpdateScript(entry);
}
catch (e) {
window.alert ( e);
}
},
function (err) {
window.alert ("ERROROR!!! - " + err);
var errCodeName = err.code;
switch (err.code) {
case FileTransferError.FILE_NOT_FOUND_ERR:
errCodeName ='FILE_NOT_FOUND_ERR';
break;
case FileTransferError.INVALID_URL_ERR:
errCodeName="INVALID_URL_ERR";
break;
case FileTransferError.CONNECTION_ERR:
errCodeName="CONNECTION_ERR";
break;
case FileTransferError.ABORT_ERR:
errCodeName="ABORT_ERR";
break;
default:
errCodeName = "UNKNOWN";
break;
}
window.alert ("Download failed: " + err.source + ", " + err.target + ", " + errCodeName);
},
true
);
}
catch (e) {
window.alert ( e);
}
}
Man, gotta love all these async callbacks...
Next we get to the heart of the matter, trying to READ the downloaded file:
//Bulk of applyUpdateScript script ommited, but eventually it gets here:
function readComplete (evt) {
$("#dbDownloadProgressContainer").text("Parsing script file...");
//Got this gem from here: http://beckism.com/2010/09/splitting-lines-javascript/
var lines = evt.target.result.match(/^.*([\n\r]+|$)/gm);
//var lineIndx = lines.length;
window.setTimeout(function () {
$("#dbDownloadProgressContainer").text("Processing " + lines.length + " statements");
},50);
};
try {
var fileReader = new FileReader();
fileReader.onloadend=readComplete;
fileReader.onerror=function (err) {
//var errStr = translateFileError (err);
window.alert ("FileReader.onerror: " +JSON.stringify (err));
};
fileReader.onloadstart=function (evt) {
window.alert ("FileReader.onloadstart - " + JSON.stringify (evt));
};
fileReader.onload=function (evt)
{
window.alert ("FileReader.onload - Called when the read has successfully completed.- " + JSON.stringify (evt));
};
fileReader.onprogress = function (evt)
{
window.alert ("FileReader.onprogress - " + JSON.stringify (evt));
}
fileReader.onabort = function (evt)
{
window.alert ("FileReader.onabort - " + JSON.stringify (evt));
}
function gotFile (fileEntry) {
window.alert ("Activating reader for file '" + fileEntry.fullPath + "'");
fileReader.readAsText(fileEntry);
};
function noFileFound (fileError) {
alert ("Can not access database update script: code " + translateFileError (fileError));
};
// window.alert ("scriptPath.name = " + scriptPath.name);
DATADIR.getFile (scriptPath.name,null,gotFile,noFileFound);
}
catch (e) {
window.alert (e);
}
NOW, when I hit the reading bits, I eventually get this from the 'onerror' event (rember this is the JSON.stringfied error object:
{
"type":"error",
"bubbles":false,
"cancelBubble":false,
"cancelable":false,
"lengthComputable":false,
"loaded":0,
"total":0,
"target":{
"_readyState":2,
"_error":{
"code":"JSON error"
},
"_result":null,
"_fileName":"file:///mnt/sdcard/com.app.id/update.sql",
"_realReader":{
"error":null,
"result":"",
"readyState":0
}
}
}
Please also note that 'com.app.id' is a place holder for the actual app ID - can't paste that for fear of sensitive names. I did try other folder names as well.
Other notable(?) items:
The download progress event seems to indicate that we are downloading precisely double the actual file size (wtf?)
Results are the same on android device and emulator
BlackBerry10 seems to work fine
Thanks in advance to any clever people....
OK.
This was the solution:
function gotFile (fileEntry) {
fileEntry.file (function (file) {
fileReader.readAsText(file);
});
};
So thanks a BAJILLION to this dude:
http://www.html5rocks.com/en/tutorials/file/filesystem/?ModPagespeed=noscript
In case you missed it, the magic is the call to the "file(...)" function on the fileEntry object.
Why it works on the BB10 WITHOUT it....aarrgggghhh

Categories

Resources