Inline images with Text in android - android

I'm attempting to download webpages for a user to view later. So far, I've downloaded the html, and the images. I can get the HTML to show up nicely formatted, but I cannot get the images to inline.
The code I'm using so far:
This is my method to get the article.
MyImageGetter mig = new MyImageGetter(this, urlId);
Spanned span = Html.fromHtml(contents[1], mig, null);
contents[1] = span.toString();
titleView.setText(contents[0]);
content.setText(contents[1]);
contents[] is an array that contains two strings. contents[0] is a simple string, contents[1] is a string with HTML markup.
MyImageGetter:
public class MyImageGetter implements Html.ImageGetter{
String urlId = null;
Context c = null;
public MyImageGetter(ArticleViewer articleViewer, String urlId2) {
c = articleViewer;
urlId = urlId2;
}
public Drawable getDrawable(String source) {
String[] brokenUrl = source.split("/");
String imgName = brokenUrl[brokenUrl.length-1];
File image = new File("/data/data/com.theHoloDev.Reader/Offline/" + urlId + "/" + imgName);
Log.w("MyApp", image.getAbsolutePath());
Bitmap bm = BitmapFactory.decodeFile(image.getAbsolutePath());
Drawable d = new BitmapDrawable(c.getResources(), bm);
return d;
}
}
When I have it log image.getAbsolutePath() it comes up with a file that exists in ddms. The Text content is there perfectly, but there are still little black boxes that say obj in each image. I had thought a textview would still be able to display images in that fashion, but either I'm doing something wrong, or there is another way to do this.

What is your desired end result? It is confusing to see that you are displaying html but you want the user to see the page... without html or did you do that for debugging? I assume the users will not see the html but rather the the page itself. In this case, I would go for a webview.
http://developer.android.com/reference/android/webkit/WebView.html
I don't think the text view is meant to be used like you are using it.
Good luck.

I figured it out. Instead of:
Spanned span = Html.fromHtml(contents[1], mig, null);
contents[1] = span.toString();
content.setText(contents[1]);
I need:
Spanned span = Html.fromHtml(contents[1], mig, null);
content.setText(span);
I was running into problems setting span to string.

Related

Link on a Android textView

I am trying to put a link on a textview, but when I click this link the application breaks!! This is my code:
final TextView msg = (TextView)view_aux.findViewById(R.id.accordion_msg);
msg.setText(Html.fromHtml(dbStructure.getMsg()));
msg.setTypeface(tF);
msg.setTextColor(Color.DKGRAY);
msg.setMovementMethod(LinkMovementMethod.getInstance());
Where dbStructure.getMsg() returns a String. This String could be something like:
< a href="/reference/android/widget/RelativeLayout.html">RelativeLayout< /a>
lets child views specify their position relative to the parent view or to each other (specified by ID). So you can align two elements by right border, or make one below another, centered in the screen, centered left, and so on.
It seems nice, but the app stops when I press it.
EDIT
The error thrown ActivityNotFoundException.
the link you are trying to open is broken
/reference/android/widget/RelativeLayout.html
there is nothing corresponding to the above link.
replace it with the proper url like this
http://developer.android.com/reference/android/widget/RelativeLayout.html
Thank you very much for every one... the problem is (as #Antonio #danidee #TheRedFox and #Arslan say) the format of the url... it doesn´t start with http.
With permission from you all, I am going to answer my own question:
final TextView msg = (TextView)view_aux.findViewById(R.id.accordion_msg);
String msg_text = dbStructure.getMsg();
if(msg_text.contains("href=\"")) {
String[] msg_aux = msg_text.split("<a href=\"");
if (!msg_aux[1].toLowerCase().startsWith("http"))
msg_aux[1] = "href=\"http://" + msg_aux[1];
else
msg_aux[1] = "href=\"" + msg_aux[1];
msg_text = msg_aux[0] + msg_aux[1];
}
msg.setText(Html.fromHtml(msg_text));
msg.setTypeface(tF);
msg.setTextColor(Color.DKGRAY);
msg.setMovementMethod(LinkMovementMethod.getInstance());
Thank you.
EDIT on the code, these lines:
else
msg_aux[1] = "href=\"" + msg_aux[1];

SKipping image while converting html text to string android

Iam converting some Html text from a webpage into a String by doing the following
mydescription =Html.fromHtml(data.getBody()).toString();
This is what data.getBody() returns:-
<div><p>​It's great to have great dynamic companies to work with, and NXP is no exception.</p><p><img alt="This is an image of NXP Logo" src="https://anprodstorage.blob.core.windows.net/b75ef288-0381-45c4-a4cd-809097370bec/untitled.png" style="margin:5px;" /><br></p><div><iframe width="560" height="315" src="https://www.youtube.com/embed/I6191gXXGog" frameborder="0"></iframe> </div><p>​<br></p></div>
But within that html text there is a image source as well. When I do the above I get a square image with obj written inside it instead of the image.
This is myDescription

I just want to get the text and not the image.
How do i just get the text and not the image
Try this way,hope this will help you to solve your problem.
String htmlString = "<div><p>​It's great to have great dynamic companies to work with, and NXP is no exception.</p><p><img alt=\"This is an image of NXP Logo\" src=\"https://anprodstorage.blob.core.windows.net/b75ef288-0381-45c4-a4cd-809097370bec/untitled.png\" style=\"margin:5px;\" /><br></p><div><iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/I6191gXXGog\" frameborder=\"0\"></iframe> </div><p>​<br></p></div>";
String first = htmlString.substring(0,htmlString.indexOf("<img"));
String second = htmlString.substring(htmlString.indexOf("/>",htmlString.indexOf("<img"))+2,htmlString.length());
textview.setText(Html.fromHtml(first+second));
use this code:
String clippedBody = htmlString.replaceAll("<img[^>]*?>.*?/[^>]*?>", "");
I advise using libraries, like jsoup when working with HTML (with soup you will be able to get only text by calling Jsoup.parse(html).text())
Haven't tried it myself
private static final Pattern REMOVE_TAGS = Pattern.compile("<img>(\\S+)</img>");
public static String removeTags(String string) {
if (string == null || string.length() == 0) {
return string;
}
Matcher m = REMOVE_TAGS.matcher(string);
return m.replaceAll("");
}
If you want to strip down all the HTML code, then you can use:
replaceAll("\\<[^>]*>","")
For your second question (from Source 2):
// the pattern we want to search for
Pattern p = Pattern.compile("<p>(\\S+)</p>");
Matcher m = p.matcher(string);
// if we find a match, get the group
if (m.find())
{
// get the matching group
String codeGroup = m.group(1);
// print the group
System.out.format("'%s'\n", codeGroup);
}
Source: 1, 2 and 3

Android - Breaking down a Spanned object

spanned = Html.fromHtml("<sup>aaa</sup>bbb<sub>ccc</sub><b>ddd</b>");
Will create a Spanned object with with 3 spans aaa, ccc, ddd.
bbb is being ignored since it's not inside an html tag,
spans = spanned.getSpans(0, spanned.length(), Object.class);
will only identify 3 spans.
I need a way to extract all the 4 sections of the code, if possible into some sort of an array that will allow to me to identify the the type of each span.
I need a way to extract all the 4 sections of the code
Use nextSpanTransition() to find the starting point of the next span. The characters between your initial position (first parameter to nextSpanTransition()) and the next span represent an unspanned portion of text.
You can take a look at the source code to the toHtml() method on the Html class to see this in action.
'bbb' is the one which is not inside html tag. Even though i guess it will not be missed. 'ccc' is a subscript, may be it is rendered but not visible to you. Try to increase textview height if you have constrained it.
use this http://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String, android.text.Html.ImageGetter, android.text.Html.TagHandler), pass null for ImageGetter and your custom TagHandler
see the example
String source = "<b>bold</b> <i>italic</i> <unk>unknown</unk>";
TagHandler tagHandler = new TagHandler() {
Stack<Integer> starts = new Stack<Integer>();
#Override
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (tag.equals("unk")) {
if (opening) {
starts.add(output.length());
} else {
int start = starts.pop();
int end = output.length();
Object what = new Object();
output.setSpan(what, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
};
Spanned spanned = Html.fromHtml(source, null, tagHandler);
TextUtils.dumpSpans(spanned, new LogPrinter(Log.DEBUG, TAG), "span ");

Parsing ImageGetter image as text

Using ImageGetter and HTML, I have some emoticons in an edittext (code below), however I want to be able to recognize these images later in the edittext so it can be stored as a string. Does anyone know how to retrieve this, or should I keep a string updated with string value instead.
Thanks
ImageGetter imggtr = new ImageGetter()
{
public Drawable getDrawable(String source)
{
Drawable d = getActivity().getResources().getDrawable(getEmoticonDrawable(position));
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
Spanned cs = Html.fromHtml("<img src='" + getActivity().getResources().getDrawable(getEmoticonDrawable(position))
+ "'/>", imggtr, null);
mEditor.append(cs);
As you mentioned, you should keep a separate string in memory. If you try to parse the html back to a string, it's going to be complicated and not very flexible.

Displaying image based on string chosen?

I have a code rite now that just generates a random drink combination from an array, what I need to do is have a different image assigned to each choice and have it display that image.
Here is my code for a random drink:
if(Vodka.equals(true)){
final TextView text2 = (TextView) findViewById(R.id.display2);
randomIndex = random.nextInt(array_city.Vodka.length);
text2.setText(array_city.Vodka[randomIndex]);
}
Say this code spits out "Smirnof" then i display a picture of the bottle, it spits out "Sky" then changes to a picture of that bottle. How would i do this without making an if statement for each option, my arrays are very long and that would be alot of if statements i was just Hoping that there is an easier way to do it?
Thanks anybody for your help! it is very much appreciated I have been stuck on this for a while.
===============================================================
#Joan
Here is what i am trying to put together using your code:
//Run option Vodka
if(Vodka.equals(true)){
final TextView text2 = (TextView) findViewById(R.id.display2);
randomIndex = random.nextInt(array_city.Vodka.length);
text2.setText(array_city.Vodka[randomIndex]);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
int Cimage = getResources().getIdentifier(array_city.Vodka[randomIndex], null, "com.famousmods.what.should.i.drink");
image.setImageResource(Cimage);
}
Here is what my array looks like (a smaller example):
public static final String[] Vodka = {"Absolut Vodka","Finlandia","Ketel One","Polmos Krakow","Skyy","smirnoff vodka",
"Stolichnaya","Fleischmann's","Gilbey's","Gordon's","Wolfschmitt","Five-O-Clock"};
I have put the file "smirnoff_vodka.png" into my res/drawables as an example but it doesnt work?
You can use getResources().getIdentifier("image_name", null, "your_application_package"); on your context to retrieve the image id. Then you can use this id as you would use R.id.image_name.
EDIT: It needs to be "drawable" instead of null. See below.

Categories

Resources