PhoneGap Android copy to clipboard plugin implementation - java

I'm trying to use this plugin in my application. I've never written a plugin and this is my first time trying to use one in my Phonegap program. I had to try and change a whole bunch of stuff in the java file to get rid of the errors. When I click a button on my screen, I get an error "Uncaught ReferenceError: cordova is not defined at file:///android_asset/www/js/clipboardmanager.js:2". No idea what that means or how to change that. I'll try and paste everything so hopefully it's easier to find my error.
structure:
src
-->com.example.basket
-->MainActivity.java
-->com.saaticiouglu.phonegap.ClipboardManagerPlugin
-->ClipboardManagerPlugin.java
ClipboardManagerPlugin.java:
package com.saatcioglu.phonegap.ClipboardManagerPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.ClipboardManager;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.PluginResult;
#SuppressWarnings("deprecation")
public class ClipboardManagerPlugin extends CordovaPlugin {
private static final String actionCopy = "copy";
private static final String actionPaste = "paste";
private static final String errorParse = "Couldn't get the text to copy";
private static final String errorUnknown = "Unknown Error";
private ClipboardManager mClipboardManager;
#SuppressLint("NewApi") #Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
{
// If we do not have the clipboard
if(mClipboardManager == null) {
mClipboardManager = (ClipboardManager) cordova.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
}
// Copy
if (action.equals(actionCopy)) {
String arg = "";
try {
arg = (String) args.get(0);
mClipboardManager.setText(arg);
} catch (JSONException e) {
callbackContext.error( errorParse);
} catch (Exception e) {
callbackContext.error( errorUnknown);
}
callbackContext.success();
// Paste
} else if (action.equals(actionPaste)) {
String arg = (String) mClipboardManager.getText();
if (arg == null) {
arg = "";
}
PluginResult copy_ret = new PluginResult(PluginResult.Status.OK, arg);
callbackContext.sendPluginResult(copy_ret);
callbackContext.success();
} else {
callbackContext.error("invalid action");
return false;
}
return true;
}
}
I had to use the Surpress warnings because setText and getText were giving me errors...and they are still crossed out in my file. But no errors there now...
clipboardmanager.js:
window.clipboardManagerCopy = function(str, success, fail) {
cordova.exec(success, fail, "ClipboardManagerPlugin", "copy", [str]);
};
window.clipboardManagerPaste = function(success, fail) {
cordova.exec(success, fail, "ClipboardManagerPlugin", "copy", []);
};
I referenced to the JS file in my index.html:
$('button').on('click', function(){
window.clipboardManagerCopy(
"the text to copy",
function(r){alert("copy is successful")},
function(e){alert(e)}
);
});
I just want to get a simple alert to see that it works. Thanks for taking the time to help out. Please help me fix this!!!

Related

Exception: java.lang.NoClassDefFoundError: org.ehcache.CacheMangerBuilder

I'll preface this by saying "I have no idea what I'm doing" with java, let alone ehcache, but I'm trying to learn.
That said, I have this code I've written that ran fine until I added the ehcache stuff. I had been simply writing to and reading from files, which worked fine but slow, so I'm trying to speed things up by using cache instead.
When I run my program, I get the following error, and I don't understand what it's telling me is wrong:
Exception in thread "Connect thread - [6, 5]."
java.lang.NoClassDefFoundError: org.ehcache.CacheManagerBuilder
at com.ibm.tpf.internal.ZSTATEngine.doFilter(ZSTATEngine.java:24)
at com.ibm.tpf.etos.filter.FilterFramework.filterMessage(FilterFramework.java:229)
at com.ibm.tpf.etos.api.APIFramework.addMessage(APIFramework.java:304)
at com.ibm.tpf.etos.comm.ETOSConnection.addMessage(ETOSConnection.java:765)
at com.ibm.tpf.etos.comm.ETOSModel._connect(ETOSModel.java:528)
at com.ibm.tpf.etos.comm.ETOSModel$ConnectThread.run(ETOSModel.java:706)
Caused by: java.lang.NoClassDefFoundError:
org.ehcache.CacheMangerBuilder
at java.net.URLClassLoader.findClass(URLClassLoader.java:496)
at java.lang.ClassLoader.loadClass(ClassLoader.java:631)
at java.lang.ClassLoader.loadClass(ClassLoader.java:597)
... 6 more
I tried to mimic the cache code found on the ehcache 3.0 documentation page... but I must've done something horribly wrong. Anyone mind taking a look?
package com.ibm.tpf.internal;
import java.awt.Color;
import java.io.File;
import org.ehcache.*;
import org.ehcache.config.CacheConfigurationBuilder;
import com.ibm.tpf.etos.TPFFilter.*;
import com.ibm.tpf.etos.api.*;
import com.ibm.tpf.etos.filter.*;
public class ZSTATEngine implements ETOSFilterEngine {
FilterFramework fw = null;
String[] names = null;
public ZSTATEngine(FilterFramework filFW, String[] parms) {
super();
this.fw = filFW;
}
public MessageBlock doFilter(MessageBlock msgBlock) throws FilterRuntimeException {
File file = new File("{path omitted}\\FILTER.DAT");
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("csmpCache",CacheConfigurationBuilder.newCacheConfigurationBuilder().buildConfig(Long.class, String.class)).build(false);
cacheManager.init();
Cache<Long, String> csmpCache = cacheManager.getCache("csmpCache", Long.class, String.class);
if(msgBlock.getMsgID().equals("CSMP0097I")) {
csmpCache.put(1L, msgBlock.getMsg()); /* 1L is a key */
msgBlock.setSuppressed(TernarySwitch.ON);
}
else {
if(msgBlock.getFlag() == Constants.ETOS_ONE_MSG || msgBlock.getFlag() == Constants.ETOS_START_MSG) {
if(file.exists() && file.isFile()) {
String csmpValue = csmpCache.get(1L);
MessageBlock mbCSMP = new MessageBlock(csmpValue, Constants.ETOS_ONE_MSG);
mbCSMP.setForeground(Color.BLUE);
msgBlock.setForeground(Color.BLUE);
fw.addFilteredMessage(mbCSMP);
}
}
}
cacheManager.close();
return msgBlock; /* whatever gets returned is what the system prints */
}
private Color ColorStringInterpreter(String colorMsg) throws FilterRuntimeException {
if (colorMsg.toUpperCase().startsWith("TOS")) { /* if it starts with TOS, then we're using color names */
String[] colorParts = colorMsg.split("_",2);
String colorTxt = colorParts[1].toString().trim();
if (colorTxt.toUpperCase() != "NONE") {
Color finalColor = Colors.fromString(colorTxt);
return finalColor;
}
}
else {
String[] colorParts = colorMsg.split("_",3); /* otherwise we're using RGB values */
String sRed = colorParts[0].toString().trim();
String sGreen = colorParts[1].toString().trim();
String sBlue = colorParts[2].toString().trim();
int iRed = Integer.parseInt(sRed);
int iGreen = Integer.parseInt(sGreen);
int iBlue = Integer.parseInt(sBlue);
Color finalColor = new Color (iRed, iGreen, iBlue);
return finalColor;
}
return null;
}
public String getName() {
return null;
}
public void modifyState(Object[] newParams) throws FilterConfigurationException, FilterRuntimeException {
}
public boolean isActive() {
return false;
}
public void shutdown() {
}
}
Thank you for your time

try/catch not working in Java?

I am making an app for android in Qt. So in order to use the Google API I need to implement Java. So I have looked through the QtNotifier example and I am trying to implement the same as a starter.
This Java example comes from the QtNotifier example aswell so it should work the same but it doesn't. I have tried to debug it using the Qt debugger but the breakpoints do not seem to trigger So I added println statements to see at which line it goes wrong. But this is not enough so I am trying to print a stacktrace using a catch/try clause.
I have implemented it like this:
package org.qtproject.qt5.example;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import java.lang.Object;
import java.io.Writer;
import java.io.StringWriter;
import java.io.PrintWriter;
public class NotificationClient extends org.qtproject.qt5.android.bindings.QtActivity
{
private static NotificationManager m_notificationManager;
private static Notification.Builder m_builder;
private static NotificationClient m_instance;
public NotificationClient()
{
System.out.println("it works2222");
m_instance = this;
}
public static void notify(String s)
{
System.out.println(s);
try {
if (m_notificationManager == null) {
System.out.println("1111");
m_notificationManager = (NotificationManager)m_instance.getSystemService(Context.NOTIFICATION_SERVICE);
System.out.println("2222");
m_builder = new Notification.Builder(m_instance);
System.out.println("3333");
m_builder.setContentTitle("A message from Qt!");
System.out.println("4444");
}
System.out.println("5555");
m_builder.setContentText(s);
System.out.println("6666");
m_notificationManager.notify(1, m_builder.build());
System.out.println("7777");
} catch(Exception e) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
e.printStackTrace(pw);
String errorDetail = writer.toString();
}
}
}
The output is:
I/System.out( 4768): test string
I/System.out( 4768): 1111
It would seem that m_instance is still null because "System.out.println("it works2222");" does not get called. But the error does not get caught.
Is it because this is an error that is not an exception?
I have also tried running the QtNotifier app but the printstatement inside.
public NotificationClient()
{
System.out.println("it works2222");
m_instance = this;
}
But that is also not called in the QtNotifier app.
My question is: How can I trace this error?
In Java, there are both Errors and Exceptions. Normally, an Error is significant enough that your program should just crash and exit. However, for debugging purposes, if you want to catch both you should
catch (Throwable t)
{
t.printStackTrace();
}
to get information on both.

Exception thrown when trying to load Pentaho report through java program

This code was mostly taken from Pentaho's website on sample programs. The goal is to use their API to generate HTML output with a Pentaho report.
The report was created with Pentaho 3.5.0-RC2
The version of jars I am using are the following:
pentaho-reporting-engine-classic-core-3.5.0-RC2.jar
libloader-1.1.1.jar
libbase-1.1.1.jar
The exception I am getting is the following:
org.pentaho.reporting.libraries.resourceloader.ContentNotRecognizedException: None of the selected factories was able to handle the given data: ResourceKey{schema=org.pentaho.reporting.libraries.resourceloader.loader.URLResourceLoader, identifier=file:/C:/Users/elias.kopsiaftis/workspace_experimental/TestPentahoReport/bin/Test.prpt, factoryParameters={}, parent=null}
at org.pentaho.reporting.libraries.resourceloader.DefaultResourceManagerBackend.create(DefaultResourceManagerBackend.java:295)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:387)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:342)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.createDirectly(ResourceManager.java:205)
at ReportTester.getReportDefinition(ReportTester.java:74)
at ReportTester.getReport(ReportTester.java:25)
at ReportTester.main(ReportTester.java:84)
java.lang.NullPointerException
at ReportTester.getReport(ReportTester.java:26)
at ReportTester.main(ReportTester.java:84)
And finally, the code snippet!
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.io.*;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlReportUtil;
import org.pentaho.reporting.libraries.resourceloader.Resource;
import org.pentaho.reporting.libraries.base.util.StackableException;
import org.pentaho.reporting.libraries.resourceloader.ResourceException;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
public class ReportTester {
private String reportName = "FormCompleteUsagePerPartnerByMonth.prpt";
private String reportPath = "";
public void getReport() {
try {
final MasterReport report = getReportDefinition();
report.getParameterValues().put("partner", "");
report.getParameterValues().put("startingdate", "2015-03-01");
report.getParameterValues().put("endingdate", "2015-03-05");
HtmlReportUtil.createStreamHTML(report, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
private MasterReport getReportDefinition() {
try {
// Using the classloader, get the URL to the reportDefinition file
final ClassLoader classloader = this.getClass().getClassLoader();
final URL reportDefinitionURL = classloader.getResource(reportPath + reportName);
if(reportDefinitionURL == null) {
System.out.println("URL was null");
}
// Parse the report file
final ResourceManager resourceManager = new ResourceManager();
resourceManager.registerDefaults();
final Resource directly = resourceManager.createDirectly(reportDefinitionURL, MasterReport.class);
return (MasterReport) directly.getResource();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
ReportTester rt = new ReportTester();
rt.getReport();
}
}
Any advice on this would be much appreciated as I have been scratching my head on this all day. Thanks in advance!

phonegap android plugin using a native library

I'm trying to create a phonegap plugin for an android device, sadly my Java is terrible.
I have a simple helloworld project i'm working in to try and get this going.
I've created a plugin which loads fine and works ( just a simple return string example )
From this i then have tried to add my native library code.
public class Medida extends CordovaPlugin
{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
The error message i keep encountering is:
10-28 15:23:03.207: W/dalvikvm(11618): No implementation found for native Lorg/apache/cordova/plugin/Medida;.SFM_Init ([B)I
Now - I'm taking the libfinger.so file from a full JAVA android project and trying to wrap it into a phonegap plugin (why? Because i can code phonegap, but no java).
The files are all been placed in the correct locations
the libfinger.so file is in the libs/ folder
So my question is - what else do i need to add-in or do to get the JAVA plugin to work with the libfinger.so - so i can call all the clases etc..
Thanks for looking - spents days trying to find out, but there is not much info on calling loadlibrary for plugins which i understand.
John
Main java class
package org.apache.cordova.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class Medida extends CordovaPlugin{
static {
System.loadLibrary("finger");
}
public native static int SFM_Init(byte[] dev);
static final String LOG_TAG = "Medida.Java: ";
int fd = 0;
String retval = null;
int[] nQuality = {0};
int[] nBufferSize = {0};
private final String retSuccess = "OK";
public static final int REFRESH = 1;
public static final int ERROR = 0;
private Thread thread = null;
private int peripheral_fd = 1;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("dave")) {
String message = args.getString(0);
this.dave("Medida CALLING DAVE " + message, callbackContext);
return true;
}
else if (action.equals("scanfinger_getID")){
this.scanfinger_getID( args, callbackContext);
return true;
}
return false;
}
private void dave(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(" --- Medida FROM DAVE: " + message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
private void scanfinger_getID(JSONArray args, CallbackContext callbackContext) throws JSONException {
String message = args.getString(0);
JSONObject object = new JSONObject(message);
String id = object.getString("id");
String dev = "/dev/ttySAC3";
byte[] devName = dev.getBytes();
fd = SFM_Init(devName);
callbackContext.success("Got to scanfinger_getID: " + id);
}
}
Try to define the method as a class method (taken from here):
public class Medida extends CordovaPlugin {
static {
System.loadLibrary("finger");
}
public native int SFM_Init(byte[] dev);
}
EDIT
From the error it seems that there is no method called SFM_Init in the native library, try to list the exported methods and see the exact definition: How do I list the symbols in a .so file

Android - Java - No Activity Found to Handle Intent

I am trying to create an Android / Java plugin for the cross-platform program Phonegap / Cordova 3.2. I am following several tutorials but can't get the simplest plugin to work.
Currently I am working on the idea that my Java code is just wrong somewhere.
Could someone please review the following code and advise if there is something obviously wrong?
The error I keep getting is
Exception: No Activity found to handle Intent { act=android.intent.action.MEDIA_SCANNER_SCAN_FILE dat=file:///{"fullPath":"media\/test.mp3"} }
Here is my .java file
package org.media.scan;
import java.io.File;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import android.net.Uri;
public class Scan extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if ( action.equals("addRemove") ) {
String filePath = args.getString(0);
filePath = filePath.replaceAll("^file://", "");
if (filePath.equals("")) {
callbackContext.error("null path passed");
return false;
}
File file = new File(filePath);
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(file));
this.cordova.getActivity().startActivity( scanIntent );
callbackContext.success("good");
return true;
} else {
callbackContext.error("invalid action phrase");
}
return false;
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
}
I am calling my Java code with this .js code
var Scan = {
createEvent:function (fullPath, successCallback, errorCallback) {
cordova.exec(
successCallback, // success callback function
errorCallback, // error callback function
'Scan', // mapped to our native Java class
'addRemove', // with this action name
[
{
"fullPath":fullPath
}
]
);
}
}
module.exports = Scan;
It's a broadcast action not activity action, you should use the send broadcast method for this kind of action!
http://developer.android.com/reference/android/content/Intent.html#ACTION_MEDIA_SCANNER_SCAN_FILE
This is the wrong line in code " this.cordova.getActivity().startActivity( scanIntent );
"

Categories

Resources