11

I want my Android application to use Webview to display an html form. When the user presses the Submit button, it want the name/value pairs sent back to my program. How do I do this?

I have looked at other similar questions but not of the responses tell how, specifically, to do this.

Xarph
  • 1,429
  • 3
  • 17
  • 26

3 Answers3

1

Look into the use of Javascript interfaces within WebView. Please see this area of the Android Developers Guide. Basically, you should be able to communicate from the page to the device with the Javascript interface and let your WebView Activity know when the submit button is pressed and send its values over.

Anthony Atkinson
  • 3,101
  • 3
  • 20
  • 22
  • " and send its values over." This is the part that I can not figure out. How to collect those values and send them. – Xarph Jun 02 '12 at 05:10
1

I have found what I needed. If I set action='FORM" in the form html, then I can intercept the action with:

        public void onLoadResource (WebView view, String url){
        int index = url.indexOf("FORM?");
        if (index != -1){
            String d = URLDecoder.decode(url.substring(index+5));
        }
    }

The name/value pairs are in String d.

Xarph
  • 1,429
  • 3
  • 17
  • 26
0

If you want to save Name/Value pairs and are willing to use jQuery then it's quite simple. Assuming you put jQuery in your assets folder you can read it into a file from:

getResources().getAssets()

In the WebViewClient that you set (assuming you overrode the client) you can do:

view.loadUrl("javascript:" + escapedJqueryStringHere);

Then, make sure you have a JavascriptInterface configured for your webview with a method, for example, called 'ReturnJSONFromForm(String json)' configured for "MyJInterface" then load the form into the page and then try this:

webview.loadUrl("javascript:MyJInterface.ReturnJSONFromForm($(\"form\").serialize());");

Now in your interface, just create a JSONObject from the resultant string and there you go! Name/Value pairs from your form.

Serialize won't capture disabled fields or submit buttons.. if you need that, then a more complex javascript solution exists but it's far more difficult.

d0nut
  • 2,835
  • 1
  • 18
  • 23