简体   繁体   中英

Unable to call java methods from phonegap android?

I have created one sample app from create pdf file from html string using phonegap android.I have write the code for Creating PDF file in java.Code,

public class PdfGenerator
{
    private WebView mAppView;
    private DroidGap mGap;
    public PdfGenerator(DroidGap gap, WebView view)
    {
        mAppView = view;
        mGap = gap;
    }

    public void generatePDF()
    {
         File root = Environment.getExternalStorageDirectory();

         File gpxfile = new File(root, "test.pdf");
         System.out.println("Path ::::"+gpxfile);
         try{
         Document document = new Document(PageSize.LETTER);
          PdfWriter.getInstance(document, new FileOutputStream(gpxfile));
          document.open();
          document.addAuthor("Real Gagnon");
          document.addCreator("Real's HowTo");
          document.addSubject("Thanks for your support");
          document.addCreationDate();
          document.addTitle("Please read this");

          HTMLWorker htmlWorker = new HTMLWorker(document);
          String str = "<html><head></head><body>"+
            "<a href='http://www.rgagnon.com/howto.html'><b>Real's HowTo</b></a>" +
            "<h1>Show your support</h1>" +
            "<p>It DOES cost a lot to produce this site - in ISP storage and transfer fees, " +
            "in personal hardware and software costs to set up test environments, and above all," +
            "the huge amounts of time it takes for one person to design and write the actual content." +
            "<p>If you feel that effort has been useful to you, perhaps you will consider giving something back?" +
            "<p>Donate using PayPal® to real@rgagnon.com." +
            "<p>Contributions via PayPal are accepted in any amount " +
            "<P><br><table border='1'><tr><td>Java HowTo<tr>" +
            "<td bgcolor='red'>Javascript HowTo<tr><td>Powerbuilder HowTo</table>" +
            "</body></html>";
          htmlWorker.parse(new StringReader(str));
          document.close();
          System.out.println("Done");
          }
        catch (Exception e) {
          e.printStackTrace();
    }
    }
}

my mian class code is,

public class MainActivity extends DroidGap
{
    PdfGenerator pdf;
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);      
        super.init();   

        pdf = new PdfGenerator(this, appView);    
        appView.addJavascriptInterface(pdf, "PdfGenerator");

        super.loadUrl("file:///android_asset/www/test.html");
    }
}

Javascript code,

<html>
  <head>
    <meta name="viewport" content="width=320; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>

    <script>
   function pdf()
   {
   document.addEventListener("deviceReady", deviceReady, false);
   }

   function creatfile()
   {
    window.PdfGenerator.generatePDF();
   }



function deviceReady() {
    window.PdfGenerator.generatePDF();
}

    </script>

  </head>

  <body>
  <input type="submit" onclick="pdf()" value="IMEI" />
  </body>

whan i call generatePDF from javascript i got the following error,

Uncaught TypeError: Cannot call method 'generatePDF' of undefined 

Please help me.

Defining a function inside the DroidGap class (does not)|(will not)|(should not) expose that function to the webview javascript environment, nor will it expose member objects as DOM objects through Window.

What you want (as indicated by Raymond and Larta) is to write a PDF plugin.

Here is the documentation for writing a Cordova Plugin

In general, you need 1. Native Implementation this depends entirely on the platform your plugin is written for. In the case of android, you can find the native plugin

public class PDFWriter extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("generatePDF")) {
            // CALL YOUR GENERATE PDF CODE HERE
            return true;
        }
        return false;
    }
}
  1. JS Implementation yours might look something like PDFWriter.js: cordova.exec(successCB, failCB, "PDFWriter", "generatePDF", args);

successCB - is the success callback failCB - is the fail callback PDFWriter - is the native plugin implementation you are calling generatePDF - is the native plugin function you are calling args - an array of arguments to be passed to the native plugin function

Note that this is note a complete example, I've omitted the import statements in JAVA as well as the necessary hooks. Use the plugman npm module to autogenerate these for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM