Upload text file to webview android

So far I have read how to load โ€œregularโ€ html web pages into a web view. so far I am passing the url containing the path to my text file, but it is not loading anything. this is my method:

@Override public void onSelected(String url) { ViewerFragment viewer = (ViewerFragment) getSupportFragmentManager() .findFragmentById(R.id.view_fragment); if (viewer == null || !viewer.isInLayout()) { Intent showContent = new Intent(getApplicationContext(), ViewerFragment.class); showContent.setData(Uri.parse(url)); startActivity(showContent); } else { viewer.updateUrl(url); } } 

and the viewer fragment received the following:

  public class ViewerFragment extends Fragment{ private WebView viewer = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { viewer = (WebView) inflater .inflate(R.layout.details_fragment, container, false); return viewer; } public void updateUrl(String newUrl) { if (viewer != null) { viewer.loadUrl(newUrl); } } } 

but keep getting this screen: webviewerror

any ideas how to do this? = / I already tried to work a little, but did not find much information about this ... in fact, almost did not find anything. Therefore any help would be appreciated.

+4
source share
1 answer

Try reading the contents of the text file and the text prefix using <html><body> , then add </body></html> , then use the WebView method loadData(...) .

Example:

 StringBuilder sb = new StringBuilder("<html><body>"); sb.append(readTextFile()); sb.append("</body></html>"); myWebView.loadData(sb.ToString(), "text/html", "UTF-8"); public String readTextFile(String filename) { // Open and read the contents of <filename> into // a single string then return it } 
+6
source

Source: https://habr.com/ru/post/1389172/


All Articles