NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Friday, 25 November 2011

Basic WebView


On Android we can build what are called Hybrid Apps. i.e. apps that have both HTML pages as well as native activities co-existing. There is a lot of debate on which is the way to develop for mobiles – HTML5 or native? Each of these have their own pros and cons. I will not go into those now. However, to be able to embed HTML pages into your app, one of the ways is through the use of a WebVew component.
Here I will share with you a very simple example of building a WebView App. This is nothing too different from what you see in the google resources pages. However, the intention here is to move from this basic level to a little more advanced level of interacting from the HTML page with Native Apps – integrating through JavaScript. That will be in the next tutorial, in keeping with my principle of explaining one thing at a time.

Also, for this example you will also need to have a webserver that serves you some HTML pages that can be invoked through your WebView. As an addendum to this article, you will find how to create a small web server app in your local environment.

Now, what is a WebView? Google documentation beautifully explains it as
 “A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.”

Let’s create a WebView which should display your home Page, on loading. In the main class of the project here is the code in the onCreate() method:

  public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "Entering onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
       
        mWebView = (WebView)findViewById(R.id.webview);
        mWebView.clearCache(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
       mWebView.loadUrl("http://10.0.2.2:8080/SampleWebServer/Welcome.html");
        Log.i(TAG,"Exiting onCreate");
}    

It is simple and straight forward. I have defined a WebView in the layout folder as below (file name webview.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
            <WebView
                android:id="@+id/webview"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                  android:scrollbarStyle="outsideOverlay"
                  android:scrollbarFadeDuration="5"
                  android:fillViewport="true"/>

</LinearLayout>

I get a handle to the WebView in this line: mWebView = (WebView)findViewById(R.id.webview);
And then I load the local URL in this line       mWebView.loadUrl("http://10.0.2.2:8080/SampleWebServer/Welcome.html");

As simple as this. What this does is that it invokes the default android browser if we have links on the welcome page as shown below: (we have gone out of the WebView into a browser app)
 

If we want to be able to continue opening in the WebView, here is the piece of code that would help. Basically we are writing out own custom browser by extending the WebViewClient:

  private class WebViewSampleClient extends WebViewClient {
       
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);  
           
            return true;
        }
       
  }

Here we are telling to load the passed URL into the WebView by overriding the shoudlOverrideUrlLoading method of the WebViewClient.

After overriding the same, add another piece of code into onCreate() method:
mWebView.setWebViewClient(new WebViewSampleClient());
after mWebView.loadUrl("http://10.0.2.2:8080/SampleWebServer/Welcome.html");

Now when you click on the Second Page link, the new HTML page gets invoked within the WebView as shown below:



From here, if you press a back button, you will log out of the app, since WebView is one activity and the pages are all opened within the WebView. In order to override that behavior and you want to navigate back to the HomePage within the WebView.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
       
    }

The code is pretty self explanatory. When a back button is clicked and there is something within the WebView that we can go back it, do it within the WebView.  Here is the complete code for download.

Last but not the least, I have also added <uses-permission android:name="android.permission.INTERNET" /> into the AndroidManifest file as this app will use the internet to invoke the http based URL.

To create a Web Server and host HTML pages, please see this tutorial.

NOTE: any webserver running locally can be accessed through http protocol using the IP address 127.0.0.1 or localhost or the actual IP address which you get when you run IP address command at the command prompt. However, within the emulator, the linux kernel takes the localhost as 10.0.2.2. and hence you will see in the code above that this IP address is used.


12 comments:

  1. Link to create a Web Server and host HTML pages is missing. Can you please add it.

    ReplyDelete
  2. Nice job i realy think this could work!

    ReplyDelete
  3. Great blog article about this topic, I have been lately in your blog once or twice now. I just wanted to say my thanks for the information provided here.

    ReplyDelete
  4. hello sai geetha

    i am working on simple social application in which i have implemented galleryview in which i have shown various images available on sdcard in one screen now when user selects picture and presses save image button then selected image should be changed in his/her profile picture.

    My question is that how would be able to get that image from one screen and to change picture of user in another screen and that selected image should also inserted in database for later retrival when user logs in later. Let me tell you that my image dont come from any webservice.

    Please help me out......... Thanking You........

    ReplyDelete
  5. Can any one please post the basics of android in detail.....it will be very helpful for me.....

    ReplyDelete
  6. This is one of the advance post.I like your blog clarity.This is one of the brilliant post.

    ReplyDelete
  7. I like this blog website due to the quality of a description. I say thanks to that person who made this Wonderful Blog. Let Me Share This on My Face Book Page

    ReplyDelete
  8. mam please tell us how to tell to eclipse about tomcat..
    please tell us in detailed steps...help us

    ReplyDelete
  9. Hi there, awesome site. I thought the topics you posted on were very interesting.
    I tried to add your RSS to my feed reader and it a few. take a look at it, hopefully I can add you and follow.


    Android Developer

    ReplyDelete
  10. Hello Mam,
    I would like to invite you to visit my new blog on Android application development - http://android.programmerguru.com. The blog is targeting freshers who are interested to play around Android application development. Chip in your valuable feedback!!
    Regards,
    Android Guru
    http://android.programmerguru.com

    ReplyDelete
  11. Hi mam, I read some of your posts and it helped me as a beginner. Now am doing project on android for my final semester. A part of my app needs to fetch html source of some webpages. I have the code below and its working on emulator(API:8). but when i tried this app in ma phone(Android 4.0.4), its force closing.
    I came to know that its because ICS doesn't allow some functions in the main thread and have to use AsyncTask. I tried it but still its force closing.
    Could you help me in fetching the web content.
    This is the code used:

    public String getHtmlSource(String url)
    {

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = null;
    try {
    response = httpClient.execute(httpGet, localContext);
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    BufferedReader reader = null;
    try {
    reader = new BufferedReader(
    new InputStreamReader(
    response.getEntity().getContent()
    )
    );
    } catch (IllegalStateException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    String line = null;
    try {
    while ((line = reader.readLine()) != null){
    htmlSource += line + "\n";
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    return htmlSource;
    }

    ReplyDelete
  12. Can I get access to my webview instance outside the onCreate(Bundle SavedBundle)
    method in the same activity class ?

    ReplyDelete