Home > Net >  Storing and manipulating HTML strings in Android
Storing and manipulating HTML strings in Android

Time:06-15

I'm trying to dynamically generate some HTML that my app needs to output. The setup is a base HTML string, which contains a list - the content of the list will change from time to time. I'm not sure about how to store HTML string properly in an Android app. Just storing it as a string does not seem to work as the " signs in the HTML are breaking the string. What I wish to achieve is something like this:

<html>
  <h1 style="color:blue;">Title</h1>
  {some generated HTML code here}
  <p>Lorem ipsum</p>
</html>

The actual HTML is obviously a lot longer and more complex but for simplicity I have just created some dummy HTML.

Can someone guide me towards a way of handling something like this in Android?

CodePudding user response:

You can try and create an empty div element and fill it with the string wirtten like the HTML elements.

<html>
  <h1 style="color:blue;">Title</h1>
  <div id="myDiv"></div>
  <p>Lorem ipsum</p>
    
  <script type="text/javascript">
    myHTML = "<p>I am a paragraph with info</p>";

    document.getElementByID("myDiv").innerHTML = myHTML;
  </script>
</html>

CodePudding user response:

You can use Jsoup to manipulate HTML string in a proper way.

val doc = Jsoup.parse(htmlString)
Element div = doc.select("div").first(); // <div></div>
div.text("five > four"); // <div>five &gt; four</div>
div.prepend("First ");
div.append(" Last");

Now create a basic HTML document which you can edit dynamically like this and return as output.

  • Related