GridSurfer
GridSurfer

Reputation: 25

Auto fill in fields in WebView android

i want to fill in fields with this code but it gives me error

Account[] accounts = AccountManager.get(this).getAccounts();
    for (Account account : accounts) {
      // TODO: Check possibleEmail against an email regex or treat
      // account.name as an email address only for certain account.type values.


      String possibleEmail = account.name;



    myWebView.setWebViewClient(new HelloWebViewClient());

    setTitleColor(Color.GRAY); //the title bar color
    myWebView.loadUrl("http://m.gmail.com");
    myWebView.loadUrl("javascript: {document.getElementById('id_email').value ='"+possibleEmail+"'};");


} 

It gives me this error

05-02 20:28:24.191: E/Web Console(1402): Uncaught TypeError: Cannot set property 'value' of null at :1

Thanks for your help

Upvotes: 1

Views: 2880

Answers (1)

kwood
kwood

Reputation: 166

loadURL is asynchronous; in other words, calling loadUrl kicks off the HTTP request, but then returns immediately, before the document is downloaded and rendered. The error you're seeing is because you're trying to execute the javascript too early (before the document is downloaded, parsed, and rendered).

You'll need to use a WebViewClient, and wait for the page to finish loading before you execute your javascript. Try the onPageFinished callback, but be careful that you can sometimes get multiple callbacks because of iFrames and the like.

Hope that helps.

EDIT If you are targeting KITKAT and above then you also have to take care of which method to use based on android version. Follwoing code give a much better explanation:

 if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
 {
        webView.evaluateJavascript(yourScript, null);
 }
 else
 {
       webView.loadUrl(yourScript);

 }

Upvotes: 3

Related Questions