10

I'm loading an html asset page into a WebView using

webMain.loadUrl("file:///android_asset/record.html");

which works fine, but inside the html are a number of places where I'd like to use information from the app. For instance, the HTML may contain text that reads "[Custom]". Is there a way I can replace that word with information passed from the application?

5 Answers 5

17

This is an old and already accepted question, however I am sure that the problem can be solved in more elegant way by using javascript.

Keep the html file in your assets folder and surround the text which you want to replace into with div elements with unique id's.

<html>
  <head> ... <head> 
  <body> 
    Static text
    <div id="replace1">replace me</div>
    <div id="replace2">replace me too</div> 
    More static text ... 
  </body>
</html>

Now create a javascript function which will replace the innerHtml of a div with an id:

    function replace(id, newContent)
    {
        document.getElementById(id).innerHTML = newContent;
    }

This function will be best placed directly in the html file, update the <head> section to look like this:

<head>
  ...
    <script type="text/javascript">
        function replace(id, newContent)
        {
            document.getElementById(id).innerHTML = newContent;
        }
    </script>
</head>

Now we need to call the javascript function from from the WebView Android api:

WebView helpView = (WebView)findViewById(R.id.helpView);
helpView.getSettings().setJavaScriptEnabled(true);
helpView.setWebViewClient(new WebViewClient() {
  @Override
  public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    view.loadUrl("javascript:replace('replace1', 'new content 1')");
    view.loadUrl("javascript:replace('replace2', 'new content 2')");
  }
});
helpView.loadUrl("file:///android_asset/help.html");

Using this you will avoid reading potentially large data into memory and running expensive operations on it unnecessarily.

Sign up to request clarification or add additional context in comments.

3 Comments

What if my html has some text "{{UserName}} is very good. {{UserName}} is a programmer. {{UserGender}} can develop great apps as well" .I need to replace it like - Richard is very good. Richard is a programmer. He can develop great apps as well. Now, do I need to give 2 different IDs for both the {{UserName}}s?
can I give same IDs to the similar / same strings, as I may have multiple html files with different sequences of strings, and managing through different unique ids for same strings will be troublesome
@DroidWormNarendra In such case I guess you would use class instead of id.
6

This is worked for me.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Payment Demo</title>
</head>
<body>
    <div>
        <input type="text" id="uname " name="uname " value="">
        <input type="text" id="pass" name="pass" value="">
    </div>
</body>
</html>

This is java code.

WebView wb = (WebView) findViewById(R.id.webView1); 
wb.loadUrl("file:///android_asset/web1.html");
wb.getSettings().setJavaScriptEnabled(true);

wb.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView web, String url) {
        // TODO Auto-generated method stub
        String uname = "[email protected]";
        String pass = "******";

        web.loadUrl("javascript:(function(){document.getElementById('uname').value = '"+uname+"';})()");
        web.loadUrl("javascript:(function(){document.getElementById('pass').value = '"+pass+"';})()");
            
    }
});

2 Comments

This line will helps to change my selected language reflected in webview of android.. Thanks dude
wb.getSettings().setJavaScriptEnabled(true);
4

Actually I do not understand why the file size of record.html will affect maintainence of the code. Read the html string (using Java reader class or what ever) from the html file in asset, use replaceAll function with Regex to replace all the [Custom] in the html file. How long the html is should not really affect how you maintain the code. It should rather be a performance problem, or the string is really really long that exceeds the java String limit.

some code I have used before :

InputStream is = getApplicationContext().getAssets().open("details/product_jsmodify.html");
Reader r = new InputStreamReader(is);
String details = Utils.readertoString(r);
details = details.replace("%product_name%",productName );

Utils is my class doing the conversion to string. I am not using Regex here as I am only replacing word for once. Then I load the string like Cata does. It is quite clean I suppose.

6 Comments

I want to do it that way because it is easier to make changes to record.html than to a Java document with 200 lines of concatenated string. I tried this change and it seems to be giving me the correct info but when I call webMain.loadData(details, "text/html", null); it gives a page not found error. The page it is not finding happens to be all of the code in record.html.
if you have a <html> tag for the string I think you may need to use loadDataWithBaseURL
This turned out to be the key. Thanks!
I'm receiving an error Utils cannot be resolved .. what's the library of Utils? @OSMman @reTs
Not a library, just my custom class which contains a convenience method to convert a Reader to a String. Basically just a loop, appending reader.read() to a String.
|
4

Yes you can do that by loading your page in a String and then load that string in your WebView.

Eg:

String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);

Taken from here

2 Comments

This is definitely a solution, but record.html is a large file. For purposes of maintaining the code, I'd prefer not to redo the whole thing this way.
Unfortunately I don't think you can solve this without converting your html in a String because I don't think there is a way to tell your webview to update only some pieces of html inside it..
1

This one worked for me, with the html along with the text and images.

  InputStream is = getAssets().open(html_name);
            int size = is.available();

            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();

            String str = new String(buffer);
            str = str.replace("InitialTextToBeReplaced", "TextAfterReplacement");

       //Now instead of webview.loadURL(""), I needed to do something like -
            webView.loadDataWithBaseURL("file:///android_asset/", str, "text/html", "UTF-8",null);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.