SVM model fails to load in Android Application - android

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?

Related

How to open Google Play from the phone remotely on the watch (Wear OS)

What is the correct way to remotely open Google Play from the phone on the watch (Wear OS)? I am trying this:
Intent intentOnWatch = new Intent(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.parse("https://play.google.com/store/apps/details?id=\" + getPackageName()"));
RemoteIntent.startRemoteActivity(getApplicationContext(), intentOnWatch, null, null);
But nothing happens.
The last parameter is the nodeId. I left it as zero because the documentation says :
nodeId String: Wear OS node id for the device where the activity should be started. If null, and the current device is a watch, the activity will start on the companion phone device. Otherwise, the activity will start on all connected watch devices.
Source: https://developer.android.com/reference/com/google/android/wearable/intent/RemoteIntent#startremoteactivity
I could determine the nodeId, but it seems difficult to do. Plus in this case, starting the activity on all connected watch devices would be fine.
Is it possible to download a file using DownloadManager?
This example (sorry it's Kotlin) should work
val remoteActivityHelper =
RemoteActivityHelper(application, Dispatchers.IO.asExecutor())
val nodes = Wearable.getNodeClient(application).connectedNodes.await()
val nodeId = nodes.firstOrNull { it.displayName == "XXX" }?.id
if (nodeId == null) {
Toast.makeText(application, "No connected wear watch", Toast.LENGTH_SHORT).show()
} else {
try {
remoteActivityHelper.startRemoteActivity(
Intent(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(
Uri.parse("https://www.bbc.co.uk/sounds/play/${programme.code}")
),
).await()
} catch (e: Exception) {
toaster.showToast("Unable to open mobile app: ${e.message}")
}
}
}
But the main thing in your example is that you are not checking the result of startRemoteActivity, it returns a ListenableFuture, so you could check for an error. In the example above, I'm using the .await() extension function which does the same thing.
There are more complete examples in https://github.com/android/wear-os-samples/blob/d18c489ff415aa0fbb25c260e3aacdf50f7716e3/WearVerifyRemoteApp/Application/src/main/java/com/example/android/wearable/wear/wearverifyremoteapp/MainMobileActivity.kt
I'm not sure about the exact implementation for Java, it's really messy with the Task and Future APIs mixed here. Maybe
RemoteActivityHelper remoteActivityHelper = new RemoteActivityHelper(application, executor);
NodeClient client = Wearable.getNodeClient(application);
client.getConnectedNodes().addOnSuccessListener(nodes -> {
if (nodes.size() > 0) {
String nodeId = nodes.get(0).getId();
ListenableFuture<Void> result = remoteActivityHelper.startRemoteActivity(
new Intent(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(
Uri.parse("https://www.bbc.co.uk/sounds/play/${programme.code}")
)
, nodeId);
result.addListener(() -> {
try {
result.get();
} catch (Exception e) {
Toast.makeText(application, "Failed " + e, Toast.LENGTH_SHORT).show();
}
}, executor);
} else {
Toast.makeText(application, "No connected wear watch", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(failure -> {
Toast.makeText(application, "Unable to open mobile app: ${e.message}", Toast.LENGTH_SHORT).show();
});
I've been fighting with exatly the same problem last two days.
Works for me the next code:
Intent intent = new Intent(Intent.ACTION_VIEW)
.addCategory(Intent.CATEGORY_BROWSABLE)
.setData(Uri.parse(PLAY_STORE_APP_URI));
for (Node node : nodesWithoutApp) {
RemoteActivityHelper remoteActivityHelper =
new RemoteActivityHelper(this, Executors.newSingleThreadExecutor());
remoteActivityHelper.startRemoteActivity(intent, node.getId());
}
It didn't work with RemoteIntent.startRemoteActivity for some reason.

How to get download URL of multiple images uploaded using Android & Firebase

I see similar questions on this site but most of the questions are related to fetching the download URL for a single uploaded image. Taking help from those posts, now I can get the download URL of a single image.
But I face a problem when I try to get download URL for multiple images uploaded together. I want to do three things...
1. Select three images
2. Upload them to Firebase Cloud Storage
3. Get the URLs of the uploaded images and save them in an ArrayList.
I can do the first two things successfully, but have not managed to achieve the third thing. When I click the "update" button, all images are perfectly stored in Cloud Storage, but show an error when requesting the download URL of all images.
Here is the code for when I click the "update" button:
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.setMessage("Uploading .... ");
progressDialog.show();
storageReference = FirebaseStorage.getInstance().getReference().child("Pictures");
int uploadCount = 0;
// imageList is an ArrayList<Uri> which holds the address of selected 3 images.
// imageAddress is an ArrayList<String> where I want to save all downloadUrls of images (each url is saved as a string).
// imagePath is a StorageReference
while(uploadCount < imageList.size()) {
Log.d("UploadCount", uploadCount+"");
Uri uri_Image = imageList.get(uploadCount);
imagePath = storageReference.child(uri_Image.getLastPathSegment());
imagePath.putFile(uri_Image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imagePath.getDownloadUrl().addOnSuccessListener(newOnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
imageAddress.add(downloadUri.toString());
Log.d("ImageAddress Size: ", imageAddress.size()+"");
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignOutActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}); //.............
if(uploadCount == (imageList.size()-1)) {
Log.d("Good", "HELLO HELLO");
Toast.makeText(SignOutActivity.this, "Successfully Uploaded", Toast.LENGTH_LONG).show();
upload.setClickable(false);
progressDialog.dismiss();
}
else {
Log.d("BAD", "NOT HELLO "+uploadCount);
}
uploadCount = uploadCount + 1;
}
}
});
Here is the error:
2020-02-15 17:02:26.945 28207-28735/com.example.practiceapplication E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-02-15 17:02:26.946 28207-28735/com.example.practiceapplication E/StorageException: {"error": {"code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT"}}
java.io.IOException: {"error": {"code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT"}}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##19.1.1:433)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##19.1.1:450)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##19.1.1:441)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##19.1.1:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
2020-02-15 17:02:30.712 28207-28207/com.example.practiceapplication D/ImageAddress Size:: 1
It will be very helpful to me if anyone tells me the correction. Thank you
Your code suffers from using a mix of local variables and shared global variables whilst dealing with asynchronous code and for loops.
In the code above, you use the global variables imagePath, imageAddress and imageList inside a for loop which ultimately is the key cause of that Exception.
Code breakdown
When you click the upload button, your code performs the following steps with errors shown in bold:
Gets the first image's URI
Updates the value of imagePath to point at that image's upload location
Starts the upload of the first image
Logs "NOT HELLO 0"
Gets the second image's URI
Updates the value of imagePath to point at that image's upload location
Starts the upload of the second image
Logs "NOT HELLO 1"
Gets the third image's URI
Updates the value of imagePath to point at that image's upload location
Starts the upload of the third image
Logs "HELLO HELLO" and Toasts "Successfully Uploaded" (not actually finished yet)
[a few moments later]
The first image finishes uploading
The download URL of the third image is requested (which throws the StorageException)
The second image finishes uploading
The download URL of the third image is requested (which throws another StorageException)
The third image finishes uploading
The download URL of the third image is requested (and would work correctly)
Fixes
To fix this, the following things must be done:
Use a local variable copy of imageList
Use a local variable for storageReference
Use a local variable for imagePath, and rename to imageRef to accurately reflect it's type
Rename imageAddress to imageAddressList to accurately reflect it's type (recommended)
Remove the while() loop and use a for iterator instead
Disable the upload button immediately instead of at the end
Upload each image and fetch the download URLs in parallel, without conflicting with each other
Only display "Successfully uploaded" or "Upload failed" messages after the uploads have actually completed
Update imageAddressList only once, rather than asynchronously.
To be done:
Handle activity lifecycle changes
Tap into currentUploadTask and bind it to a view dialog/notification to show file upload progress
Update the UI once all the uploads are done
Updated code
Note: This was typed free-hand - expect a few typos.
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.setMessage("Uploading .... ");
progressDialog.show();
upload.setClickable(false); // disable upload button whilst uploading
final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Pictures");
final List<Uri> clonedImageList = new ArrayList<>(imageList);
imageList.clear(); // empty old list?
int imageListSize = clonedImageList.size();
List<Task<Uri>> uploadedImageUrlTasks = new ArrayList<>(imageListSize);
for (Uri imageUri : clonedImageList) {
final String imageFilename = imageUri.getLastPathSegment();
Log.d("upload.onClick()", "Starting upload for \"" + imageFilename + "\"...");
StorageReference imageRef = storageReference.child(imageFilename); // Warning: potential for collisions/overwrite
UploadTask currentUploadTask = imageRef.putFile(imageUri);
Task<Uri> currentUrlTask = currentUploadTask
.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
Log.d("upload.onClick()", "Upload for \"" + imageFilename + "\" failed!");
throw task.getException(); // rethrow any errors
}
Log.d("upload.onClick()", "Upload for \"" + imageFilename + "\" finished. Fetching download URL...");
return imageRef.getDownloadUrl();
}
})
.continueWithTask(new Continuation<Uri, Uri>() { // purely for logging to debug, recommended to remove
#Override
public Task<Uri> then(#NonNull Task<Uri> task) throws Exception {
if (!task.isSuccessful()) {
Log.d("upload.onClick()", "Could not get download URL for \"" + imageFilename + "\"!");
throw task.getException(); // rethrow any errors
}
Log.d("upload.onClick()", "Download URL for \"" + imageFilename + "\" is \"" + task.getResult() + "\".");
return task.getResult();
}
});
uploadedImageUrlTasks.add(currentUrlTask);
}
// At this point, all the files are being uploaded in parallel
// Each upload is tracked by the tasks in uploadedImageUrlTasks
Tasks.whenAllComplete(uploadedImageUrlTasks)
.addOnCompleteListener(new OnCompleteListener<List<Task<Uri>>>() {
#Override
public void onComplete(#NonNull List<Task<Uri>> tasks) {
int tasksCount = tasks.size();
List<Uri> failedUploads = new ArrayList<>();
imageAddressList.clear(); // empty old entries?
for (Task<Uri> task : tasks) {
if (task.isSuccessful()) {
successCount++;
Uri downloadUri = task.getResult();
imageAddressList.add(downloadUri.toString());
} else {
Uri imageUri = clonedImageList.get(tasks.indexOf(task));
failedUploads.add(imageUri);
Log.e("upload.onClick()", "Failed to upload/fetch URL for \"" + imageUri.getLastPathSegment() + "\" with exception", task.getException()); // log exception
}
}
progressDialog.dismiss(); // dismiss upload dialog
if (failedUploads.size() > 0) {
Toast.makeText(SignOutActivity.this, failedUploads.size() + "/" + tasksCount + " uploads failed.", Toast.LENGTH_LONG).show();
// TODO: Do something with list of failed uploads such as readd to the now empty upload list
imageList.addAll(failedUploads);
upload.setClickable(true);
} else {
Toast.makeText(SignOutActivity.this, "Successfully uploaded all " + tasksCount + " files.", Toast.LENGTH_LONG).show();
}
// TODO: Now that imageAddressList has been updated, update the UI - e.g tell recycler view to refresh
}
});
}
});

how to store fingerprint data in database android

I am using mantra fingerprint scanner to get finger print data, I want to store the fingerprint data in mysql.Later i want to compare with other. I am facing issue in Storing the data in mysql.
here is the code where after scanner gives the fingerprint data.
private void StartSyncCapture() {
runOnUiThread(new Thread(new Runnable() {
#Override
public void run() {
try {
FingerData fingerData = new FingerData();
int ret = mfs100.AutoCapture(fingerData, timeout, false,
true);
if (ret != 0) {
Toast.makeText(getApplicationContext(), "StartSyncCapture " + mfs100.GetErrorMsg(ret), Toast.LENGTH_SHORT).show();
} else {
if (fingerData.Quality() >= minQuality) {
final Bitmap bitmap = BitmapFactory.decodeByteArray(
fingerData.FingerImage(), 0,
fingerData.FingerImage().length);
imgFinger.post(new Runnable() {
#Override
public void run() {
imgFinger.setImageBitmap(bitmap);
imgFinger.refreshDrawableState();
}
});
Toast.makeText(getApplicationContext(), "Capture Success", Toast.LENGTH_SHORT).show();
String log = "\nQuality: " + fingerData.Quality()
+ "\nNFIQ: " + fingerData.Nfiq()
+ "\nWSQ Compress Ratio: "
+ fingerData.WSQCompressRatio()
+ "\nImage Dimensions (inch): "
+ fingerData.InWidth() + "\" X "
+ fingerData.InHeight() + "\""
+ "\nImage Area (inch): " + fingerData.InArea()
+ "\"" + "\nResolution (dpi/ppi): "
+ fingerData.Resolution() + "\nGray Scale: "
+ fingerData.GrayScale() + "\nBits Per Pixal: "
+ fingerData.Bpp() + "\nWSQ Info: "
+ fingerData.WSQInfo();
Toast.makeText(getApplicationContext(), "fingerData.Quality()" + fingerData.Quality() + "StartSyncCapture is " + fingerData.ISOTemplate().length, Toast.LENGTH_SHORT).show();
mFingerData = fingerData;
//////////////////// Extract ISO Image
int dataLen = 0;
byte[] tempData = new byte[(mfs100.GetDeviceInfo().Width() * mfs100.GetDeviceInfo().Height()) + 1078];
byte[] isoImage = null;
dataLen = mfs100.ExtractISOImage(fingerData.RawData(), tempData);
if (dataLen <= 0) {
if (dataLen == 0) {
Toast.makeText(getApplicationContext(), "Failed to extract ISO Image", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), mfs100.GetErrorMsg(dataLen), Toast.LENGTH_SHORT).show();
}
return;
} else {
isoImage = new byte[dataLen];
System.arraycopy(tempData, 0, isoImage, 0, dataLen);
mISOImage = new byte[dataLen];
System.arraycopy(tempData, 0, mISOImage, 0, dataLen);
}
} else {
Toast.makeText(getApplicationContext(), "Please try again", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
}));
}
fingerprint scanners only return image, either you can store bitmap into database or you can save image into local storage and path of image into database.
you can use external library to convert image to minutiae and enroll and verify as:
http://www.nist.gov/itl/iad/ig/nbis.cfm
http://www.neurotechnology.com/verifinger.html
Images having of different types such as bitmap, iso, wsq etc..
normally, from photo viewer only bitmap image can be previewed. But if you want to preview iso image (19794-4) then you need iso viewer and if you want to preview wsq image then you need to use wsq viewer.
About storing images in to database, you need to use blob datatype and you need to convert bitmap image into byte array and then you have to store into database.
but remember, if you want to use stored image for verification purpose then you need to store ISO Template (19794-2) into your database.
to get ISO template (19794-2), you have to use mfs100.ExtractISOTemplate function of SDK.
also best solution for store and reuse your fingerprint data in Mantra device so save your ISO temple to base64 string and store base64 string in database and get fingerprint data from database so create file from base64 to ISO temple
check this url
Base 64 encode and decode example code

Titanium Android : Facebook dialog image URL not properly formatted

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.

WebView from Unity3d Android is not shown

I am trying to show a webview in unity3d from an Android Application.
The components of this test are:
Android library(has a method that i call for test purposes):
public void nonStaticMethod() {
Log.d("TAG", "Non-static method was called from my android class");
String url = "http://roadtoautomation.blogspot.ro/2014/02/road-to-setup-and-create-first-appium.html";
Toast.makeText(mContext, "URL: " + url, Toast.LENGTH_SHORT).show();
webView = new WebView(mContext);
Log.d("Interstitialactivity", "webView: " + webView);
Toast.makeText(mContext, "webView: " + webView, Toast.LENGTH_SHORT).show();
webView.loadUrl(url); // webview is not null
}
Mono code from class:
using (AndroidJavaClass javaInterClass = new AndroidJavaClass("mypackage.MyActivity")) {
if (javaInterClass != null) {
Debug.Log ("MyActivity class is NOT null");
try {
Debug.Log ("before my activity");
javaInterClass.Call ("nonStaticMethod");
Debug.Log ("after my activity");
} catch (Exception e) {
Debug.Log ("exception");
Console.WriteLine (e);
}
} else {
Debug.Log ("MyActivity class is null");
}
}
From the above code i can see the android class is not null, but the webview( from this "javaInterClass.Call ("nonStaticMethod");") is not shown.
Do i have to add a plugin in unity3d for supporting webview? Thanks.
If you want to open webview over Unity's UI you need an activity or you need to override unity's activity otherwise you can try this
Uri uri = Uri.parse("http://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
but it work same as Unity's Application.LoadUrl(url)

Categories

Resources