How to getElementById in Java for Android

How to getElementById in Java for Android

Here is what I'd like to do.

  1. Read an html document into code
  2. Use getElementById to get a certain portion of code by id, then save this string.
  3. Create a text document to save this string to
  4. Run the text document (going to be a html doc)

Is this possible?

1 Answer

You need some html parser like it is Jsoup. Its easy simple and effective library. Down there you can see one my random implementation, I did for answering another question similar to this one. .getElementById(id); is the method you are looking for...

import org.apache.http.protocol.HTTP;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class start extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       try {
        Document doc = Jsoup.connect(URL).get();
        Log.i("DOC", doc.toString().toString());
    Elements elementsHtml = doc.getElementById(id);
        for(Element element: elementsHtml)
        {
            Log.i("ELEMENTI",URLDecoder.decode(element.text(), HTTP.UTF_8));
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Here you can get the Jsoup

For writing the file use FileWriter or any other class that allows you to write to file

Do not forget to add permision for connecting to internet in your Manifest

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.