140

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.

NickUnuchek
  • 11,794
  • 12
  • 98
  • 138
Matt Gaunt
  • 9,434
  • 3
  • 36
  • 57

16 Answers16

233

I found an even elegant and simple solution to clearing cache

WebView obj;
obj.clearCache(true);

http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29

I have been trying to figure out the way to clear the cache, but all we could do from the above mentioned methods was remove the local files, but it never clean the RAM.

The API clearCache, frees up the RAM used by the webview and hence mandates that the webpage be loaded again.

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
Akshat
  • 4,515
  • 4
  • 27
  • 28
50

The edited code snippet above posted by Gaunt Face contains an error in that if a directory fails to delete because one of its files cannot be deleted, the code will keep retrying in an infinite loop. I rewrote it to be truly recursive, and added a numDays parameter so you can control how old the files must be that are pruned:

//helper method for clearCache() , recursive
//returns number of deleted files
static int clearCacheFolder(final File dir, final int numDays) {

    int deletedFiles = 0;
    if (dir!= null && dir.isDirectory()) {
        try {
            for (File child:dir.listFiles()) {

                //first delete subdirectories recursively
                if (child.isDirectory()) {
                    deletedFiles += clearCacheFolder(child, numDays);
                }

                //then delete the files and subdirectories in this dir
                //only empty directories can be deleted, so subdirs have been done first
                if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
                    if (child.delete()) {
                        deletedFiles++;
                    }
                }
            }
        }
        catch(Exception e) {
            Log.e(TAG, String.format("Failed to clean the cache, error %s", e.getMessage()));
        }
    }
    return deletedFiles;
}

/*
 * Delete the files older than numDays days from the application cache
 * 0 means all files.
 */
public static void clearCache(final Context context, final int numDays) {
    Log.i(TAG, String.format("Starting cache prune, deleting files older than %d days", numDays));
    int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
    Log.i(TAG, String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
}

Hopefully of use to other people :)

markjan
  • 685
  • 6
  • 9
49

I found the fix you were looking for:

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");

For some reason Android makes a bad cache of the url which it keeps returning by accident instead of the new data you need. Sure, you could just delete the entries from the DB but in my case I am only trying to access one URL so blowing away the whole DB is easier.

And don't worry, these DBs are just associated with your app so you aren't clearing the cache of the whole phone.

Ziem
  • 6,579
  • 8
  • 53
  • 86
Scott
  • 2,593
  • 1
  • 22
  • 23
  • Thanks, this is an incredibly neat trick. It deserves to be more widely known. – Philip Sheard May 21 '11 at 12:54
  • 2
    This throws a nasty exception in honeycomb: 06-14 22:33:34.349: ERROR/SQLiteDatabase(20382): Failed to open the database. closing it. 06-14 22:33:34.349: ERROR/SQLiteDatabase(20382): android.database.sqlite.SQLiteDiskIOException: disk I/O error 06-14 22:33:34.349: ERROR/SQLiteDatabase(20382): at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method) – Rafael Sanches Jun 14 '11 at 22:35
  • Cheers Rafael, I would like to think this is because the original issue has been resolved in Honeycomb. Does anyone know if this is the case? – Scott Jun 15 '11 at 00:21
  • just put 2 lines in onBackpress() or back button no history remain in back stack thanks saved lots of time. – CrazyMind Dec 21 '16 at 12:14
  • This does not seem to clear JS cache, only HTML.. is that the case? – Immanuel Oct 14 '22 at 17:11
41

To clear all the webview caches while you signOUT form your APP:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookie();

For Lollipop and above:

CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookies(ValueCallback);
Kingston
  • 474
  • 5
  • 14
amalBit
  • 12,041
  • 6
  • 77
  • 94
25

To clear cookie and cache from Webview,

    // Clear all the Application Cache, Web SQL Database and the HTML5 Web Storage
    WebStorage.getInstance().deleteAllData();

    // Clear all the cookies
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();

    webView.clearCache(true);
    webView.clearFormData();
    webView.clearHistory();
    webView.clearSslPreferences();
Srinivasan
  • 4,481
  • 3
  • 28
  • 36
6

The only solution that works for me

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();
} 
Ketan Ramani
  • 4,874
  • 37
  • 42
3

This should clear your applications cache which should be where your webview cache is

File dir = getActivity().getCacheDir();

if (dir != null && dir.isDirectory()) {
    try {
        File[] children = dir.listFiles();
        if (children.length > 0) {
            for (int i = 0; i < children.length; i++) {
                File[] temp = children[i].listFiles();
                for (int x = 0; x < temp.length; x++) {
                    temp[x].delete();
                }
            }
        }
    } catch (Exception e) {
        Log.e("Cache", "failed cache clean");
    }
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
jqpubliq
  • 11,874
  • 2
  • 34
  • 26
3
webView.clearCache(true)
appFormWebView.clearFormData()
appFormWebView.clearHistory()
appFormWebView.clearSslPreferences()
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
WebStorage.getInstance().deleteAllData()
2

Simply using below code in Kotlin works for me

WebView(applicationContext).clearCache(true)
Ercan
  • 2,601
  • 22
  • 23
1
CookieSyncManager.createInstance(this);         
CookieManager cookieManager = CookieManager.getInstance();        
cookieManager.removeAllCookie();
WaqasArshad
  • 237
  • 1
  • 3
  • 12
1
CookieSyncManager.createInstance(this);    
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.removeAllCookie();

It can clear google account in my webview

1

Previous code has been deprecated. So, you can try this one in Kotlin base android projects:

CookieManager.getInstance().removeAllCookies {  
   // Do your work here.
}
canerkaseler
  • 6,204
  • 45
  • 38
  • 1
    I use this method to solve my problem. I see many answers containing "CookieManager.getInstance().flush()". It is not needed, because flush() write cookie to database in fact. If you want to clear all db, you can try WebStorage.getInstance().deleteAllData(); but in most cases it is not needed – JeckOnly Apr 27 '23 at 02:07
0

Make sure you use below method for the form data not be displayed as autopop when clicked on input fields.

getSettings().setSaveFormData(false);
Aduait Pokhriyal
  • 1,529
  • 14
  • 30
Raghu
  • 51
  • 2
0

To clear the history, simply do:

this.appView.clearHistory();

Source: http://developer.android.com/reference/android/webkit/WebView.html

Aduait Pokhriyal
  • 1,529
  • 14
  • 30
Alan CN
  • 1,467
  • 1
  • 13
  • 13
0
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db")

Did the trick

Joundill
  • 6,828
  • 12
  • 36
  • 50
Terre
  • 29
  • 9
0

to completely clear the cache in kotlin you can use:

context.cacheDir.deleteRecursively()

Just in case someone needs the kotlin code (:

Iskandir
  • 937
  • 1
  • 9
  • 21