Tips for populating web view fields on Android using a combination of Java and JavaScript

Encountering an issue while attempting to populate fields in my android web view. Consistently receiving this error message

01-28 05:06:22.980: E/Web Console(2827): Uncaught TypeError: Cannot set property 'value' of null at null:1

Despite searching, I have not found a solution yet. How can I troubleshoot and fix this problem? Here is the code snippet:

public void onStart() {
        super.onStart();

        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());

        String url = "file:///android_asset/index.html";
        webView.loadUrl(url);

        webView.setWebViewClient(new WebViewClient(){

               public void onPageFinished(WebView view, String url) {
                   webView.loadUrl("javascript: {"
                            + "document.getElementById('AddSerialNum').value = '"
                            + ABC
                            + "';"
                            + "document.getElementById('ctl00_PageContent_lblName').value = '"
                            + ABC + "';};");

                }
            });
    }

This file contains the index.html content:

<!DOCTYPE html>
 <html>

 <body>

 <div style="BORDER-BOTTOM: #dfdfdf 3px solid; PADDING-BOTTOM: 1px; MARGIN-BOTTOM: 10px; HEIGHT: 25px;">
               ......          
                <div style="padding: 10px;">
                    <table width="100%">
                        <tbody><tr>
                            <td>
                                <div style="float: left;">
                                    <div>

                                    <form>Serial Number: <input type="text" name="AddSerialNum"></form><br><br>

                                        <span id="ctl00_PageContent_lblName" style="font-weight:bold;"></span>
                                    </div>......

Looking for options to fill the fields and retrieve data later using Java. Any suggestions would be appreciated.

Thank you in advance.

Answer №1

When using getElementById, you can retrieve a DOM Element by its unique id. In this case, the id AddSerialNum is not found, as indicated by the error message. You do have an input with the name="AddSerialNum", which appears to be what you are trying to access. To target it correctly, you will need to assign an id attribute to it or utilize

getElementsByName("AddSerialNum")[0]

UPDATE: As mentioned earlier, the correct syntax should be:

webView.loadUrl("javascript: {document.getElementsByName(\"AddSerialNum\")[0].value ='" + ABC + "';};");

The getElementsByName function returns an array of elements, so you need to specify the first element in the array using [0]

Answer №2

Here is a snippet of code for setting user email in a WebView:

    mWebView.setWebViewClient(new WebViewClient() {
            private void setUserEmail(WebView view) {
                String js = "javascript: {document.getElementsByName(\"recover-email\")[0].value ='" + mEmail + "';};";
                if (Build.VERSION.SDK_INT >= 19) {
                    view.evaluateJavascript(js, s -> {
                    });
                } else {
                    view.loadUrl(js);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                mLoadingProgressBar.setVisibility(View.GONE);
                setUserEmail(view);
            }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for calculating the total number of edges connecting red and white nodes within a graph?

I need assistance in counting the number of edges that connect a white node to a red node. The red nodes are specified in the new int[] array inside the main method. Below is the code provided for the assignment: import edu.princeton.cs.algs4.Graph; pub ...

The img-wrapper is failing to show the PNG image

I'm having an issue with my code where it displays jpg images but not png. How can I make the img-wrapper show png files as well? In my example, the first image in the array is a jpg while the second is a png. However, I only see the title of the imag ...

React Native does not support Laravel Echo's listenForWhisper functionality

I have successfully implemented private channels and messaging in my Laravel App using websockets:serve. Now, I am attempting to enable whisper functionality for the typing status but encountering some issues. When sending a whisper: Echo.private('c ...

What is the best way to retrieve a single value from an SQLite database in an Android

I'm having trouble running this code: AppsDbHelper dbHelper = new AppsDbHelper(mContext); SQLiteDatabase database = dbHelper.getReadableDatabase(); String query = "select launch from apps where name=com.google.android.apps.ma ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

Retrieving a JSON object that has been exported using Mongoose in Node.js

Recently diving into the world of Node.JS, I encountered a perplexing issue that has me stumped. In my upcoming_events.js file, I have an events object that I am exporting in the following manner: module.exports = function(passport, FacebookStrategy, con ...

Establish a restriction for an array within a Mongoose schema

When creating a mongoose Schema, I want to specify one of the fields as an Array. However, I need to set a limit on the number of items that can be added to this array by default. If we attempt to add a new item when the array is already filled to the limi ...

Trigger the animation with a button click by utilizing ng-class in Angular.js

How can I make an animation run more than once when a button is clicked? I've tried using ng-class but it's not working as expected. Any help would be appreciated. Thank you! <div ng-controller="MyCtrl"> <div class='contendor_port ...

What steps are needed to set up a Queue within a JBoss cluster?

My application serves as a middle ware, receiving requests from clients and processing them according to specific logic before sending the transformed requests to another service provider either as normal HTTP requests or Webservice soap requests. The appl ...

trouble with v-for in Vue.js causing data not to show on page

Whenever I use console.log(e.data), I am able to retrieve values, but when attempting to display them using v-for, the data does not show up. Can someone please explain why this issue is occurring? Below is the HTML code intended to display the values: & ...

Parsing JSON depending on field availability and another field's value

Is there a way to map JSON payloads to specific concrete types based on a hierarchy with four end concrete types, each having two abstract sub-types? To determine the sub-type, we check for the presence of either ".job" for JobCallback or ".notify" for No ...

What steps should I take to create an Image + Text combination within a button in an Android app?

I'm trying to create a phone number button with an icon that is clickable in my app. After looking at Google Maps' implementation, I found it to be good. How can I replicate this in my own app? I attempted using the Image Button view but it didn ...

Capture and set the new value of the Datetime picker in MUI upon user's acceptance click

import React from 'react' import { Stack, Typography } from '@mui/material' import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker' import { renderTimeViewClock } from '@mui/x-date-pickers/timeViewRenderers&ap ...

D3.json request falls flat

Is failure inevitable in this scenario? d3.json("https://api.kraken.com/0/public/Time", function(){ console.log(arguments); }); I'm encountering a familiar CORS hurdle XMLHttpRequest cannot load https://api.kraken.com/0/public/Time/. No ...

Storing values as JSON in Redis: A comprehensive guide

In my application, I have implemented Redis as the caching store. Below is the configuration setup for Redis: @Configuration @EnableCaching public class SpringRedisConfig { @Bean public JedisConnectionFactory connectionFactory() { JedisConnectionFacto ...

Is it possible to dynamically assign trigger and target divs to bPopup?

On our ColdFusion page, we have a dynamic list of paired divs created using a loop over a query. For example, each pair consists of internshipHandleX and internshipHiddenX: <div id="internshipHidden#internship.currentrow#" class="hidden pop-up"> We ...

Incorporate a collection of product titles along with their short forms in JavaScript/jQuery

Seeking guidance as a newcomer to JS. I have encountered the need for two different views in an application I am working on - one displaying full product names and the other showing only their abbreviations. Instead of hard-coding this information, I wish ...

Guide to automatically triggering overscrolling

Currently working on a kiosk webpage designed for an iPad. Discovered an app that enables fullscreen mode, but requires overscrolling at the bottom. Is there a method to automatically trigger this on my webpage? Attempted to achieve this using autoscroll ...

What are the steps to configure an option date for Yesterday, Today, and Tomorrow?

I have been working on setting options for dates like yesterday, today, and tomorrow. I have implemented the following code which is functioning properly, but it is not displaying yesterday's date. I want today's date to be selected and also disp ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...