How to recover data from an HTML form opened in a Webview?

Asked

Viewed 530 times

1

Hello! I have a responsive web application that I intend to open via android app through a Webview. Well, the only problem is that I would need to take some Submit data from just one application form to send to a bluetooth printer (whose code is based on java). Is there any way I can take this data that comes from the web application and move it to my java application? The simpler the better. Thanks in advance.

1 answer

2

You need to add an interface when declaring webView.

Example:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

Class code Webappinterface:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Now in your PHP, you should include onClick in your input.

Example:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

And Javascript will be responsible for "chat" with Android:

Example:

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

You can see more examples and details on android documentation

  • Thanks for the reply, very interesting but it was not clear to me how I can pass the form data through the onClick of the Ubmit button and retrieve them in Java. I would be most grateful if it were possible to share an example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.