Get latitude and longitude data from SQLite and showcase it in a webview

I am currently facing an issue where I am unable to display the latitude and longitude values on a webview by accessing a Java method from JavaScript. The values are not getting displayed as expected.

Any help or guidance in resolving this issue would be greatly appreciated. Thank you!

Below is my WebviewActivity.java code snippet:

static final String TAG = "JavascriptDataDemo";

DataHelper myDB=new DataHelper(this);

/** This method retrieves data for JS */
@JavascriptInterface
public String getData() {
    // Inserting dummy latitude and longitude values into database
    myDB.insert(16.5048, 80.6338);
    myDB.insert(16.5024, 80.6432);
    myDB.insert(16.512, 80.6216);
    myDB.insert(16.5124, 80.6219);

    Cursor cursor = myDB.fetchAllCountries();
    double[] array = new double[cursor.getCount()];
    double[] array1 = new double[cursor.getCount()];
    int i = 0;
    if (cursor.moveToFirst()) {
        do {
            double data = cursor.getDouble(cursor.getColumnIndex("lat"));
            double data1 = cursor.getDouble(cursor.getColumnIndex("longt"));
            array[i] = data;
            array1[i] = data1;
            i++;
        } while (cursor.moveToNext());
    }

    Log.d(TAG, "getData() called");
    return convertToJson(array, array1).toString();
}

...

Above is just a snapshot of my index.html file that accesses the Android activity method to showcase the data:

<html>
<head>

<script> 
    var showData = function() {
        var data = android.getData();
        data = JSON.parse(data);
        window.alert("Hello! Data are: " + data + "; first = " + data[0]);
    }

 </script>

 </head>

 <body>


 <input type="button" value="Display data" onclick="showData()">

 <input type="button" value="Update data" onclick="setData();">

 <br/>

 <input type="button" value="Done" onclick="android.finish();">

 </body>
 </html>

Answer №1

Finally, I have found the solution!

DataHelper myDB = new DataHelper(this);

//double[] data = new double[] {42.6, 24, 17, 15.4};

/** This function sends our data to the JavaScript */
@JavascriptInterface
public String getData() {

    myDB.insert(16.5048, 80.6338);
    myDB.insert(16.5024,80.6432);
    myDB.insert(16.512,80.6216);
    myDB.insert(16.5124,80.6219);

    Cursor cursor = myDB.fetchAllCountries();
    double[] arr = new double[cursor.getCount()];
    int i = 0;

    if(cursor.moveToFirst()) {
        do {
            double data = cursor.getDouble(cursor.getColumnIndex("lat"));
            arr[i] = data;
            i++;
        } while (cursor.moveToNext());
    }

    Log.d(TAG, "getData() called");
    return arrayToJson(arr).toString();
}

@JavascriptInterface
public String getLong() {

    Cursor cursor1 = myDB.fetchAllCountries();
    double[] arr1 = new double[cursor1.getCount()];
    int i = 0;

    if(cursor1.moveToFirst()) {
        do {
            double data1=cursor1.getDouble(cursor1.getColumnIndex("longt"));
            arr1[i]=data1;
            i++;
        } while (cursor1.moveToNext());
    }

    Log.d(TAG, "getLong() called");
    return arrayToJson(arr1).toString();
}

private Activity activity;

public Context getActivity() {
    return activity;
}

public void setActivity(Activity app) {
    this.activity = app;
}

@JavascriptInterface
public void finish() {
    Log.d(TAG, "ArrayApplication.finish()");
    activity.finish();
}

/** Using a custom method instead of org.json.JSONArray due to limitations */
private String arrayToJson(double[] data) {
    StringBuffer sb = new StringBuffer();
    sb.append("[");
    for (int i = 0; i < data.length; i++) {
        double d = data[i];
        if (i > 0)
            sb.append(",");
        sb.append(d);
    }
    sb.append("]");
    return sb.toString();
}

Javascript code:

<html>
<head>

<script>
    var showData = function() {
        var data = android.getData();
        data = JSON.parse(data);
        var data1 = android.getLong();
        data1 = JSON.parse(data1);
        window.alert("Hello! Data are: " + data );
        window.alert("Hello! Data are: " + data1 );
    }
 </script>
   </head>

 <body>
    <input type="button" value="Display data" onclick="showData()">
    <input type="button" value="Done" onclick="android.finish();">
     </body>
      </html>

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 process for retrieving the date and time a location was added to Google Maps?

My goal is to extract the date and time a location pin was added in Google Maps. For example, if I search for McDonald's in a specific area, I want to retrieve the dates and times of all McDonald's locations in that area. Is there a method to acc ...

Ensuring the validity of input tags

I encountered an issue with an input tag that has a specific logic: https://codepen.io/ion-ciorba/pen/MWVWpmR In this case, I have a minimum value retrieved from the database (400), and while the logic is sound, the user experience with the component lea ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

What is the proper way to define the classpath for the compile() function in com.sun.tools.javac.Main?

When compiling Java files at runtime in my Struts projects using the com.sun.tools.javac.Main.compile() function, I encountered an issue with specific jars like axis2 being required for some files. Although I have the necessary jars, I'm unsure of how ...

Step-by-step guide on receiving notification action through WorkManager

Previously, I utilized an IntentService for handling notification actions before the introduction of WorkManager. When dealing with multiple actions, I would include them in the intent and retrieve them in my IntentService class as shown below. @Overrid ...

The keyboard doesn't appear when using autocompletetextview

I am currently working on an Android application that utilizes fragments and includes an AutoCompleteTextView. I want the keyboard to automatically appear when the fragment is displayed, but so far my attempts have been unsuccessful. Below is an excerpt o ...

Verification of product discount calculations using Selenium

I have a question that's been on my mind! Is there an option in Automation Testing to verify discount calculations when a product is added to the cart? Here's the scenario I'm referring to: Add a discounted product to the cart When proceed ...

Utilizing recursive techniques within a print method's implementation

One of the problems in my homework requires printing a string of asterisks using recursion within a void method. The number of asterisks printed is determined by 2 raised to the power of n (where n is the parameter of the method). For example: print(1) w ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Updating text in React Native does not reflect changes in context after a state change

I'm facing a challenging issue that I just can't seem to figure out. Here's the dilemma: <TouchableOpacity onPress={() => { if (myContext.value) { alert('true'); //changes myContext.value to false } els ...

Swap Text Inside String - JS

I have a challenge where I need to extract an ID from an HTML element and then replace part of the extracted word. For instance: HTML <input type="checkbox" id="facebookCheckbox"></div> JavaScript var x = document.getElementById("facebookCh ...

Encoding and decoding objects across varying JVM versions in Java

I am utilizing a remote system with Java 8 to communicate with another system (potentially running Java 17) through the transmission and reception of serialized Java DTOs over the network. Each Java class has its own serialVersionUID, but I am unsure if th ...

The construction was unsuccessful due to errors in the webpack process

I encountered a sudden error in my Next.js app. Is there any solution available to resolve this issue? ./pages/_app.tsx Error: [BABEL] C:\Projects\skribeNew\app-web\pages\_app.tsx: You provided us with a visitor for the node type T ...

javascript menu.asp

Is there a method to access a specific MenuItem element within an asp:Menu using JavaScript? I am trying to dynamically change the imageUrl path when a user hovers over the menu. <div align="center"> <asp:Menu ID="Menu1" runat="server"& ...

Discord bot struggling to reach every user in the server

After creating a discord bot with Discord.js, I was able to retrieve all the users from my server. However, lately I noticed that it is only returning 59 members out of the 300+ in total. I want to ensure that I am able to access all the users as before. ...

Chromedriver is failing to detect the GPS location due to the absence of the "Insecure origins treated as secure" setting

Utilizing chromedriver on the latest Chrome version - Version 107.0.5304.88 (Official Build) (64-bit) with Windows 10, I encountered an issue with GPS location detection on a certain website. The solution was to set the "Insecure origins treated as secure" ...

Dealing with AngularJS: Overcoming Lexer Errors When Passing Email Addresses for Regex Validation in Functions

Trying to pass an email address to an AngularJS function has been my recent challenge. Below is a snippet of the code I've been working on. <script> //For simplicity, descriptions for the module and service have been omitted this.sendEmail = f ...

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

Errors can arise in Discord.js when encountering "undefined" before the first array object in an embed

I am currently in the process of creating a Discord bot command that allows users to construct their own city. I am encountering an issue with a list command that is supposed to display all the roads and places built within the city. However, each list kee ...