EzDevInfo.com

webview interview questions

Top webview frequently asked interview questions

How to listen for a Webview finishing loading a URL in Android?

I have a webview that is loading a page from the Internet. I want to show a progressbar until the loading is complete.

How do I listen for the completion of page loading of a [WebView][1]?


Source: (StackOverflow)

What do setUseWideViewPort() and setLoadWithOverviewMode() precisely do?

I am disappointed at the lack of documentation of WebView and related stuff.

(unless you think the following is propert documetation)

public void setLoadWithOverviewMode (boolean overview)

Set whether the WebView loads a page with overview mode

and:

public synchronized void setUseWideViewPort (boolean use)

Tell the WebView to use the wide viewport

So: What is "Overview mode" ? what is "Wide viewport" ?

ps: I tried to look for webkit related docs but could not find it.


Source: (StackOverflow)

Advertisements

detect ipad/iphone webview via javascript

Is there a way to differ via javascript if the website runs inside the ipad safari or inside an application WebView?


Source: (StackOverflow)

How to check if a file exists in Documents folder?

I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.

Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.

How I can do that? With NSFileManager I can't get outside of mainBundle..


Source: (StackOverflow)

Android Webview - Completely Clear the Cache

I have a WebView in one of my Activities, and when it loads a webpage, the page gathers some background data from Facebook.

What I'm seeing though, is the page displayed in the application is the same on each time the app is opened and refreshed.

I've tried setting the WebView not to use cache and clear the cache and history of the WebView.

I've also followed the suggestion here: How to empty cache for WebView?

But none of this works, does anyone have any ideas of I can overcome this problem because it is a vital part of my application.

    mWebView.setWebChromeClient(new WebChromeClient()
    {
           public void onProgressChanged(WebView view, int progress)
           {
               if(progress >= 100)
               {
                   mProgressBar.setVisibility(ProgressBar.INVISIBLE);
               }
               else
               {
                   mProgressBar.setVisibility(ProgressBar.VISIBLE);
               }
           }
    });
    mWebView.setWebViewClient(new SignInFBWebViewClient(mUIHandler));
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.clearHistory();
    mWebView.clearFormData();
    mWebView.clearCache(true);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    Time time = new Time();
    time.setToNow();

    mWebView.loadUrl(mSocialProxy.getSignInURL()+"?time="+time.format("%Y%m%d%H%M%S"));

So I implemented the first suggestion (Although changed the code to be recursive)

private void clearApplicationCache()
{
    File dir = getCacheDir();

    if(dir!= null && dir.isDirectory())
    {
        try
        {
            ArrayList<File> stack = new ArrayList<File>();

            // Initialise the list
            File[] children = dir.listFiles();
            for(File child:children)
            {
                stack.add(child);
            }

            while(stack.size() > 0)
            {
                Log.v(TAG, LOG_START+"Clearing the stack - " + stack.size());
                File f = stack.get(stack.size() - 1);
                if(f.isDirectory() == true)
                {
                    boolean empty = f.delete();

                    if(empty == false)
                    {
                        File[] files = f.listFiles();
                        if(files.length != 0)
                        {
                            for(File tmp:files)
                            {
                                stack.add(tmp);
                            }
                        }
                    }
                    else
                    {
                        stack.remove(stack.size() - 1);
                    }
                }
                else
                {
                    f.delete();
                    stack.remove(stack.size() - 1);
                }
            }
        }
        catch(Exception e)
        {
            Log.e(TAG, LOG_START+"Failed to clean the cache");
        }
    }
}

However this still hasn't changed what the page is displaying. On my desktop browser I am getting different html code to the web page produced in the WebView so I know the WebView must be caching somewhere.

On the IRC channel I was pointed to a fix to remove caching from a URL Connection but can't see how to apply it to a WebView yet.

http://www.androidsnippets.org/snippets/45/

If I delete my application and re-install it, I can get the webpage back up to date, i.e. a non-cached version. The main problem is the changes are made to links in the webpage, so the front end of the webpage is completely unchanged.


Source: (StackOverflow)

How to enable zoom controls and pinch zoom in a WebView?

The default Browser app for Android shows zoom controls when you're scrolling and also allows for pinch zooming. How can I enable this feature for my own Webview?

I've tried:

webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);

but neither of the features get enabled as a result. Btw I've set a WebChromeClient and a WebViewClient for the Webview if that makes a difference.

Thanks!


Source: (StackOverflow)

Android. WebView and loadData

It's possible to use following method for content's setting of a web-view loadData(String data, String mimeType, String encoding)

How to handle the problem with unknown encoding of html data?!

Is there a list of encodings?!

I know from my college that in my case html comes from DB and is encoded with latin-1. I try to set encoding parameter to latin-1, to ISO-8859-1 / iso-8859-1, but still have problem with displaying of special signs like ä, ö, ü.

I'll be very thankful for any advice.


Source: (StackOverflow)

Android Webview - Webpage should fit the device screen

I have tried the following to fit the webpage based on the device screen size.

mWebview.setInitialScale(30);

and then set the metadata viewport

<meta name="viewport" content="width=320, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0;"/>
<meta name="viewport" content="width=device-width, target-densityDpi=medium-dpi"/>

But nothing works, webpage is not fixed to the device screen size.

Can anyone tell me how to get this?


Source: (StackOverflow)

Android webview & localStorage

I have a problem with a webview which may access to the localStorage by an HTML5 app. The test.html file informs me that local storage is'nt supported by my browser (ie. the webview). If you have any suggestion.. Please take a look at my code :

package com.test.HelloWebView; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.webkit.WebChromeClient; 
import android.webkit.WebSettings; 
import android.webkit.WebStorage; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
public class HelloWebView extends Activity { 
WebView webview; 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    webview = (WebView) findViewById(R.id.webview); 
    webview.getSettings().setJavaScriptEnabled(true); 
    webview.setWebViewClient(new HelloWebViewClient()); 
    webview.loadUrl("file:///android_asset/test.html"); 
    WebSettings settings = webview.getSettings(); 
    settings.setJavaScriptEnabled(true); 
    settings.setDatabaseEnabled(true); 
    String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
    settings.setDatabasePath(databasePath);
    webview.setWebChromeClient(new WebChromeClient() { 
    public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { 
            quotaUpdater.updateQuota(5 * 1024 * 1024); 
        } 
    }); 
} 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { 
        webview.goBack(); 
        return true; 
    } 
    return super.onKeyDown(keyCode, event); 
} 
private class HelloWebViewClient extends WebViewClient { 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
        view.loadUrl(url); 
        return true; 
    } 
}
} 

Thanks, Thomas.


Source: (StackOverflow)

Android WebView handling orientation changes

Just started working with the webview. The issue is performance following rotation. The WebView has to reload the page, which can be a bit tedious.

What's the best of of handling an orientation change without reloading the page from source each time?


Source: (StackOverflow)

Android WebView style background-color:transparent ignored on android 2.2

I'm struggling to create a WebView with transparent background.

webView.setBackgroundColor(0x00FFFFFF);
webView.setBackgroundDrawable(myDrawable);

Then I load a html page with

<body style="background-color:transparent;" ...

The background color of the WebView is transparent but as soon as the page is loaded, it's overwritten by a black background from the html page. This only happens on android 2.2, it works on android 2.1.

So is there something to add in the html page code to make it really transparent ?


Source: (StackOverflow)

Android Calling JavaScript functions in WebView

I am trying to call some javascript functions sitting in an html page running inside an android webview. Pretty simple what the code tries to do below - from the android app, call a javascript function with a test message, which inturn calls a java function back in the android app that displays test message via toast.

The javascript function looks like:

function testEcho(message){
     window.JSInterface.doEchoTest(message);
}

From the WebView, I have tried calling the javascript the following ways with no luck:

myWebView.loadUrl("javascript:testEcho(Hello World!)");
mWebView.loadUrl("javascript:(function () { " + "testEcho(Hello World!);" + "})()");

I did enable javascript on the WebView

myWebView.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
myWebView.addJavascriptInterface(myJSInterface, "JSInterface"); 

And heres the Java Class

public class JSInterface{

private WebView mAppView;
public JSInterface  (WebView appView) {
        this.mAppView = appView;
    }

    public void doEchoTest(String echo){
        Toast toast = Toast.makeText(mAppView.getContext(), echo, Toast.LENGTH_SHORT);
        toast.show();
    }
}

I've spent a lot of time googling around to see what I may be doing wrong. All examples I have found use this approach. Does anyone see something wrong here?

Edit: There are several other external javascript files being referenced & used in the html, could they be the issue?


Source: (StackOverflow)

jQuery get the location of an element relative to window

Given an HTML DOM ID, how to get an element's position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent since the element may be inside an iframe or some other elements. I need to get the screen location of the element's rectangle (as in position and dimension) as it is currently being displayed. Negative values are acceptable if the element is currently off-screen (have been scrolled off).

This is for an iPad (WebKit / WebView) application. Whenever the user taps on a special link in an UIWebView, I am supposed to open a popover view that displays further information about the link. The popover view needs to display an arrow that points back to the part of the screen that invokes it.


Source: (StackOverflow)

WebView and HTML5

I'm piecing together a cheapo app that amongst other things "frames" some of our websites... Pretty simple with the WebViewClient... until I hit the video.

The video is done as HTML5 elements, and these work fine and dandy on Chrome, iPhones, and now that we fixed the encoding issues it works great on Android... in the native browser.

Now the rub: WebView doesn't like it. At all. I can click on the poster image, and nothing happens.

Googling, I found http://www.codelark.com/2010/05/12/android-viewing-video-from-embedded-webview/ which is close, but seems to be based on a 'link' (as in a href...) instead of a video element. (onDownloadListener does not appear to get invoked on video elements...)

I also see references to overriding onShowCustomView, but that seems to not get called on video elements... nor does shouldOverrideUrlLoading..

I would rather not get into "pull xml from the server, reformat it in the app".. by keeping the story layout on the server, I can control the content a bit better without forcing people to keep updating an app. So if I can convince WebView to handle tags like the native browser, that would be best.

I'm clearly missing something obvious.. but I have no clue what.


Source: (StackOverflow)

Favourite content is not shown correctly on webview

I'm developing a language dictionary app. I save the favourite word into Preference. The Favourite content in the XML file looks like the following:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
  <map>
    <string name="history">
      dict_name::160170::hi,dict_name::157140::he-man,dict_name::184774::jet,dict_name::34527::black
    </string>
    <string name="waitingTime">
      0
    </string>
    <boolean name="saveFavourite" value="true" />
    <string name="defaultDictionary">
      dict_name
    </string>
    <string name="favourite">
      dict_name::149271::go,dict_name::25481::back,dict_name::184774::jet
    </string>
    <boolean name="saveHistory" value="true" />
  </map>

I use the following code to load the Favourite content into the webview:

public class User extends Activity {
    private static final String FAVOURITE_TAG = "[MyDict - FavouriteView] ";
    private static final String CONTENT_TAG = null;

    private ListView mLSTFavourite = null;
    private ArrayList<String> lstDict = null;
    private ArrayList<Integer> lstId = null;
    private ArrayList<String> mWordFavourite = null;
    private ArrayAdapter<String> aptList = null;
    private SharedPreferences prefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.favourite);
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        if (prefs.getBoolean("saveFavourite", true)) {
            String strFavourite = prefs.getString("favourite", "");
            Log.i(FAVOURITE_TAG, "Favourite loaded");
            if (strFavourite != null && !strFavourite.equals("")) {
                mWordFavourite = new ArrayList<String>(Arrays.asList(strFavourite.split(",")));
            } else {
                mWordFavourite = new ArrayList<String>();
            }
        } else {
            mWordFavourite = new ArrayList<String>();
        }

        Log.d(FAVOURITE_TAG, "mWordFavourite = " + mWordFavourite.size());
        mLSTFavourite = (ListView) findViewById(R.id.lstFavourite);

        ImageButton btnClear = (ImageButton) findViewById(R.id.btnClear);
        ImageButton btnBackToContent = (ImageButton) findViewById(R.id.btnBackToContent);

        if (lstDict == null) {
            lstDict = new ArrayList<String>();
            lstId = new ArrayList<Integer>();
            aptList = new ArrayAdapter<String>(getApplicationContext(), R.layout.customlist);
        }
        lstDict.clear();
        lstId.clear();
        aptList.clear();

        if (mWordFavourite != null && mWordFavourite.size() > 0) {
            try {
                for (int i = 0; i < mWordFavourite.size(); i++) {
                    Log.i(FAVOURITE_TAG, "item = " + mWordFavourite.get(i));
                    String arrPart[] = mWordFavourite.get(i).split("::");
                    if (arrPart.length == 3) {
                        Log.i(CONTENT_TAG, "loaded content " + arrPart.length + ", wordId = " + arrPart[1]);
                        // Log.i(CONTENT_TAG, "loaded 0");
                        lstDict.add(i, arrPart[0]);
                        // Log.i(CONTENT_TAG, "loaded 1");
                        lstId.add(i, Integer.parseInt(arrPart[1]));
                        // Log.i(CONTENT_TAG, "loaded 2");
                        aptList.add(arrPart[2]);
                    } else {
                        Log.i(FAVOURITE_TAG, "Wrong entry: " + mWordFavourite.get(i));
                    }
                }
            } catch (Exception ex) {
                Log.i(FAVOURITE_TAG, "Wrong entry found!");
            }
        }
        // Log.i(CONTENT_TAG,"Adapter size = " + aptList.getCount());
        // assign result return
        mLSTFavourite.setAdapter(aptList);
        mLSTFavourite.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
                        // mEDWord.setText(mAdapter.getItem(arg2));
                        Intent i = new Intent();
                        i.putExtra("dict", lstDict.get(arg2));
                        i.putExtra("wordId", lstId.get(arg2));
                        setResult(RESULT_OK, i);
                        finish();
                    }
                });
        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mWordFavourite.clear();
                aptList.clear();
                mLSTFavourite.setAdapter(aptList);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("favourite", "");
                editor.commit();
                setResult(RESULT_OK);
                finish();
            }
        });

        btnBackToContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });
    }
}

The Favourite content is successfully loaded. The favourite words are listed in the webview. But the problem is that it only shows the definition of the latest word added to the Favourite regardless of what word is chosen. For example:

word1
word2
word3

Despite word1 and/or word2 is selected for meaning, the definition of the last word, which is word3, is always shown. My purpose is to display the definition of word1 when word1 is selected, and the definition of word2 when word2 is selected, and so on and so forth. I save my dictionary data in SQLite database.

Can anybody there help to solve this problem.


Source: (StackOverflow)