What is the best way to structure a JSON data string for transmission from a WebView to JavaScript?

Seeking a solution for passing multiple values from an Android WebView to JavaScript. The challenge is that the string received in JS appears completely raw with control characters.

The specific issue arises when sending the following string from Java:

final String chartData = "{ \"data\": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }";

Instead of receiving the properly parsed string in JavaScript, the raw string is returned:

"{ \"data\": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }"

The desired output should be the java-parsed string:

{ "data": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }

Currently not handling any JSON, so the focus is on receiving the string correctly. Below is the code implemented so far:

WebViewActivity.java

webView = (WebView) findViewById(R.id.webView1);

    webView.getSettings().setJavaScriptEnabled(true);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);
    webSettings.setAllowFileAccessFromFileURLs(true);

    final String chartData = "{ \"data\": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }";

    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient(){
        public void onPageFinished(WebView view, String url){
            webView.loadUrl("javascript:showAlert('message from android')");
            webView.loadUrl("javascript:createChart('"+chartData+"')");
        }
    });

    webView.loadUrl("file:///android_asset/report.html");

report.html

<div id="debugContainer">
    debug
</div>

script.js

function createChart(lineChartData){
document.getElementById('debugContainer').innerHTML = JSON.stringify(lineChartData, null, 4);}

Answer №1

The data you get is in JSON format, which can be converted to a standard object by using JSON.parse(). When messages are sent via HTTP, they are always in string format. You must either work with the string directly or parse it as JSON.

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

Angular 1: Handling Multiple Conditions and Exclusions Based on Other Conditions

I have currently added an additional span to accommodate one condition. <div ng-repeat="(key, resultLinks) in resultGroup.resultLinks"> <div ng-if="key < 4 || viewMore" ng-repeat="(subKey, linksWrap) in resultLinks.linksWrap"> & ...

In the sequence of events, does the constructor method or the onDraw() method get

After referencing a question on Stack Overflow, I realized it did not provide the answers I was looking for. The issue I am facing involves global variable declarations set to NULL initially. In the constructor, I invoke a function named "newGame()" to in ...

Assign the value of "td" to the variable "val"

I am trying to set the value of my td element from my JavaScript JSON, but for some reason it doesn't seem to be working when I inspect the element. The HTML is functioning fine, it's just the value that isn't updating. I've tried chang ...

Executing a RESTful API request with Mocha in a Node.js environment

I've been attempting to make a REST call using Mocha. I tried using the "request" framework to log in at auth0. The REST call is correct; I tested the same data in Postman and received the correct response. However, when trying to implement the call ...

Collection of items consists of identical objects repeated multiple times

Multiple objects are being created and then pushed into the array objArr: var objArr = []; var obj = {}; var height = [9,8,7,3,6,5,2,4]; for (var i = 0; i < 8; i++) { debugger; var mountainH = height[i]; obj.h = mountainH; obj.index = i; o ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

Prepend a fixed header to the filter

Imagine this (simplified) JSON data: [ { "type": "foo", "name": "test_1" }, { "type": "bar", "name": "test_2" }, { & ...

Unable to change the background color of h1 tag in a ReactJS project

import React from 'react' export default function Home(){ return<div> <h1 className="bg-dark text-white p-3">Home Page</h1> </div> } I am attempting to modify the background color of the h1 tag in my Reac ...

Discover Vue3's efficient event handling feature that allows you to easily listen to events from dynamically generated child components

I am dynamically creating a Vue component and need to listen to the event it emits. While I know that you can use @eventName in the markup, my component is being created using createApp. const div = document.createElement('div'); this.$refs.logi ...

Having trouble with the Android XML graphical layout viewer? Unable to instantiate a custom view, with the class not found

I am facing an issue with my custom view that is attempting to draw an OvalShape from the android.graphics.drawable.shapes.OvalShape SDK. However, I am encountering an error during instantiation. The error message reads as follows: com.dan.test.ui.ArcBut ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

What is the best way to eliminate the "1 empty item" from a JSON object using JavaScript?

This is an example json object that has been modified to remove certain values. { name: { first: 'Robert', middle: '', last: 'Smith' }, age: 25, DOB: '-', hobbies: [ 'running', 'coding', & ...

Strange interaction observed when working with Record<string, unknown> compared to Record<string, any>

Recently, I came across this interesting function: function fn(param: Record<string, unknown>) { //... } x({ hello: "world" }); // Everything runs smoothly x(["hi"]); // Error -> Index signature for type 'string' i ...

Trouble retrieving data from an array in Angular locally

No matter how hard I tried, fetching data from MySQL, H2, and Derby databases seemed impossible. Following the instructions on w3schools website didn't yield any results. However, a light bulb went off in my head and I decided to give the Array Functi ...

Ways to show dropdown menu link exclusively on mobile browsers and not on desktop browsers

<li class="megamenu-content"> <div class="megamenu-content-wrapper clearfix"> <ul class="col-lg-3 col-sm-3 col-md-3 "> <li class="cat-header">DISPLAY MEMBERS</li> ...

Learn how to properly display the state array within a React component. Even though the array is present in the state, you may encounter issues where it

I am facing an issue while trying to display data from firestore in my React component. I have updated the global state array with the firestore data and it is being updated, but when I try to render that array, it shows as undefined. Initially, I attempt ...

Utilizing Bootstrap to arrange table cells in a shifted manner

I'm new to utilizing bootstrap in web development. I've been exploring various examples of bootstrap templates that include tables, and I noticed that when I resize my browser window, the table adjusts accordingly. Now, I'm curious to know ...

Error encountered with Charles Proxy while using the Andy emulator: SSL handshake failure due to unsupported curveId 29

I'm currently attempting to debug an Android app by monitoring the outbound and inbound HTTP traffic on the Andy emulator. I encountered this error related to SSL traffic: Failure: SSLHandshake: Unsupported curveId: 29 Previously, I did not encounter ...

Completely triggering a forced refresh on a single page application, disregarding cache, service workers, and all other

After experimenting with service workers on my Vue-built website, I made a critical error that has left Safari on my iPhone displaying only a blank page. To troubleshoot the issue, I connected my phone to my Mac and utilized Safari's inspector tool t ...