Attempting to add an image in an Android WebView

Recently, I have been exploring the most straightforward method to insert an image into a webview using javascript. After crafting my own html and designing a function similar to the one below:

<script type="text/javascript">

function image(src) {
    var img = document.createElement("IMG");
    img.src = src;
    document.getElementById('image').appendChild(img);
}
</script>

I realized that simply using myview.loadurl(javascript:image('line1.png')); is not working as expected. Now, I am attempting to devise a solution for this issue. My initial thought was to condense this function into a single line of code that can be incorporated within loadurl(), however, this approach is triggering errors. I have come across suggestions of implementing addJavascriptInterface, but its complexity leaves me uncertain if it aligns with my requirements. So, what would be the most optimal path forward?

Answer №1

It's actually quite simple. Give this a try:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;

public class CustomActivity extends Activity {

    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        WebView view=(WebView)findViewById(R.id.webView1);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl("file:///android_asset/index.html");
        view.addJavascriptInterface(new JavaScriptBridge(), "Android");
    }

    final class JavaScriptBridge
    {
        public void ProcessJavaScript(final String scriptname, final String args)
            {             
                mHandler.post(new Runnable()
                    {
                        public void run()
                            {
                    String url="file:///android_asset/img.jpg";
                                webview.loadUrl("javascript:image(\""+url+"\")");
                            }
                    });
            }
    }
}

index.html:

<script type="text/javascript">
 function getimage()
 {
   Android.ProcessJavaScript("image",null); 
 }

function image(src) {
    var img = document.createElement("IMG");
    img.src = src;
    document.getElementById('image').appendChild(img);
}
</script>

and include the following,

<body onload="getimage()" >

To add more images:

function image(src) {

        //var img = document.createElement("IMG");
        //img.src = src;
       // document.getElementById('image').appendChild(img);
            images = eval('(' + src+ ')');
            for (i = 0; i < images.length; i++) {    
            var img = document.createElement("IMG");
            img.src = images[i];            
              document.getElementById('image').appendChild(img);
            }
    }

and pass a String array instead of a String in the load url like

final class JavaScriptBridge
        {
            public void ProcessJavaScript(final String scriptname, final String args)
                {             
                    mHandler.post(new Runnable()
                        {
                            public void run()
                                {
                        //String url="file:///android_asset/img.jpg";
                                    //webview.loadUrl("javascript:image(\""+url+"\")");
                                    ArrayList<String> url=new ArrayList<String>();
                                    url.add("file:///android_asset/img1.jpg");
                                    url.add("file:///android_asset/img2.jpg");
                                    url.add("file:///android_asset/img3.jpg");
                                    webview.loadUrl("javascript:image(\""+url+"\")");
                                }
                        });
                }
        }

To execute the image script multiple times:

  final class JavaScriptBridge
            {
                public void ProcessJavaScript(final String scriptname, final String args)
                    {             
                        mHandler.post(new Runnable()
                            {
                                public void run()
                                    {
                                      // You can load the URL at any point in the application. See below to call it from within another function.
                                       callFirstTime(scriptname,args);
                                     // Check below to load URL in another class Test.java
                                      Test newtest=new Test();
                                      newtest.methodToLoadUrl(scriptname,args);
                                    }
                            });
                    }
            }

public void callFirstTime(String script, String arguments)
{
  // Add images with a String array and pass it here
  webview.loadUrl("javascript:image(\""+url+"\")");

}

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

Creating animations for canvas using the .stroke() method, all done without the need for additional

I've noticed this question has been asked many times (I did my research), but I'm struggling to figure out how to animate the .stroke() command on a canvas. I came across some examples, however, they all seem to rely on external libraries that ar ...

Displaying information stored in a database as notifications in the notification icon within the HTML/PHP header

Within my MySQL database, there exists a table named order_detail. This table is populated with values from my android app. I am looking to display the order_id as a notification in my admin panel, which is built using HTML/PHP. The attributes of the orde ...

Using the Android application to link up with Google Drive

Greetings, I'm currently using a code that opens the camera and sends the captured picture to Google Drive. However, I've encountered two errors that I'm unable to resolve. Below is the complete code: (Code snippet her ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...

"Enhance your user experience with Android AutoComplete TextView

Hello there! I am currently using an autocomplete textview and I'm wondering how I can determine the direction of the pop up list. Any suggestions? ...

Having trouble bringing in components to my pages in ReactJS

There seems to be an issue preventing me from importing the components onto the page, resulting in this error: ERROR in ./src/pages/Home.jsx 4:0-37 Module not found: Error: Can't resolve './components/Card' in '/home/c4p1/blog/src/pages ...

Serializing intricate objects using JavaScript

I'm curious if there are any options outside of npm for serializing complex JavaScript objects into a string, including functions and regex. I've found a few libraries that can do this, but they all seem to depend on npm. Are there any good seri ...

Perform an action if the ImageView is within the specified Region

In my current setup, I have defined regions in my activity to detect touches as shown below: onTouch(...){ int x = (int) ev.getX(); int y = (int) ev.getY(); if (x >= 370 && x <= 500 && y >= 250 && y <= 420) ...

Error: The parser did not expect a closing curly brace

I'm working on a jQuery script that adds an input button to the body and then assigns it an onclick function. The function being called should take two arguments, both variables defined earlier in the code. Here's the current code snippet I have ...

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

Express.js routes are malfunctioning with jade/pug, causing frequent crashes and routing errors

Here is the code for my contact router: var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.render('contact'); }); module.exports = rou ...

Why are the height and width values I specified not matching the values returned?

I am currently learning HTML and JavaScript, specifically diving into the width() and height() methods in JavaScript. Setting the dimensions of div1 to 100px for height and 300px for width, I encountered a discrepancy when running the code. Upon execution ...

Why doesn't ngSubmit function inside a modal?

I am experiencing an issue where my submit button is not activating the ng-click angular directive, and I cannot seem to identify the cause. Most people who faced a similar problem did not have their submit button placed inside their form, but I am confi ...

Steps for assigning a value to extracted JSON data and then showcasing it

I would like to alter a parsed JSON by adding my own values and displaying only that modified data. Currently, I am able to display all the results from the response, but I specifically want to show the JSON with my customized values :) Here is the code w ...

Unlocking the value of data within a nested object in React: A guide

Recently, I have started working with React and am encountering a challenge in accessing data nested within an object. My goal is to develop an application that compares today's date with the dates in a list, and if the condition is met, display the c ...

What could be causing SVG to not render in a NEXTJS project upon deployment on Vercel?

Recently, I created a standout single-page nextJS application that was beautifully styled with Tailwind CSS. One interesting feature I added was incorporating the background of a component called SectionWrapper as an svg file. To achieve this, I crafted a ...

What are some ways to ensure that the promise from postgres is fulfilled before moving forward with my code execution?

I am currently developing a Node-js application that requires retrieving information from the database before making another database call. However, I am facing an issue where the first check is not always resolved before proceeding to the next step. I hav ...

Scrolling horizontally, a grid view is nested inside a HorizontalScrollView

Can anyone provide guidance on how to place a GridView within a HorizontalScrollView? Here is the XML code I have tried, but it doesn't seem to be working: <HorizontalScrollView android="http://schemas.android.com/apk/res/android" android:l ...

The exported class does not properly recognize the input values, causing them to be displayed as Undefined and triggering an error

Currently working with Ionic Framework version 6.13.1, I have two services set up in a similar code structure. One is the appointment.service.ts, and the other is the registration.service.ts. Each service corresponds to its own TypeScript file containing a ...

Is there a way to prevent elements on a web page from shifting when the page width becomes narrow enough?

Currently, as I delve into the world of web development with Svelte, I am in the process of creating a basic website to put my knowledge to the test. The main aim is to ensure that no matter how much the page is resized, the text and video content remain e ...