To show a static html page in android - android

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");

Related

Loading a custom css into a WebView

How do I inject a custom CSS file into a WebView?
I am using Jsoup to extract the HTML Code, then I remove the existing CSS file. I do not know how to inject my local CSS file to the HTML code properly. I am using Stackoverflow as an example. This is some portion of my code. My test.css file is in the assets folder.
Document doc;
String htmlcode = "";
web = (WebView) findViewById(R.id.webView1);
try {
doc = Jsoup.connect("http://stackoverflow.com/users").get();
doc.head().getElementsByTag("link").remove();
doc.head().appendElement("link").attr("rel", "stylesheet")
.attr("type", "text/css").attr("href", "test.css");
htmlcode = doc.html();
web = (WebView) findViewById(R.id.webView1);
web.loadDataWithBaseURL("file:///android_asset/test.css",
htmlcode, "text/html", "UTF-8", null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is what's inside my test.css file, it's the same CSS file being used by Stackoverflow.
Here's a link!
Thank you and I appreciate your time!
Instead of loadDataWithBaseURL try
web.loadUrl("file:///android_asset/test.css");

Android : Display images in Webview

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);

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.

html5 apps for tablets: possible to load images from device's filesystem?

I created a simple html file that loads some images from my local hard-drive (ubuntu).
It is enough to put
<img src=/home/user/directory/image.jpg></img>
Now I need to know if it is the same when Html5 is displayed on a tablet like Android or iOS, or Html5 is used in offline app.
I mean, if html5 can load an image from the device's filesystem just like on my computer, without localStorage or sessionStorage.
If you deploy the application as native application it is possible (wrap it with Phonegap).
For saved HTML files it is not possible.
On Android, it can be done even though it looks a bit tricky at first. Say you have defined a WebView in your layout.xml, which you want to fill with an html file shipped with your application, which in turn should import a png also shipped with your application.
The trick is to put the html file into res/raw and the png into assets.
Example.
Say you have hello.html which should include buongiorno.png.
Within your project, say MyProject, place buongiorno.png into MyProject/assets.
The hello.html goes into MyProject/res/raw (because we want to avoid having it 'optimised' by the android resource compiler), and could look like this:
<html>
<head></head>
<body>
<img src="file:///android_asset/buongiorno.png"/>
<p>Hello world.</p>
</body>
</html>
In your java code, you would put this code:
WebView w = (WebView) findViewById(R.id.myWebview);
String html = getResourceAsString(context, R.raw.hello);
if (html != null) {
w.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
}
where getResourceAsString() is defined as follows:
public static String getResourceAsString(Context context, int resid) throws NotFoundException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(resid);
try {
if (is != null && is.available() > 0) {
final byte[] data = new byte[is.available()];
is.read(data);
return new String(data);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
try {
is.close();
} catch (IOException ioe) {
// ignore
}
}
return null;
}

How to show static HTML page in android emulator?

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

Categories

Resources