Struggling to use Cordova barcodescanner plugin - eclipse

I'm trying to create an application with Cordova (developing in eclipse, using JBoss Hybrid Mobile Tools + CordovaSim).
I have inspired the code snippet that's giving me problems on this example.
The error I get is:
!JavaScript ERROR: TypeError: 'undefined' is not an object (evaluating 'cordova.plugins.barcodeScanner') on line 6 for http://localhost:54726/js/QRScan.js
QRScan.js only contains the following code (so basically as in the example):
var scanBut = document.getElementById('QRScanButton');
scanBut.onclick = quickScan();
function quickScan(){
cordova.plugins.barcodeScanner.scan(
function (result) {
var s = "Result: " + result.text + "<br/>" +
"Format: " + result.format + "<br/>" +
"Cancelled: " + result.cancelled;
resultDiv.innerHTML = s;
},
function (error) {
alert("Scanning failed: " + error);
}
);
}
And I made sure my index.html contains the following line at the appropriate spot:
<script type="text/javascript" src="cordova.js"></script>
Finally my xml file should be configured correctly, I imported the correct plugin, the file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0"
id="csam.test" version="1.0.0">
<name>csam test</name>
<description>
A sample Apache Cordova application that responds to the
deviceready
event.
</description>
<author href="http://www.eclipse.org/thym" email="thym-dev#eclipse.org">
Eclipse.org -
Thym
</author>
<content src="index.html" />
<access origin="*" />
<preference name="fullscreen" value="true" />
<preference name="webviewbounce" value="true" />
<feature name="App">
<param name="android-package" value="org.apache.cordova.App" />
</feature>
<feature name="BarcodeScanner">
<param name="android-package" value="com.phonegap.plugins.barcodescanner.BarcodeScanner" />
<param name="ios-package" value="CDVBarcodeScanner" />
<param name="wp-package" value="BarcodeScanner" />
<param name="id" value="cordova-plugin-barcodescanner" />
</feature>
<engine name="android" version="4.0.1" />
</widget>

Plugins must wait for the deviceready event for use. Here is the piece of code from the demo which waits for deviceready added back in.
document.addEventListener("deviceready", init, false);
function init() {
document.querySelector("#startScan").addEventListener("touchend", startScan, false);
var scanBut = document.getElementById('QRScanButton');
scanBut.onclick = quickScan();
}

Related

Ionic v2 Download and display Image

I am trying to develop an application where I have to download and display an image from a website. THis is the code snippet which I have used:-
LoadImage(){
const transfer = new Transfer();
var url = "http://demo.observerjobs.lk/storage/public/uploads/vacancies/"+this.hash+"/"+this.attachment;
var uri = encodeURI(url);
var filepath = cordova.file.cacheDirectory+ '/' + this.vacancy.attachment;//("/"+this.vacancy.attachment);
transfer.download(uri, filepath, true ).then((entry) => {
console.log('download complete: ' + entry );
this.image = "<ion-img src= '"+ entry.toURL() + "'/>";
console.log(this.image);
}).catch(error => {
console.log(JSON.stringify(error));
});
}
I create the img tag in the following format:-
"<ion-img src= 'file:///data/user/0/package_name/cache/suo-01-29-012588-12x3-kbd.jpg'/>"
However, I am unable to retrieve this file to be displayed. What Have I done wrong, and what can I do to remedy this?
Edit:- Here is the config.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="OBSCURED FOR IDENTITY" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>OBSCURED</name>
<description>An awesome Ionic/Cordova app.</description>
<author email="hi#ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
<content src="index.html"/>
<access origin="*"/>
<allow-intent href="http://*/*"/>
<allow-intent href="https://*/*"/>
<allow-intent href="tel:*"/>
<allow-intent href="sms:*"/>
<allow-intent href="mailto:*"/>
<allow-intent href="geo:*"/>
<platform name="android">
<allow-intent href="market:*"/>
<icon src="resources\android\icon\drawable-ldpi-icon.png" density="ldpi"/>
<icon src="resources\android\icon\drawable-mdpi-icon.png" density="mdpi"/>
<icon src="resources\android\icon\drawable-hdpi-icon.png" density="hdpi"/>
<icon src="resources\android\icon\drawable-xhdpi-icon.png" density="xhdpi"/>
<icon src="resources\android\icon\drawable-xxhdpi-icon.png" density="xxhdpi"/>
<icon src="resources\android\icon\drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
<splash src="resources\android\splash\drawable-land-ldpi-screen.png" density="land-ldpi"/>
<splash src="resources\android\splash\drawable-land-mdpi-screen.png" density="land-mdpi"/>
<splash src="resources\android\splash\drawable-land-hdpi-screen.png" density="land-hdpi"/>
<splash src="resources\android\splash\drawable-port-ldpi-screen.png" density="port-ldpi"/>
<splash src="resources\android\splash\drawable-port-mdpi-screen.png" density="port-mdpi"/>
<splash src="resources\android\splash\drawable-port-hdpi-screen.png" density="port-hdpi"/>
</platform>
<platform name="ios">
<allow-intent href="itms:*"/>
<allow-intent href="itms-apps:*"/>
</platform>
<platform name="windows">
<preference name="windows-target-version" value="10.0"/>
</platform>
<preference name="webviewbounce" value="false"/>
<preference name="UIWebViewBounce" value="false"/>
<preference name="DisallowOverscroll" value="true"/>
<preference name="android-minSdkVersion" value="16"/>
<preference name="BackupWebStorage" value="none"/>
<preference name="SplashMaintainAspectRatio" value="true"/>
<preference name="FadeSplashScreenDuration" value="300"/>
<preference name="SplashScreen" value="screen"/>
<preference name="SplashScreenDelay" value="3000"/>
<feature name="StatusBar">
<param name="ios-package" onload="true" value="CDVStatusBar"/>
</feature>
<plugin name="ionic-plugin-keyboard" spec="~2.2.1"/>
<plugin name="cordova-plugin-whitelist" spec="1.3.1"/>
<plugin name="cordova-plugin-console" spec="1.0.5"/>
<plugin name="cordova-plugin-statusbar" spec="2.2.1"/>
<plugin name="cordova-plugin-device" spec="1.1.4"/>
<plugin name="cordova-plugin-splashscreen" spec="~4.0.1"/>
<icon src="resources\android\icon\drawable-xhdpi-icon.png"/>
<allow-navigation href="http://192.168.1.3:8100"/>
<allow-navigation href="http://192.168.1.3:8101"/>
<allow-navigation href="http://192.168.1.2:8100"/>
<allow-navigation href="http://192.168.8.105:8100"/>
</widget>
Here is the http file of the relevant page:-
<!--
Generated template for the Vacancy page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>Vacancy</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list no-lines *ngIf="vacancy">
<ion-item >Contract Type : {{vacancy.value}}</ion-item>
<ion-item >Company : {{item.company_name}}</ion-item>
<ion-item >Deadline : {{ deadlinetime }}</ion-item>
<ion-item >Job ID : #JD{{ item.id }}</ion-item>
</ion-list>
<h2 *ngIf="vacancy" orientation="center">{{item.job_title}}</h2>
<div *ngIf="image" [innerHtml]="image"></div>
</ion-content>
I would try:
Component:
imageSrc:string//class variable
LoadImage(){
const transfer = new Transfer();
var url = "http://demo.observerjobs.lk/storage/public/uploads/vacancies/"+this.hash+"/"+this.attachment;
var uri = encodeURI(url);
var filepath = cordova.file.cacheDirectory+ '/' + this.vacancy.attachment;//("/"+this.vacancy.attachment);
transfer.download(uri, filepath, true ).then((entry) => {
console.log('download complete: ' + entry );
this.imageSrc = entry.toUrl();
console.log(this.imageSrc);
}).catch(error => {
console.log(JSON.stringify(error));
});
}
HTML:
<img *ngIf="imageSrc" [src]="imageSrc"></img>

FacebookConnect plugin with phonegap adobe build not working

I have a Phonegap projct which is being built with adobe build.
I want to integrate FacebookConnect as per this git / tutorial page : https://github.com/phonegap-build/FacebookConnect
This is my adobe build config.xml :
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns= "http://www.w3.org/ns/widgets"
xmlns:gap= "http://phonegap.com/ns/1.0"
id= "com.TomBers.foodidapp"
version = "0.0.1">
<cordova>
<preference name="KeyboardDisplayRequiresUserAction" value="true" />
<preference name="SuppressesIncrementalRendering" value="false" />
<preference name="UIWebViewBounce" value="true" />
<preference name="TopActivityIndicator" value="gray" />
<preference name="EnableLocation" value="false" />
<preference name="EnableViewportScale" value="false" />
<preference name="AutoHideSplashScreen" value="true" />
<preference name="ShowSplashScreenSpinner" value="true" />
<preference name="MediaPlaybackRequiresUserAction" value="false" />
<preference name="AllowInlineMediaPlayback" value="false" />
<preference name="BackupWebStorage" value="cloud" />
<preference name="orientation" value="portrait" />
<preference name="phonegap-version" value="2.5.0" />
<content src="index.html" />
<plugins>
<plugin name="Device" value="CDVDevice" />
<plugin name="Logger" value="CDVLogger" />
<plugin name="Compass" value="CDVLocation" />
<plugin name="Accelerometer" value="CDVAccelerometer" />
<plugin name="Camera" value="CDVCamera" />
<plugin name="NetworkStatus" value="CDVConnection" />
<plugin name="Contacts" value="CDVContacts" />
<plugin name="Debug Console" value="CDVDebugConsole" />
<plugin name="Echo" value="CDVEcho" />
<plugin name="File" value="CDVFile" />
<plugin name="FileTransfer" value="CDVFileTransfer" />
<plugin name="Geolocation" value="CDVLocation" />
<plugin name="Notification" value="CDVNotification" />
<plugin name="Media" value="CDVSound" />
<plugin name="Capture" value="CDVCapture" />
<plugin name="SplashScreen" value="CDVSplashScreen" />
<plugin name="Battery" value="CDVBattery" />
<plugin name="Globalization" value="CDVGlobalization" />
<plugin name="InAppBrowser" value="CDVInAppBrowser" />
<plugin name="com.phonegap.facebook.Connect" value="com.phonegap.facebook.ConnectPlugin" />
<gap:plugin name="FacebookConnect">
<param name="APP_ID" value="133914256793487" />
</gap:plugin>
</plugins>
<access origin="*" />
</cordova>
</widget>
I then added the various javascript scraps and buttons shown in the Simple example : https://github.com/phonegap-build/FacebookConnect/tree/master/example/Simple including :
document.addEventListener('deviceready', function() {
try {
alert('Device is ready! Make sure you set your app_id below this alert.');
FB.init({ appId: "133914256793487", nativeInterface: CDV.FB, useCachedDialogs: false });
document.getElementById('data').innerHTML = "";
} catch (e) {
alert(e);
}
}, false);
With my updated appid. When my app loads - i get the alert saying device is ready!
Then I get 2 more alerts, one saying : plugin fail on init.
Then one saying : plugin fail on auth.status.
I have added my android debug keystore hash to the app on facebook + my developer settings.
I am not sure how to debug from here.
Cheers,
Andy
I would suggest you use the inappbrowser plugin to do this instead... example shown below.
Fill in the xxx below with your relevant info
var my_client_id = "xxxxxx", // YOUR APP ID
my_secret = "xxxxxxxxx", // YOUR APP SECRET
my_redirect_uri = "https://www.facebook.com/connect/login_success.html", // LEAVE THIS
my_type ="user_agent", my_display = "touch"; // LEAVE THIS
var facebook_token = "fbToken"; // OUR TOKEN KEEPER
var ref; //IN APP BROWSER REFERENCE
// FACEBOOK
var Facebook = {
init:function(){
// Begin Authorization
var authorize_url = "https://www.facebook.com/dialog/oauth?";
authorize_url += "client_id=" + my_client_id;
authorize_url += "&redirect_uri=" + my_redirect_uri;
authorize_url += "&display=" + my_display;
authorize_url += "&scope=publish_stream";
//CALL IN APP BROWSER WITH THE LINK
ref = window.open(authorize_url, '_blank', 'location=no');
ref.addEventListener('loadstart', function(event){
Facebook.facebookLocChanged(event.url);
});
},
facebookLocChanged:function(loc){
if (loc.indexOf("code=") >= 1 ) {
//CLOSE INAPPBROWSER AND NAVIGATE TO INDEX
ref.close();
//THIS IS MEANT TO BE DONE ON SERVER SIDE TO PROTECT CLIENT SECRET
var codeUrl = 'https://graph.facebook.com/oauth/access_token?client_id='+my_client_id+'&client_secret='+my_secret+'&redirect_uri='+my_redirect_uri+'&code='+loc.split("=")[1];
console.log('CODE_URL::' + codeUrl);
$.ajax({
url: codeUrl,
data: {},
type: 'POST',
async: false,
cache: false,
success: function(data, status){
//WE STORE THE TOKEN HERE
localStorage.setItem(facebook_token, data.split('=')[1].split('&')[0]);
},
error: function(){
alert("Unknown error Occured");
}
});
}
}
I would add more functions for logout and posting to a wall etc.
You can find documenatation on the inappbrowser here
After hours and hours of trying I got this to work.
Here's what's wrong with the proposed xml:
Tag cordova is wrong, remove it.
Tag gap:plugin does NOT go inside the plugins tag.
Tag plugin name="com.phonegap.facebook.Connect" is unnecessary and probably wrong.
Then I suggest inspecting the .apk file produced by phonegap build. If things are working as they should the files cdv-plugin-fb-connect.js and facebook-js-sdk.js should be present in assets/www.
By the way those files must not be present in the supplied src.

Orchard cms adding data-mediapicker-uploadpath to a custom type

I have created a custom type in orchard cms, that has a two column lay out
It has 2 header text fileds and 2 content HTML flavour fileds
Heres the migration :
public class MigrationTwoColumnPageType : DataMigrationImpl
{
public int Create()
{
// Define the project type
ContentDefinitionManager.AlterTypeDefinition("TwoColumnPage", cfg => cfg
.WithSetting("Stereotype", "Content")
.CommomPart()
.AutoroutePart()
.WithPart("TitlePart")
.WithPart("MenuPart")
.WithPart("TagsPart")
.WithPart("PublishLaterPart")
.WithPart("TwoColumnPage")
.Creatable()
.Draftable());
return 1;
}
public int UpdateFrom1()
{
// Define project part - having a part with the same name will create fields in the project type
ContentDefinitionManager.AlterPartDefinition("TwoColumnPage", builder => builder
.TextField("Column1Title", Flavour.Large)
.TextField("Column1Text", Flavour.Html)
.TextField("Column2Title", Flavour.Large)
.TextField("Column2Text", Flavour.Html)
.Attachable());
return 2;
}
}
NOTE: TextField is a custom extension method to make things less verbose
When I try and use the media picker to up load an image into one of these content fields I get a folder not found error, - I have traced this back to the media path on the Request querystring not being set
// media directory to save uploaded files into
var mediaPath = Request["uploadpath"];
in ../../Orchard.MediaPicker/Views/admin/Tab_Url.cshtml
Is there some way to set this using filed settings ?
Seems to work fine for any pages I create, but custom types .... how do I set this value ?
UPDATE
Heres the xml meta data for a page...
<!--Exported from Orchard-->
<Orchard>
<Recipe>
<Name>Generated by Orchard.ImportExport</Name>
<Author>admin</Author>
</Recipe>
<Metadata>
<Types>
<Page ContentTypeSettings.Creatable="True" ContentTypeSettings.Draftable="True" TypeIndexing.Included="true" DisplayName="Page">
<NavigationPart />
<CommonPart DateEditorSettings.ShowDateEditor="true" />
<PublishLaterPart />
<TitlePart />
<AutoroutePart AutorouteSettings.AllowCustomPattern="true" AutorouteSettings.AutomaticAdjustmentOnEdit="false" AutorouteSettings.PatternDefinitions="[{Name:'Title', Pattern: '{Content.Slug}', Description: 'my-page'}]" AutorouteSettings.DefaultPatternIndex="0" />
<BodyPart />
<TagsPart />
<LocalizationPart />
</Page>
</Types>
<Parts>
<NavigationPart ContentPartSettings.Attachable="True" />
<CommonPart ContentPartSettings.Attachable="True" />
<PublishLaterPart ContentPartSettings.Attachable="True" />
<TitlePart ContentPartSettings.Attachable="True" />
<AutoroutePart ContentPartSettings.Attachable="True" />
<BodyPart ContentPartSettings.Attachable="True" BodyPartSettings.FlavorDefault="html" />
<TagsPart ContentPartSettings.Attachable="True" />
<LocalizationPart />
</Parts>
</Metadata>
</Orchard>
Here's the XML meta for my custom type, using TestFiledSetting instead of BodyPartSetting
<!--Exported from Orchard-->
<Orchard>
<Recipe>
<Name>Generated by Orchard.ImportExport</Name>
<Author>admin</Author>
</Recipe>
<Metadata>
<Types>
<TwoColumnPage Stereotype="Content" OwnerEditorSettings.ShowOwnerEditor="false" ContentTypeSettings.Creatable="True" ContentTypeSettings.Draftable="True" DisplayName="Two Column Page">
<CommonPart />
<AutoroutePart AutorouteSettings.PatternDefinitions="[{Name:'/Title', Pattern: '/{Content.Slug}', Description: 'my-page'}]" />
<TitlePart />
<MenuPart />
<TagsPart />
<PublishLaterPart />
<TwoColumnPage />
</TwoColumnPage>
</Types>
<Parts>
<CommonPart ContentPartSettings.Attachable="True" />
<AutoroutePart ContentPartSettings.Attachable="True" />
<TitlePart ContentPartSettings.Attachable="True" />
<MenuPart ContentPartSettings.Attachable="True" />
<TagsPart ContentPartSettings.Attachable="True" />
<PublishLaterPart ContentPartSettings.Attachable="True" />
<TwoColumnPage ContentPartSettings.Attachable="True">
<Column1Title.TextField TextFieldSettings.Required="True" TextFieldSettings.Flavor="Large" TextFieldSettings.Hint="" />
<Column1Text.TextField TextFieldSettings.Required="True" TextFieldSettings.Flavor="Html" TextFieldSettings.Hint="" />
<Column2Title.TextField TextFieldSettings.Required="True" TextFieldSettings.Flavor="Large" TextFieldSettings.Hint="" />
<Column2Text.TextField TextFieldSettings.Required="True" TextFieldSettings.Flavor="Html" TextFieldSettings.Hint="" />
</TwoColumnPage>
</Parts>
</Metadata>
</Orchard>
No mention of data-mediapicker-uploadpath in either. I'm still lost!

How to recognize redirect and submit in struts action

My website use struts and tiles.
I use this link to link to register form:
<a href='<s:url action="register" namespace="/vtv" />' >Register</a>
here is the register.jsp:
<s:form namespace="/vtv" action="register">
<s:textfield label="Username" name="username" />
<s:textfield label="Password" name="password" />
</s:form>
In action, i insert the user :
public String execute() {
String retVal = ERROR;
try {
MemberDAO.InsertUser(mo);
retVal = SUCCESS;
}
} catch (Exception e) {
retVal = ERROR;
}
return retVal;
}
in tiles file, i define:
<definition name="vtv.register" extends="basic">
<put-attribute name="content" value="/modules/register/register.jsp" />
</definition>
and in struts file:
<package name="Register" namespace="/vtv" extends="struts-default">
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="register" class="vtv.action.RegisterAction">
<result name="success" type="tiles">vtv.register</result>
<result name="error" type="tiles">vtv.error</result>
</action>
</package>
My problem is how can i redirect to register page using link
<a href='<s:url action="register" namespace="/vtv" />' >Register</a>
without doing the execute in action ? How can i know if this is redirect or submit ?
In your <s:url> tag you can specify a specific method you want to invoke in your RegisterAction:
<s:url action="register" method="yourRedirectMethodName" namespace="/vtv" />
And then in your action define:
public String yourRedirectMethodName() {
// Redirect logic
return SUCCESS;
}
That way form submits will invoke execute() whereas the above link will invoke yourRedirectMethodName().

I get an error when using redirectAction with struts2 and portlets inside jboss portal

I have the following struts.xml:
<struts>
<package name="default" namespace="/view" extends="struts-portlet-default">
<action name="index" class="com.gigi.LoginAction">
<result type="redirectAction">
<param name="actionName">showAlerts</param>
<param name="namespace">/view</param>
<param name="portletMode">view</param>
</result>
<result name="error">/includes/error.jsp</result>
</action>
<action name="showAlerts" class="com.gigi.AlertsAction">
<result>/jsp/view/Alerts.jsp</result>
</action>
</package>
<package name="edit" namespace="/edit" extends="struts-portlet-default">
<action name="index" class="com.gigi.UpdateNameAction">
<result type="redirectAction">
<param name="actionName">index</param>
<param name="portletMode">view</param>
</result>
<result name="input">/jsp/edit/index.jsp</result>
</action>
</package>
</struts>
and LoginAction has the following execute method:
public String execute() throws Exception {
boolean loggedIn = checkLogin();
System.out.println("LoggedIn = " + loggedIn);
if (loggedIn) {
return SUCCESS;
}
return ERROR;
}
I am trying a redirect from LoginAction to AlertsAction. Every time I open the portlet in jboss portal 2.7.1, I get the following error:
The requested resource (/portlet/view/showAlerts) is not available
Can anyone tell me what I am doing wrong?
I tried writing the redirect in different ways, but the result is the same...
Thanks.
Where exactly is Alerts.jsp? Is it in /jsp or /WEB-INF/jsp? Can you log something out of the execute() method of AlertsAction?