Application for Android: Transferring JavaScript Variable to Native Java Variable

I'm developing an Android App and I have a piece of javascript code that is being loaded from "str8red.com" within a webview:

<script>var name = "bob", age = 30;</script>

There's a textbox in the app that I can set using:

textView.setText("Static Text")

I want to populate my textbox with the value of the name variable from the javascript. I've tried using

webview.loadUrl("javascript:Android.getIds(Ids);");
and evaluateJavascript without any luck. I've also searched through various guides on stack overflow and other websites but couldn't find a solution.

Below is the code snippet for loading the webview:

wv = (WebView) findViewById(R.id.wv);
//Enable JavaScript
wv.getSettings().setJavaScriptEnabled(true);
wv.setFocusable(true);
wv.setFocusableInTouchMode(true);
//Set Render Priority To High
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wv.getSettings().setDomStorageEnabled(true);
wv.getSettings().setDatabaseEnabled(true);
wv.getSettings().setAppCacheEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//Load Url
wv.loadUrl("https://str8red.com/");

Answer №1

Alright,

It appears that for Android versions starting from KitKat, the solution is quite straightforward:

    wv.evaluateJavascript("fromAndroid()", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String value) {
            textView.setText(value);

The key point I missed was attempting to directly access the javascript variables, whereas in reality, evaluateJavascript executes the specified javascript function, such as fromAndroid() in this case, and stores the returned data in the native app as a variable.

Provided below is my javascript snippet for reference:

<script>
function fromAndroid(){
  return "{% if user.is_authenticated %}true{% else %}false{% endif %} 1 0";
}
</script>

I would appreciate feedback from experts, but I do hope this explanation proves helpful to someone down the line.

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

AngularJS implemented to trigger a popup alert after a certain duration of time has elapsed since the

Can we create a popup alert that says "Error Contacting Server" when the http request does not receive any response? .controller('items_ctrl',['$scope','$http',function($scope,$http){ $scope.shop_id=localStorage.getItem(" ...

No results found from Android database query

Below is the code snippet used to query the android database. int lastID = -1; String selectQuery = "SELECT * FROM " + TABLE_MAIN + " WHERE " + KEY_ID + " > " + lastID; Log.i(LOG, selectQuery); SQLiteDatabase db = this.getReadableDatabase(); Cursor ...

What is the process for retrieving user data from Postgresql using axios.get when the data is already stored within the database?

Using auth0 for user sign up, my React app automatically retrieves user information upon logging in and sends a POST request with axios to the backend. The user ID is stored in userId and the user information is stored in currUser. However, upon logout and ...

Avoid nesting subscriptions in Rxjs

I am working with an array of objects and I need to extract an array of IDs from it. After that, I have to make calls to 2 different APIs before closing the modal window. Below is my code snippet: from(this.alerts) .pipe(map(alert => alert._id)) ...

Encountering an unexpected issue with $urlMatcherFactory during an AngularJS service unit test

I am seeking guidance on writing a proper unit test for a service using the jasmine framework and karma as the test runner. Below is the implementation in example-service.js: export default class ExampleService { constructor($resource, $http, $urlMatcher ...

Struggling with implementing a personalized zoom feature in React-Leaflet?

Looking to create a custom Zoom button using react-leaflet Below is the code I have been working on: import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { Map, TileLayer } from 're ...

Tips for fading an image as you scroll using CSS and JavaScript?

I have been dedicating my day to mastering the art of website development. However, I am facing a challenge that is proving to be quite difficult. I am looking to create a smooth transition effect where an image gradually blurs while scrolling down, and re ...

What are the common practices for UI bindings in JavaScript and AJAX applications?

Background Information Currently, I am in the process of developing a traditional web application with most forms operating through AJAX. I am facing challenges in connecting the user interface to the model. As of now, I have to explicitly: Specify the ...

Leverage the power of JavaScript by utilizing it as the view

Currently, in my React app, the view engine is set to hbs. There are a few hbs files in the Views folder. The following code snippet is in my app js file: // View engine app.engine( 'hbs', hbs({ extname: 'hbs', }) ) app.set ...

Utilizing proxies and leveraging the power of the Map collection in tandem

I have been exploring the Map collection and came across the [[MapData]] internal slot, which led me to utilize Reflect for trapping purposes. After some trial and error, I came up with the following code snippet: const map = new Map(); const proxiedMap ...

Utilizing JavaScript filtering logic in Angular Filter with AngularJS

This inquiry originates from this source Within the realm of Javascript, I have crafted a code to facilitate filtering, specifically showcasing elements from the array colors only if they correspond as values in cars. var colors = ["blue","red","pink","y ...

Tips for updating a React state while using the history API

In an effort to simplify and stay focused on the problem, I recently wrote a brief piece of code. Within this code, there is a component containing a Dialog that plays a role in a commercial process. This Dialog allows users to input information such as no ...

Launch an Android application directly from a web browser upon the webpage's loading

When a user visits www.example.com/myApp, I want my app to open automatically without any click required. I have attempted the following methods: window.onload = function () { window.location.replace("intent://something#Intent;scheme=myapp;packag ...

Angular UI modal on close event

Is there a way to trigger a function after a modal window is closed, regardless of whether it was closed by a button click or clicking on the backdrop? var dialog, options; options = { windowClass: "lightBox" templateUrl: "url to the template", con ...

A-Frame VR: Image missing from display on Chrome browser

UPDATE: I discovered that the issue was caused by running the HTML file from my local hard drive instead of a web server. Once I uploaded it to my web server and ran it from there, everything worked perfectly. A-Frame Version: 0.4.0, Chrome: 55.0.2883.87, ...

Executing a JavaScript function in Wicket 6 by utilizing the Link's "onclick()" method

In my code, I have a Java snippet and an HTML file: this.leakageModel = new PropertyListView<Leakage> ( "leakage", new ArrayList<Leakage> ()) { private static final long serialVersionUID = 1L; @Override protected void ...

Switch between light and dark modes with the MUI theme toggle in the header (AppBar)

I'm currently working on implementing a feature that allows users to switch between dark and light themes in my web app. The challenge I am facing is how to ensure that this theme change functionality is available throughout the entire app, not just i ...

Deeply nested .map function to update state value

The current state value const [settings, setSettings] = useContext(SettingsContext) Utilizing the .map method on the settings state {settings[categoryIndex]?.config?.map((item: ConfigItem, index: number) => ...

The View Model variable is being monitored multiple times

I have encountered a unique issue in my development process. Within my code, I am observing a MutableLiveData object of type String in the view Model and displaying the content as a toast message. Interestingly, when running this code on the AVD, the toast ...

Uncovering the Reasons Behind Multiple Accesses to a ReactJS Page

The code snippet provided shows an issue with accessing the /profile page. Upon accessing the page, there are 6 POST requests sent to the backend. However, after implementing the useEffect hook, while the page is still accessed 6 times, now only 2 POST req ...