Android textview for html from url

旧城冷巷雨未停 提交于 2020-01-15 04:56:06

问题


Ive been trying to get a TextView working to display my HTML from a url but all the examples ive seen use a string e.g

String htmltext = "<h2>Title</h2><br><p>Description here</p>";
    myTextView.setText(Html.fromHtml(htmltext));

But i want to display from a webpage that i run. If i change htmltext to "www.example.com but that is displayed not the content.

Im sure many will say use webview. I have and looks just like a browser.


回答1:


First get all the content from web page by supplying URL to getResponseFromUrl(String str) method , written below. Then you will be able to show it in your TextView.

 String htmltext = getResponseFromUrl("www.example.com");
 myTextView.setText(htmltext);


 public static String getResponseFromUrl(String url) {
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpGet httpget = new HttpGet(url); 
        HttpResponse response = httpclient.execute(httpget); 
        HttpEntity entity = response.getEntity(); 
        InputStream iStream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(iStream, "iso-8859-1"), 8);
        StringBuilder strBuilder = new StringBuilder();
        String line= null;

        while ((line= reader.readLine()) != null)
            strBuilder .append(line);

        String content = strBuilder .toString(); 

        iStream.close();

        return  content; 
        }



回答2:


In the end I used JSoup to do my task. Will post code later

new Thread(new Runnable() {

            @Override
            public void run() {
                try {

                    //get the Document object from the site. Enter the link of site you want to fetch
                    Document document = Jsoup.connect("http://www.mywebsite.com.au/message.html").get(); // this is the website string

                    //Get the text we want
                    title = document.select("h2").text().toString();
                    //set the title of text view
                    //Run this on ui thread because another thread cannot touch the views of main thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            //set both the text views
                            titleText.setText(title);
                            titleText.setMovementMethod(new ScrollingMovementMethod());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


来源:https://stackoverflow.com/questions/34331812/android-textview-for-html-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!