Input information into the website, click the designated button, and analyze the retrieved data

I am looking to create a feature where users can input a vehicle number, retrieve the data, and display the vehicle details without using a webview. Currently, I have been successful in populating the data with the following code snippet:

webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://parivahan.gov.in/rcdlstatus/vahan/rcstatus.xhtml");
        webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                String reg1="KA51X";
                String reg2="2442";
                 if(isFirstLoad) {
                     webView.loadUrl("javascript: {" +
                             "document.getElementById('convVeh_Form:tf_reg_no1').value = '" + reg1 + "';" +
                             "document.getElementById('convVeh_Form:tf_reg_no2').value = '" + reg2 + "';" +
                             "var frms = document.getElementsByName('convVeh_Form');" +
                             "frms[0].submit(); };");

                     isFirstLoad = false;
                 }
            }
        });

The website providing the data for this app can be accessed here:

Currently, I am attempting to trigger the submit button with the following lines of code:

 "frms[0].submit(); };");

as well as,

"javascript:(function(){document.getElementById('convVeh_Form:j_idt21').click();})()"

However, these commands are not producing the desired results. How can I successfully click the button identified by the Id

convVeh_Form:j_idt21

Once the button is clicked, the response from the website will be received. Is there a way to extract and display this response text within the app's textview?

Answer №1

It seems like there may be a different issue you are facing, as convVeh_Form:j_idt21 appears to be just a label (as of now). Have you tried using convVeh_Form:j_idt27 instead? It's possible that there have been changes made.

If you want to style your injected JavaScript and selector, consider using

document.querySelector('[id="convVeh_Form:j_idt27"]').click()
.

To avoid issues with the : character in CSS selectors, this approach can be helpful.

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://parivahan.gov.in/rcdlstatus/vahan/rcstatus.xhtml");
webView.setWebViewClient(new WebViewClient() {
  public void onPageFinished(WebView view, String url) {
    String reg1 = "KA51X";
    String reg2 = "2442";
    if (isFirstLoad) {
      webView.loadUrl("javascript: {" +
        "document.getElementById('convVeh_Form:tf_reg_no1').value = '" + reg1 + "';" +
        "document.getElementById('convVeh_Form:tf_reg_no2').value = '" + reg2 + "';" +
        "document.querySelector('[id=\"convVeh_Form:j_idt27\"]').click(); };");

      isFirstLoad = false;
    }
  }
});

Alternatively, you could use button[type="submit"] as the selector if the button position remains constant. In this case, the specific Ids become less important. The other fields can be accessed using

document.querySelectorAll('input[type="text"]')[0]
and [1].

After submitting the form, the navigation will change, triggering an event that can be intercepted by subclassing the WebView. Check out this answer for guidance on handling such events.

private class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // ...
    }
}

You can use this event to detect the URL at the endpoint and then inject additional JavaScript to extract relevant information from the page. Feel free to reach out if you need further assistance.

Answer №2

After conducting some research, I discovered that the correct ID is convVeh_Form:j_idt26 instead of

"javascript:(function(){document.getElementById('convVeh_Form:j_idt21').click();})()"

To verify this information, please refer to my link

My key suggestion is to test your JavaScript code in a browser before integrating it into Android. Chrome's debug mode can be very helpful for this purpose.

If you are confident that the JS code functions correctly, then incorporate the code into Android in logical blocks. This approach can aid in debugging.

For instance, begin with these lines of JS code:

document.getElementById('convVeh_Form:tf_reg_no1').value = 'text' document.getElementById('convVeh_Form:tf_reg_no2').value = 'text'

If the desired outcome is achieved on the device, proceed by adding a click event after that.

document.getElementById('convVeh_Form:j_idt26').click()

This separation of JS logic can help pinpoint any issues with the code.

In regards to this inquiry:

Once the button is successfully clicked, the website will provide a response. How can this response text be extracted and displayed in the app's textview?

You need to implement a custom WebViewClient(), override onPageFinished, and only run JS code on the appropriate page.

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    if("https://parivahan.gov.in/rcdlstatus/vahan/rcstatus.xhtml".equals(url)) {
        // execute JS
    } else if("response_link".equals(url)) {
        // notify user or perform other actions
    }
}

Best of luck!

P.S. The provided JS code has been tested successfully in a browser from my end.

Answer №3

Is there a way to activate the button with the unique identifier convVeh_Form:j_idt21?

$('#convVeh_Form:j_idt21').click();

How can I extract and display the response text in an app's textview? If the response is a result of a form submission, utilizing an ajax call would simplify this process:

$.ajax({
   url: "http://your.url",
})
.done(function( data ) {
   $('#textview').text(data);
});

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

Is there a quicker method to access an object's ID?

Within my array of objects, the structure is as follows: var locations = [ [{id: 1, lat: 51.52376322544537, lng: 5.13785702262885, content: 'Title A'}], [{id: 2, lat: 51.52358632767757, lng: 5.137921395645208, content: 'Title B'}], [{i ...

Measuring Load Time Percentage in AngularJS Using $http Requests

I am currently utilizing Angular with my Rails application. I have a sample app and I am interested in displaying the response time required to load a response in Angular. For example, When loading a response of an array containing 100,000 elements, I w ...

Rectangles on canvas, each with identical dimensions, appear in varying sizes when positioned at different locations

In my canvas, I have created two rectangles using the rect element. Both rectangles are supposed to be 40 units wide and 20 units tall. The first rectangle starts at coordinates 0,0 for its top-left corner, while the second one begins at 60,40. Interesti ...

In order to avoid conflicts, please update the version code of your APK as there is currently one with version code 1. How can I go about changing the version?

My attempt to upload an apk file on Google Play has hit a roadblock. The apk file was created using Unity3D. Google Play is giving me an error message stating that I need to use a different version code for my APK because a version with code 1 already exis ...

Implementing Image Data in AngularJS: A Guide to Binding Images to IMG Tags

Allow me to explain the problem further. I am retrieving a user's profile picture by calling an API that returns image data, as shown in the screenshot below https://i.stack.imgur.com/t8Jtz.jpg https://i.stack.imgur.com/pxTUS.png The reason I canno ...

The computed variable in Vuex does not get updated when using the mapState function

I searched through several posts to find out what I am doing incorrectly. It seems like everything is set up correctly. MOTIVE Based on the value of COMPONENT A, I want to change hide/display content using v-show in DEPENDENT COMPONENT. ISSUE In the T ...

When inputting forms into the database, identifiers are used instead of names. Despite this, the user interface functions without any issues

In this demonstration, I am building a dynamic conditional drop-down list using Java script and Ajax. PHP: Add Data <html> <head> <title>Add Data</title> </head> <body> <?php //including the database connection ...

Should we consider it a poor practice for useEffect to be triggered by a user action in this manner?

The code below showcases my attempt to encapsulate all collapsible behavior within the Collapsible component. However, the collapse functionality is triggered by a button located outside of Collapsible. To address this issue, I modified Collapsible to resp ...

Oops, seems like there was a problem with parsing the

I have encountered an issue when trying to decode the value of a PHP array sent as JSON format. Here is how I created the array: $ads = $atts['ads']; if (sizeof($ads) > 0) { foreach($ads as $social_item) { $sdbr = $social_ ...

Discover the object in the initial array that is not included in the second array using AngularJS

Imagine having these two sets of objects: first set: [ { id: "123", title: "123", options: [] }, { id: "456", title: "456", options: [ { id: "0123", t ...

Saving picture as a blob within a file system

After experiencing slow performance and reaching the 1MB cursor limit, I made the decision to transition from storing images in a blob field in the database to the file system. However, I have a few concerns. Where is the best location to store these ima ...

Any number of elements in a single JSX code snippet

In my React code, I've created a function called optionTemplate to be used as a prop in a React component. const optionTemplate = (option) => { return ( <div className="flex align-items-center gap-2" style={ ...

"The boundary of suspense was updated before completing hydration." This error occurs when utilizing suspense and dynamic import within Next.js

I am currently working on lazy loading a list of data using suspense and dynamic import in Nextjs. However, I encountered the following error: Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch ...

Having trouble integrating a custom dialog with DirtyForms plugin

I have successfully implemented DirtyForms, a plugin that triggers a confirmation dialog when a user tries to navigate away from a page. The base functionality of the plugin is working as intended. Now, I am trying to integrate jQuery UI's Dialog for ...

Encountered a runtime error while trying to insert a list item <li> into a paragraph <p> element

Take a look at this code snippet: <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication18._Default" %> <!DOCTYPE html> <html> <body> <p id="someId"></p& ...

Guide to making a nested dropdown menu in React using an array of information

My data is structured in the following way: [ { group: 'team A', category: 'item1', task: 'task A' }, { group: 'team A', category: 'item1', task: 'task B' }, { ...

Encountering an Invariant Violation: React does not allow objects to be used as children

I can't figure out why my code isn't working. Every time I run it, I get the error message: Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of chil ...

Error encounter in JSP is nested within another JSP file, both of which utilize jQuery

Before proceeding, it is important to note that I am in the process of selecting a month using a datepicker and a specific meter (by its serial number). Once this information is selected, a query will be sent to a MySQL database to retrieve data for plotti ...

The web drive management system is currently undergoing a shutdown process

When attempting to run Protractor using some code I found online, the WebDriver manager shuts down right after entering protractor config.js. I have Google Chrome installed, but my default browser is Firefox. I am wondering if this could be related to the ...

Sending an Array from a ReactJS Frontend to a Django Backend using JavaScript and Python

I successfully created a website using Django and React JS. In my project, I am working on passing an array named pict from the frontend JavaScript to the backend Python in Django. let pict = []; pictureEl.addEventListener(`click`, function () { console ...