0

I am making an application which uses webview to display content from a url for a logged in user.It's a very basic and small application. My problem is that the user logs out and some other user logs in, the previously loaded content(stale content) is displayed. Here's the java class:

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class WebViewActivity extends Activity {
    boolean clearHistory;
    private final String API_KEY = "apiKey";
    private final String TOKEN = "token";
    private WebView mWebView;
    String TAG="Response";
    TextView topbar;
    LinearLayout parentLayout;
    HashMap<String, String> maps = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        mWebView =(WebView)findViewById(R.id.webview1);
        mWebView.stopLoading();
        topbar=(TextView)findViewById(R.id.topbar);
        parentLayout=(LinearLayout)findViewById(R.id.parentLayout);

        SharedPreferences pref = getSharedPreferences("MyPref", 0);
        final String webviewUrl = pref.getString("webviewUrl", "");
        final String token = pref.getString("app_token", "");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);


        topbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(WebViewActivity.this);
                alertDialog.setTitle("Confirm Logout");
                alertDialog.setMessage("Are you sure you want to logout?");
                alertDialog.setIcon(R.drawable.smlalo);
                alertDialog.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {

                        SharedPreferences pref = getSharedPreferences(
                                "MyPref", 0);
                        SharedPreferences.Editor editor = pref.edit();
                        editor.putString("webviewUrl", "");
                        editor.putString("app_token", "");
                        editor.commit();
                        maps.put(TOKEN,token);
                        maps.put(API_KEY, BuildConfig.API_KEY_VALUE);
                        RestClient.getApiInterface().logout(maps).enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {
                                startActivity(new Intent(WebViewActivity.this, MainActivity.class));
                                finish();
                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {

                            }
                        });
                    }
                });

                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();
            }
        });

        final ProgressDialog progressDialog = ProgressDialog.show(WebViewActivity.this, "", "Loading...");

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onLoadResource(WebView view, String url) {
                view.clearHistory();
                super.onLoadResource(view,url);
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                progressDialog.show();
                super.onPageStarted(view, url, favicon);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "Processing webview url click...");
//                view.loadUrl(url);
                super.shouldOverrideUrlLoading(view, url);
                return false;
            }
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                view.loadUrl(request.getUrl().toString());
                super.shouldOverrideUrlLoading(view, request);
                return false;
            }
            public void onPageCommitVisible(WebView view, String url) {
                view.clearHistory();
                view.clearCache(true);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "Finished loading URL: " +url);
                topbar.setVisibility(View.VISIBLE);
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                /*if (clearHistory)
                {
                    clearHistory = false;
                    mWebView.clearHistory();
                    mWebView.clearCache(true);
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }*/
                super.onPageFinished(view, url);
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.e(TAG, "Error: " + description);
                new android.app.AlertDialog.Builder(WebViewActivity.this)
                        .setTitle("Error")
                        .setMessage(description)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                super.onReceivedError(view,errorCode,description,failingUrl);
            }
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                new android.app.AlertDialog.Builder(WebViewActivity.this)
                        .setTitle("Error")
                        .setMessage(error.getDescription())
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
                super.onReceivedError(view, request, error);
            }
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view,
                                            WebResourceRequest request, WebResourceResponse errorResponse) {

                Toast.makeText(WebViewActivity.this, "WebView Error" + errorResponse.getReasonPhrase(), Toast.LENGTH_SHORT).show();

                super.onReceivedHttpError(view, request, errorResponse);
            }

        });
        /*mWebView.loadUrl("about:blank");
        mWebView.reload();*/
        mWebView.loadUrl(webviewUrl);
//        clearHistory = true;
//        mWebView.reload();
    }

}

and here's the layout file:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:id="@+id/parentLayout"
    android:layout_height="fill_parent"
    tools:context=".SplashActivity">

    <RelativeLayout
        android:background="@color/colorPrimary"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".2"
        android:padding="10dp"
        android:id="@+id/topbarbbb">

    <ImageView
        android:text="@string/coachapp"
        android:layout_width="wrap_content"
        android:layout_centerVertical="true"
        android:src="@drawable/smlalo"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerInParent="true"
        android:id="@+id/imageView2" />
    <TextView
        android:text="Logout"
        android:textSize="12sp"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:visibility="gone"
        style="@style/Base.TextAppearance.AppCompat.Button"
        android:id="@+id/topbar"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerInParent="true">

    </TextView>

</RelativeLayout>

    <WebView android:id="@+id/webview1"
        android:layout_below="@+id/topbarbbb"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
</LinearLayout>

Also to mention, I have debugged and researched for this. The sharedpreferences are not a problem, the url being retrieved is the one I want to display. It opens properly in the browser. Have tried all the previous answers like Clear previously loaded Webview's content before loading the next one,clear webview history and this one: Destroying the WebView. None of these works for me.
I'd really appreciate some help.

Community
  • 1
  • 1
Ashish Bahl
  • 33
  • 1
  • 5
  • 2
    Please don't [delete and repost questions](http://stackoverflow.com/questions/41907714/webview-in-android-loading-stale-content). Simply editing your original post with any new information you have will bump it to the top of the active queue. – Mike M. Jan 28 '17 at 12:25
  • I understand that, but I included something I shouldn't have. Editing also won't work because there was a chance that anyone could have seen it. So I had to correct and re-post. – Ashish Bahl Jan 28 '17 at 16:43

2 Answers2

0

I figured it out. Turns out because of using javascript in the webview, it led to creation of cookies. I just had to add the code to clear cookies after successful log out. Here's what I used:

@SuppressWarnings("deprecation")
public static void clearCookies(Context context)
{

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        Log.d(C.TAG, "Using clearCookies code for API >=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
        CookieManager.getInstance().removeAllCookies(null);
        CookieManager.getInstance().flush();
    } else
    {
        Log.d(C.TAG, "Using clearCookies code for API <" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
        CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
        cookieSyncMngr.startSync();
        CookieManager cookieManager=CookieManager.getInstance();
        cookieManager.removeAllCookie();
        cookieManager.removeSessionCookie();
        cookieSyncMngr.stopSync();
        cookieSyncMngr.sync();
    }
}

Complete answer can be found here: clear cookies webview

Community
  • 1
  • 1
Ashish Bahl
  • 33
  • 1
  • 5
0

This issue can occur due to javascript cookies saved on your web view. Refresh cookies before opening your webview.