Trying to call the JavaScript function from Java Source code - java

I am developing an Android App to read the barcode by using the Zxing Barcode reader Plugin.
In the plugin there is an object named window.plugins.barcodeScanner with which we encode/decode the barcode.
I don't wanna use HTML to invoke things instead want the below Javascript function to be called from Java [on click of the image- the below function would be invoked].
function scanCode(){
window.plugins.barcodeScanner.scan(
function(result){
alert("Scanned Code: " + result.text
+ ". Format: " + result.format
+ ". Cancelled: " + result.cancelled);
},
function(error){
alert("Scan failed: " + error);
}
);
}
Kindly let me know how to achieve this.

Assumptions:
You've already setup the LibararyProject from https://github.com/wildabeast/BarcodeScanner/tree/master/src/android.
Your Activity is not extending CordovaActivity but is extending Activity.
Your main goal is really just to use the scanner. You were just trying to find an easy/quick way to do so and thought the PG plugin may do the trick.
All you have to do is pull out the scan and onActivityResult methods and some of the helper strings from https://github.com/wildabeast/BarcodeScanner/blob/master/src/android/com/phonegap/plugins/barcodescanner/BarcodeScanner.java and put them in your activity. You'll need to replace the references to cordova with your own activity.
End result may look something like this:
public static final int REQUEST_CODE = 0x0ba7c0de;
private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
public void scan() {
Intent intentScan = new Intent(SCAN_INTENT);
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
this.startActivityForResult(intentScan, REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String barcode = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
//Do whatever you need with the barcode here
} else if (resultCode == Activity.RESULT_CANCELED) {
// handle a canceled scan
} else {
// throw an error or something
}
}
}
If that works for you, then you don't even need cordova as a dependancy.

You can invoke Javascript code from native side on Android using the sendJavascript function defined in CordovaWebView.
In your case you would do something like this. Considering that the you want to call the following function:
function scanSuccessCallback(result) {
//do something
}
on the native side in your plugin:
this.webView.sendJavascript("scanSuccessCallback('the result');");

Related

How to learn what is the "key" in Android Studio Bundle?

I'm using a library which is not up to date. (https://github.com/notsukamto/GFIPhotoPicker)
It has a onActivityResult function to get activity result. It returns an intent with this function
if (selection != null) {
intent.putExtra(EXTRA_SELECTION, new LinkedList<>(selection));
}
public static List<Uri> getSelection(Intent data) {
return data.getParcelableArrayListExtra(EXTRA_SELECTION);}
So my question is what is the key for this Parcelable and how I get that intent correctly?
(I tried "EXTRA_SELECTION" which is not working)
Bundle[
{com.github.potatodealer.gfiphotopicker.activity.extra.SELECTION=
[file:///storage/emulated/0/DCIM/Camera/IMG_20190114_072919.jpg,
file:///storage/emulated/0/DCIM/Camera/IMG_20190114_072904.jpg,
file:///storage/emulated/0/DCIM/Camera/IMG_20190114_072848.jpg],
com.github.potatodealer.gfiphotopicker.activity.extra.FACEBOOK_SELECTION=[],
com.github.potatodealer.gfiphotopicker.activity.extra.INSTAGRAM_SELECTION=[]
}
]
If you access this directory in the github link you provided, there will be a EXTRA_SELECTION constant in each of those activities.
For example, if we click on the FacebookPreviewActivity.java, we see:
private static final String EXTRA_SELECTION = FacebookPreviewActivity.class.getPackage().getName() + ".extra.SELECTION";

Zxing NotFoundException with Barcode 128C

I try to use Zxing to decode 128C (Code set C) barcodes. I have success when I read other types like QR_CODE, UPC_A.
These are barcodes that I trying to read:
Is possible read 128C barcodes (Not CODE 128 pure) with Zxing ?
Short aswer, yes, it should is possible. As 128C just is a subset of 128. Can scan the codes, might take a few seconds. And have XZing working in a app.
You have found out that 128 is supported, now you got to make an translation. 128C takes the same input as 128, just turns out numbers. So you could make a translation from the data you get back, and turn it into 128C. Check the second link for how that translates.
https://github.com/zxing/zxing/blob/master/README.md
https://en.wikipedia.org/wiki/Code_128
Get the needed classes from the XZing github, put them in a package in the java part of your project. I used only 2:
IntentIntegrator
IntentResult
Here is how it is initiated in my code:
/**
* Method called to intiate the scan (it's linked to a button)
*/
public void doScan(View view) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
// when you click the Scan Bar Code button
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) { // we have a result
String scanContent = scanningResult.getContents(); // set the content of the scan.
String scanFormat = scanningResult.getFormatName(); // set the type of scan.
// You will want to put this data somewhere else, globals, etc.
} else {
toast("No scan data received!"); // call to make a toast
}
}

Get all folders google drive api on Android

I use the new Google drive api and I can't get All folders from my google drive, I only get the folders that I create with the google drive api...
Anybody know why happens this?
this is my code:
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
/**
* Called when activity gets invisible. Connection to Drive service needs to
* be disconnected as soon as an activity is invisible.
*/
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
/**
* Called when {#code mGoogleApiClient} is connected.
*/
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
rootFolder = Drive.DriveApi.getRootFolder(mGoogleApiClient);
rootFolder.listChildren(getGoogleApiClient()).setResultCallback(pruebaChildren);
}
ResultCallback<DriveApi.MetadataBufferResult> pruebaChildren = new
ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
if (!metadataBufferResult.getStatus().isSuccess()) {
showMessage("Problem while retrieving files");
return;
}
Log.i(TAG,"got root folder");
MetadataBuffer buffer = metadataBufferResult.getMetadataBuffer();
Log.i(TAG,"Buffer count " + buffer.getCount());
if(buffer.getCount() == 0){
createFolderApp();
}
else{
for(Metadata m : buffer){
Log.i(TAG,"Metadata name " + m.getTitle() + "(" + (m.isFolder() ? "folder" : "file") + ")");
if (m.isFolder() && m.getTitle().equals(TAG)){
Log.i(TAG,"APP FOLDER FOUND");
Drive.DriveApi.getFolder(mGoogleApiClient, m.getDriveId())
.listChildren(mGoogleApiClient)
.setResultCallback(foreachAppAplication);
}
}
}
return;
}
};
And now I want see all folders in rootFolder Drive, I try the requestSync() but the result is same... I need help please!
And another question: How I can set the AppFolder? I only see getAppFolder but How I can set ??
Thanks
By design, GDAA supports only the FILE scope, i.e. it will find / list only folders / files created by the Android app.
There are 2 ways around it:
Use one of the intents of the GDAA, basically letting the user pick the file / folder. That way it will become available to your app.
Use a different API, the REST Api, which supports the DRIVE scope, giving your app full set of files / folders.
In case you want to study how the two APIs behave, I've put two different demos on the Github (the REST and the GDAA CRUD demo wrappers).
The second part of your question does not have answer. You don't set the app folder, you can only get it's DriveFolder id. You use it to create / retrieve objects.
DriveFolder appFldr = Drive.DriveApi.getAppFolder(mGooleApiClient);
appFldr.createFile(...);
appFldr.createFolder(...);
appFldr.listChildren(...);
appFldr.queryChildren(...);
... and don't forget to add the SCOPE_APPFOLDER scope
Good Luck

Is there anyway to send the scanned QR code results directly to the server?

I have developed an android app for scanning QR Codes and send it over the server.
In this app i am getting multiple QR code scanned results in a list-view using an array list and sending them to the server on a button click event.
The requirement is to send all the scanned QR-code results directly to the
server without using any of the events e.g button click or something like that.
Here i am using zxing QR scanner using intent. Below is the code for getting the QR-code scan result.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == SCANNER_REQUEST_CODE) {
// Handle scan intent
if (resultCode == Activity.RESULT_OK) {
// Handle successful scan
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra(
"SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = (intentOrientation == Integer.MIN_VALUE) ? null
: intentOrientation;
String errorCorrectionLevel = intent
.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
QRContent = contents;
QR_Receivd.setText(QRContent);
listItems.add(QRContent); //adding scan result to an array list(listItems)
} else if (resultCode == Activity.RESULT_CANCELED) {
// Handle cancel
}
//On-click method to initiate scan.
#Override
public void onClick(View v) {
if (v.getId() == R.id.btScan) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "SCAN_MODE");
startActivityForResult(intent, SCANNER_REQUEST_CODE);
}
}
So instead of using on-click event i want to send the scanned result directly to a server immidiately after getting the result from the scanner.
Thanks!!!
Part 1
first you should pick how you want to send it. you can send it using the official tools, or using 3rd party libraries. i'll assume the later.
on my approach you will need, on the server, a PHP file in charge of recieving (by GET or by POST) the scanned QR as parameter.
example call :
myserver.com/API/addqr?qrcode=XXXXXXXXXX
this PHP file must then save that to your database, i suppose MYSQL.
PART 2
now that you have your server set, you should take a look at the different libs or the official documentation.
USING VOLLEY
Using Loopj's Android Async HTTP petitions (i reccomend this)
i will assume you pick method 2.
all you have to do is send the petition :
if (resultCode == Activity.RESULT_OK) {
//blah blah blah all the code that decodes and adds it to the listview
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("qrcode", "XXXXXXXXXXXXX");
client.post("myserver.com/API/addqr", params, new JsonHttpResponseHandler() {
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//do something with the response, if there is one.
}
});
}

Dropbox Sync API errors

I have downloaded and installed the Dropbox Sync API for Android from here: https://www.dropbox.com/developers/sync
I couldn't understand much of their tutorial. It lacked a lot of crucial variables, so that I had to find them out myself. I now have a very messy code and a lot of things aren't there.
private DbxAccountManager mDbxAcctMgr;
static final int REQUEST_LINK_TO_DBX = 0; // This value is up to you // thanks for telling what it actually does, Dropbox!
DbxPath path = new DbxPath("/test.pdf");
public void onClickLinkToDropbox(View view) {
mDbxAcctMgr.startLink((Activity)this, REQUEST_LINK_TO_DBX);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_LINK_TO_DBX) {
if (resultCode == Activity.RESULT_OK) {
DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount()); // try /catch error
DbxFile testFile = dbxFs.open(path); //try/catch error
String contents = testFile.readString();
Log.d("Dropbox Test", "File contents: " + contents); // try / catch error
} else {
// ... Link failed or was cancelled by the user.
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
This gives me errors on the 3 lines, saying that I need to add try/catch.
But when I add try/catch, Eclipse tells me to null the variables, which would mean all the functions would only read nulls, thus not reading anything..
Could anyone help me any further? Dropbox only confused me more by giving wrong instructions etc. I am sure that even if I didn't have 3 try/catch errors it would still not work.
Anyone here who has experience with the Dropbox Sync API and could share an example program reading a txt file in a User's Dropbox folder?
Bart
For more info on REQUEST_LINK_TO_DBX, check out the Android documentation for onActivityResult: https://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent). It's there to help you differentiate between different activities.
For a working example, I'd suggest looking at the HelloDropbox example that comes with the SDK. Among other things, it reads a string from a file in Dropbox.
Here's the relevant code from HelloDropboxActivity.java:
try {
// ...
DbxFileSystem dbxFs = DbxFileSystem.forAccount(mDbxAcctMgr.getLinkedAccount());
// ...
String resultData;
DbxFile testFile = dbxFs.open(testPath);
try {
resultData = testFile.readString();
} finally {
testFile.close();
}
} catch (IOException e) {
// ...
}

Categories

Resources