How to make links in a raw file clickable - android

I have a raw file with html content and comprising of <a href links. Right now I have referenced that raw file. Though the content displays, the links are not clickable. How do I make them clickable?
Below is the code for the same:
protected String doInBackground(final Void... params) {
try {
return Utils.readTextFile(Application.getAppContext(), R.raw.acknowledgements);
} catch (final IOException e) {
e.printStackTrace();
return null;
}
}
}

If using a TextView, you might use android:autoLink in XML or setAutoLinkMask in code to make URLs clickable. Note that this has nothing to do with <a> tags being present, it just scans for URLs (or other content such as e-mail addresses, if you enable them).

Related

android set TextView to html file

I need to get information from this website: http://rowans.diekantankys.nl/bonnen/index.php?id=4 (It's in dutch)
From line 36 and on is a table in which you can see the debt op people on this website:
<td>Marc</td>
<td>16.75</td>
</tr> <tr>
<td>Marlieke</td>
<td>7.27</td>
</tr> <tr>
<td>Anne Ruth</td>
<td>4.70</td>
but all the functions and methods that I found that should download an HTML file from a website/web-server to a string/array somehow fail, can anyone give me a method on which I can give my full error report?
My apology's if this is considered: "Not a real question", I don't know how to formulate this
Thanks in advance
I would recommend to use (http://jsoup.org "JSoup") to download the parse the HTML from URL
You can get the HTML as document and read the text on the elements
Document doc = Jsoup.connect("http://rowans.diekantankys.nl/bonnen/index.php?id=4").get();
In you case on this website , you need to get the text in the table body i.e., tbody
String table = doc.body().getElementsByTag("tbody").text()
So, you need to download the content first in an background thread and then update the TextView on UIThread.
new AsyncTask<Void, Integer, Long>(){
#Override
protected Long doInBackground(Void... params) {
try {
final Document doc = Jsoup.connect("http://rowans.diekantankys.nl/bonnen/index.php?id=4").get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String tableContent = doc.body().getElementsByTag("tbody").text();
// you can split the text and read it, as required.
textView.setText(tableContent);
}
});
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
Hope it helps you. Let me know if any issue.
You have to download all the HTML content, put it into a string and parse manually the code. If you are interested in the values into that table, I would suggest you to search into the string that contains the downloaded HTML for a uniqui piece of string that identifies the beginning of the table (eg. search for '' tag and you put the HTML section of code of the table into a different variable. Then you proceed to parse manually that string searching for and and extracting the values with a loop. Another way would be use regular expressions but it becames more difficult if you're not faimiliar with them. It's not a relevant resource but in this android app, I did exactly what just explained https://github.com/rexromae/mytotem_android/blob/master/com.torvergata.mytotem/src/com/torvergata/mytotem/student/StudentLogin.java

Access specific Android system fonts via CSS

I'm building a webapp off of Android's WebView class. Currently, when I point it at my page, any Japanese characters are rendered with the DroidSansFallback font which is what I want. However, when the device's language is changed to Japanese, it begins rendering Japanese characters in the MTLmr3m.ttf font, which sometimes affects the layout of the webpage that is being loaded. After doing some research, I've found that this is due to this snippet of code out of the fallback_fonts.xml system file
<family>
<fileset>
<file lang="ja">MTLmr3m.ttf</file>
</fileset>
</family>
Presumably I can't change this system file, but is there a way I can directly reference the DroidSansFallback.ttf file and set the font to that when the string has Japanese characters so that this fonts is used regardless of the language the device is set to?
I've tried using shouldInterceptRequest() from the WebViewClient class to catch a dummy protocol in a css #font-face delcaration like this: src: url("font:Droid") format("truetype"); and send the font that way via this code:
...
if (url.equals("font:Droid")){
File font = new File(Environment.getRootDirectory(),"/fonts/DroidSansFallback.ttf");
InputStream is = new FileInputStream(font);
String encoding="UTF-8";
WebResourceResponse font = new WebResourceResponse("font/ttf",encoding,is);
return font;
}
...
The method catches the request, but does not return the WebResourceResponse as expected.
I was hoping maybe there was a solution to this where I could reference the font I want in the CSS somehow. Any suggestions?
I know this must be late to answer, but may be it's useful to someone.
1) you can not access android root directory "/" unless you have Root permission.
2) i believe you used the wrong mimetype for font, use this "application/x-font-ttf"
so you have 2 options, put your desired font in asset, or copy your font to external storage.
i will show the first way and leave the other to you.
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
if(url.contains("font/droid.ttf"))
{
return getFontFromAsset();
}
}
private WebResourceResponse getFontFromAsset()
{
InputStream fontIn = null;
try
{
fontIn = yourContext.getAssets().open("DroidSansFallback.ttf");
}
catch (IOException e)
{
e.printStackTrace();
}
if(fontIn == null)
return null;
else
{
WebResourceResponse response = new WebResourceResponse("application/x-font-ttf", "UTF-8", fontIn);
return response;
}
}
also you might use some thing like this for your css:
#font-face { font-family: 'droid'; src: url('font/droid.ttf');} body { font-family: 'droid';}
this is the working method for me.

Retrieve only one image with Html.ImageGetter?

Iv'e been using the ImageGetter() interface in the Html.fromHtml() to retrieve image urls from a long html String. But since I only really need one image I don't want to go through the entire String and look for images. I would simply like to stop when I find the first image.
Any suggestions?
Html.fromHtml(html, new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
item.setImageUrl(source);
return null;
}
}, null);
EDIT : for now I only retrieve the last image in the html String so the ImageGetter will only retrieve that image.
private String getLastImage(String htmlContent){
String img = "";
try{
img = htmlContent.substring(htmlContent.lastIndexOf("<img"));
}catch (Exception e) {
e.printStackTrace();
}
return img;
}
Have a boolean field in your ImageGetter. In getDrawable(), fetch the image only if the boolean is false and then set it to true; return null otherwise.
To completely avoid parsing the rest of the HTML, you can not use Html.fromHtml(). Instead you may try using XMLPullParser. Just keep pulling tags until you get an <img> tag, at which point get the value of its <src> attribute.
But you may have to handle inputs which are not strict XHTML properly.

Jsoup select() return nothing in Android application

I'm making an Android app for my board community. The board provider gives me RSS feeds from general categories but don't generate feeds from topics. So I retreive topics URLs from these feeds and want to parse HTML with Jsoup and give it to a WebView.
It works nice except with the select() function which returns nothing.
The "HTML RETREIVED" log gives me : <html><head><title>The topic title</title></head><body></body></html>
h1 tags are in the code on test purpose : it displays well on WebView and the title of the parsed webpage too.
I also putted the log line right after the select() line. It returns nothing too.
I've tried in a pure Java project to parse with Jsoup only and it goes well.
So I assumed something's wrong with Android.
PS : Internet permission is active in the manifest.
Did I miss something ?
Here is the code :
String html;
Bundle param = this.getIntent().getExtras();
String url = param.getString("url");
try {
Document doc = Jsoup.connect(url).get();
doc.select(".topic .clear").remove();
String title = doc.title().toString();
html = doc.select(".username strong, .entry-content").toString();
html = "<html><head><title>"+title+"</title></head><body><h1>"+title+"</h1>"+html+"</body></html>";
WebView webview = new WebView(this);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(webview);
webview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
Log.d("LOADING",""+ progress);
}
});
webview.loadData(html, "text/html", "UTF-8");
//webview.loadUrl(url);
Log.i("HTML RETREIVED", ""+html);
} catch (IOException e) {
Log.e("ERROR", "Error while generate topic");
}
Ok I've found out something interesting.
The class I wanted to select was not here because I'm getting the mobile version of the webpage. It appears Android App use a mobile user-agent, which is quite normal but not said anywhere.
Anyway I know what thinking about now.

Parse HTML in Android

I am trying to parse HTML in android from a webpage, and since the webpage it not well formed, I get SAXException.
Is there a way to parse HTML in Android?
I just encountered this problem. I tried a few things, but settled on using JSoup. The jar is about 132k, which is a bit big, but if you download the source and take out some of the methods you will not be using, then it is not as big.
=> Good thing about it is that it will handle badly formed HTML
Here's a good example from their site.
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
//http://jsoup.org/cookbook/input/load-document-from-url
//Document doc = Jsoup.connect("http://example.com/").get();
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
Have you tried using Html.fromHtml(source)?
I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.
String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();
We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..
So Code goes like this
private void getWebsite() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
String title = doc.title();
Elements links = doc.select("a[href]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("href"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
You just have to call the above function in onCreate Method of your MainActivity
I hope this one is also helpful for you guys.
Also read the original blog at Medium
Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.
http://developer.android.com/reference/android/webkit/WebView.html
I think that you can enable javascript if you need it.

Categories

Resources