I am obtaining HTML coded content from an SQlite database that I would like to display in a WebView . I am currently using:
public class ShowAbstracts extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String body = extras.getString(DatabaseHelper.KEY_BODY);
WebView webview = new WebView(this);
setContentView(webview);
String summary = "<html><body> "+body+" </body></html>";
webview.loadData(summary, "text/html", "iso-8859-1");
}
}
}
It works in that it opens a WebView and displays the contents but I get strange characters and for some content it just crashes. The Database is ISO-8859-1 encoded.
Is there any way to take care of the special characters in my database content and display them properly?
Thanks very much in advance!
Rik
Success!
Solving this was a combination of 3 things:
uri encoding the string
pasting a head in the HTML string identifying utf-8 encoding
installing LibreOffice which allowed the xls file used for generating the SQLite database to be saved as a csv file with utf-8 encoding (as far as I can tell not possible from MS Office Excel).
.
public class ShowAbstracts extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String body = extras.getString(DatabaseHelper.KEY_BODY);
WebView webview = new WebView(this);
setContentView(webview);
String summary = "<?xml version='1.0' encoding='utf-8'?><html><body>"+body+" </body></html>";
String uri = Uri.encode(summary);
webview.loadData(uri, "text/html", "utf-8");
}
}
}
The api for WebView (http://developer.android.com/reference/android/webkit/WebView.html) says that the the data argument must be URI-escaped (http://developer.android.com/reference/java/net/URLEncoder.html).
Also, when you have a string, the encoding has already been done. You have to see to that the string is created using the correct encoding (for Android the default is UTF-8).
Related
After days of research and numerous compiler errors... i think i need some assitance from the community.
I have a simple app that retrieves a url through a shared intent from another app.
I want to extract a value from the intent's stringextra (which is a url) add it to the end of my script's url and send that final string as a URL to an URLconnection httpget request.
I've defined my script's url as a variable.
I've gotten the intent and its extras and put it in a variable.
I've tried to just concat my url variable and the stringextra variable to no avail,
URLconnectio gave me back a MalformedURLException. I've logged the concat'd variable
and it looked exactly like what i wanted but for some reason it wouldn't go through.
So now, I'm attempting to just cut the piece I need off of the stringextra and put it on my script's url and then make the http get request off that newly formed string.
SO....
how do I extract 11 characters after "v=", which is in the stringextra, which is
a variable called sharedText?
String goLoQooUrl = "http://my.domain.my/script.php?link=";
private static final String TAG = "LTV";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent rIntent = getIntent();
String rAction = rIntent.getAction();
String rType = rIntent.getType();
if (Intent.ACTION_SEND.equals(rAction) && "text/plain".equals(rType))
displaySentText(rIntent);
}
private void displaySentText (Intent rIntent) {
String sharedText = rIntent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText == null) return;
if (sharedText.startsWith("http://")) {
TextView url = (TextView) findViewById(R.id.URL);
url.setText(String.valueOf(sharedText));
****String w = goLoQooUrl+SUBSTRING***** this is what I want
Log.d("TAG", w);
};
playOnLoqooTv(w);
}
private void playOnLoqooTv (String w) {
try {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(w);
I've tried numerous things to no avail
namely tried using the substring method and it gave me an error about that method
wasn't available I probably wasn't calling it correct.
Can any Masters of the Universes', shed some light?
Try this out:-
int indexOfv = sharedText.indexOf("="); // Get the index of =
indexOfv++; // To get the substring after this element.
String subString = sharedText.substring(indexOfv, indexOfv+11); //Get the 11 characters after the = sign.
I can show up HTML file content in android webview well.Now how could i pass parameter into HTML file.For ex.my HTML content has an video player
i need to pass dynamic values(URL) into HTML file for playing dynamic video.My HTML file is located on asset folder.How could i do this?
Thanks.
I came upon this problem today, however I needed this to work with UTF-8 encoding, so this was my approach, hopefully it will help someone and clarify some of the previous answers to this question.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1>%ERR_TITLE%</h1>
<h2>%ERR_DESC%</h2>
</body>
</html>
Java:
String content = IOUtils.toString(getAssets().open("error.html"))
.replaceAll("%ERR_TITLE%", getString(R.string.error_title))
.replaceAll("%ERR_DESC%", getString(R.string.error_desc))
mWebView.loadDataWithBaseURL("file:///android_asset/error.html", content, "text/html", "UTF-8", null);
As for IOUtils:
http://commons.apache.org/proper/commons-io/download_io.cgi
Instead of passing directly the video URL (following you example), i would have used tokens in the Html file. For example:
<embed src="$VIDEO_URL$" autostart="false" />
where the $VIDEO_URL$ will be the token wich will be replaced during the runtime with a real video URL.
Also, since you cannot change the contents of your asset folder during runtime you should load the html file contents into a String variable and use the replace method to replace the token with a real URL and, finally, pass that string to your webview. Something like this:
//The html variable has the html contents of the file stored in the assets folder
//and real_video_url string variable has the correct video url
html = html.replace("$VIDEO_URL$", real_video_url);
webview.loadData(html, "text/html", "utf-8");
If i would like to have something dynamic in my HTML i would have an html with dynamic parts written like this:
<B>%NAME%</B>
Then i would load my HTML:
String template = Utils.inputStreamToString(assets.open("html/template.html"));
then
Then i would replace all dynamics parts with what i want like this:
String data = template.replaceAll("%NAME%", "Alice McGee");
then i would pass it to my webView!
WebView webView = new WebView(this);
webView.loadDataWithBaseURL("file:///android_asset/html/", data, "text/html", "utf-8", null);
I managed to pass variables in a different way.
My problem was that everytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet.
What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.
In onCreate method after setting up myWebView I did the following:
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String urlString)
{
Log.i("onPageFinished", "loadVariables("+newURL+")");
if(newURL!="")
myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
jsInterface = new JSInterface(this,myWebView);
myWebView.addJavascriptInterface(jsInterface, "Android");
if (savedInstanceState != null)
{
// retrieve saved variables and build a new URL
newURL = "www.yoururl.com";
newURL +="?var1=" + savedInstanceState.getInt("key1");
newURL +="?var2=" + savedInstanceState.getInt("key2");
Log.i("myWebApp","NEW URL = " + newURL);
}
myWebView.loadUrl("www.yoururl.com");
So, what it happens is that first I load the page with the default URL (www.yoururl.com) and onPageFinished I call a new javascript method where I pass the variables.
In javascript loadVariables function looks like this:
function loadVariables(urlString){
// if it is not the default URL
if(urlString!="www.yoururl.com")
{
console.log("loadVariables: " + urlString);
// parse the URL using a javascript url parser (here I use purl.js)
var source = $.url(urlString).attr('source');
var query = $.url(urlString).attr('query');
console.log("URL SOURCE = "+source + " URL QUERY = "+query);
//do something with the variables
}
}
here assets means what?
String template = Utils.inputStreamToString(assets.open("html/template.html"));
After processing a file, I get a HTML string in which the image is set as
<img src="abc.001.png" width="135" height="29" alt="" style="margin-left:0pt; margin-top:0pt; position:absolute; z-index:-65536" />
The path of the image should not be modified because I have to choose the file item from a list. The image is in the same directory as the file. I load the HTML string using loadData/loadDataWithBaseURL, but the image isn't displayed. I only see its frame.
How can I fix this? And can I apply that solution in case I have many images which are indexed as .001.jpg, .002.png , etc... (all in a directory) ?
Update: Thanks, it works with loadUrl() statement no matter how I name the image. In fact I have to read and process the content before loading it in WebView. That's why I use loadDataWithBaseUrl() statement and get the trouble above. Here's my code in the test project to read and display the content of Test.html.
String res = "";
File file = new File(Environment.getExternalStorageDirectory()+"/Test.html");
try {
FileInputStream in = new FileInputStream(file);
if (in != null) {
BufferedReader buffreader = new BufferedReader(
new InputStreamReader(in));
String line;
while ((line = buffreader.readLine()) != null) {
res += line;
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
wv.loadDataWithBaseURL(null, res, "text/html", "utf-8", null);
//wv.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Test.html");
The statement in // works but that's not what I can do in my real project. I have a solution: after processing the content I have to save it in a temporary HTML file then load it, that file will be delete later. However, I'm still looking forward to a better solution :)
Try to change the name of the image file. I thought this is because of double dot in the name.
<img id="compassRose" src="CompassRose.jpg"></img>
this is working for me....
Code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
public class StackOverFlowActivity extends Activity {
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView view=(WebView)findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/index.html");
view.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
}
final class MyJavaScriptInterface
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
//Do your activities
}
});
}
}
}
index.html:
<html>
<head>
<title title="Index"></title>
</head>
<body>
<h2>Android App demo</h2>
<br /> <img src="CompassRose.jpg" />
</body>
</html>
Result:
simply use:
webview.loadUrl("file:///android_asset/mypicture.jpg");
Your problem is with the line:
wv.loadDataWithBaseURL(null, res, "text/html", "utf-8", null);
The first parameter (baseURL) is null. For some reason, WebView then refuses to load any linked resources even if you use absolute URLs. You might find that it will work if you change your code to (assuming your images are stored in the external dir):
wv.loadDataWithBaseURL ("file://" + Environment.getExternalStorageDirectory(), res, "text/html", "utf-8", null);
Remember to add the proper permission if you refer to resources on the network:
<uses-permission android:name="android.permission.INTERNET" />
Sorry, a little late in my reply. I was researching a similar problem when I came across this post.
WebView webView=(WebView)findViewById(R.id.my_wb);
String url = "YOUR URL";
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl(url);
I am trying to show an html file in my assets folder but in web view i am seeing white blank page. I got similar example from stackflow only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String mimeType="text/html";
final String encoding="UTF-8";
String htmlString="<html><body>";
Document doc;
WebView wv= new WebView(this);
Elements link = null;
setContentView(wv);
try{
InputStream in=getAssets().open("myweb.html");
byte[] buffer= new byte[in.available()];
in.read(buffer);
in.close();
wv.loadData(new String(buffer), mimeType, encoding);
}
catch(IOException e)
{
Log.d("MyWebView", e.toString());
}
}
you can load the content of the web view using
// add a webview with id #+id/the_webwiev to your main.xml layout file
WebView wv = (WebView)findViewById(R.id.the_webview);
wv.loadUrl("file:///android_asset/myweb.html");
Uhm, did you try following the WebView example from the official webpage? It's really simple.
http://developer.android.com/resources/tutorials/views/hello-webview.html
I followed that and had no trouble implementing a WebView. Your code looks overly complicated for something that is quite simple.
If your file is called pmi_help.html (and located in the /assets/ folder), you load it using:
mWebView.loadUrl("file:///android_asset/pmi_help.html");
Put your html page in asset > www, then load:
mWebView.loadUrl("file:///android_asset/index1.html");
I want to display one static HTML page in my android emulator.
an easier way is described at Android HTML resource with references to other resources. Its working fine for me.
Put the HTML file in the "assets" folder in root, load it using:
webView.loadUrl("file:///android_asset/filename.html");
I'm assuming you want to display your own page in a webview?
Create this as your activity:
public class Test extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
try {
InputStream fin = getAssets().open("index.html");
byte[] buffer = new byte[fin.available()];
fin.read(buffer);
fin.close();
webview.loadData(new String(buffer), "text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
This will read the file 'index.html' from your project assets/ folder.
So you can simply use the WebView control to display web content to the screen, which can think of the WebView control as a browser-like view.
You can also dynamically formulate an HTML string and load it into the WebView, using the loadData() method. It takes three arguments. String htmlData, String mimeType and String encoding
First of all you create a “test.html” file and save it into assets folder.
Code:
<html>
<Body bgcolor=“yellow”>
<H1>Hello HTML</H1>
<font color=“red”>WebView Example by Android Devloper</font>
</Body> </html>
if you want see full source code : Display HTML Content in Android