1

I have an app in which I log in using my username and password and then I switch to a page which contains a webview. The webview recognizes this username and password and loads the content (thru sharedpreferences) , but the issue is, it loads ONLY ONCE and when i navigate to some other part of my app and come back, it shows a blank screen which eventually loads page cant be displ;ayed in the webview. Is there anyway to fix this, to keep the webview recognize the username and pass everytime u navigate to the page and load the content.Here's the code for the same: The page containing the webview :

public class AnswersFragmentWebView extends Fragment implements  MainActivity.BackPressListener<Fragment>  {

    private static final String SYMBOL = "symbol";
    private static final String SYMBOL_TYPE = "symbol_type";
    public  static final String CONTAINER_ID = "container_id";
    public static final String TAG_QUOTES_FRAGMENT_WEBVIEW = "AnswersFragmentWebView";
    public static void removeInstance(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment == null) {
            return;
        }

        final FragmentStackManager stackManager = FragmentStackManager.getInstance();
        if (stackManager.getTopFragment() instanceof AnswersFragmentWebView) {
            stackManager.popTopFragment();
        }
    }

    private boolean goingBack = false;
    private boolean onBackPressClearStack = true;
    private WebView webView;
    private final static String URL = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=dark&uuid=PADACT-002&userAgent=iphone";
    //private final static String URL = "https://www.google.com";
    SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
    private final  String USERNAME =manager.getLoginUsername(); 
    private final  String PASSWORD = manager.getDecryptedLoginPassword();
    private final static String HOST = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
    private final static String REALM = "Users Only";

    public void setOnBackPressClearStack(boolean b){
        onBackPressClearStack = b;
    }
    public boolean webViewSteppedBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();

            return true;
        }
        return false;
    }

    @Override
    public boolean backPressed(final MainActivity mainActivity) {
        if (webViewSteppedBack()) {
            return true;
        }

        if (onBackPressClearStack) {
            goingBack = true;
            FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);
        }
        return false;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId, final int inAnimation, final int outAnimation, final int popInAnimation, final int popOutAnimation) {
        final Bundle bundle = new Bundle();
        bundle.putString(AnswersFragmentWebView.SYMBOL, searchAutoSuggestSymbol);
        bundle.putString(AnswersFragmentWebView.SYMBOL_TYPE, symbolType);
        bundle.putInt(AnswersFragmentWebView.CONTAINER_ID, containerViewId);
        fragment.setArguments(bundle);

        FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, containerViewId);
        fragmentInfo.setAnimation(inAnimation, outAnimation);
        fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
        fragmentInfo.setFragmentTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.nav_option_quotes));
        FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);

        return fragment;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId, R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }


    private static void clearWebView(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment != null && fragment instanceof AnswersFragmentWebView) {
            ((AnswersFragmentWebView)fragment).clearWebView();
        }
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container);
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType, int containerViewId) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final FragmentManager manager, final String searchAutoSuggestSymbol,  final String symbolType, int containerViewId) {
        AnswersFragmentWebView fragment =  __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
        fragment.setOnBackPressClearStack(false);
        return fragment;
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final AnswersFragmentWebView fragment, final FragmentManager manager, final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        fragment.setOnBackPressClearStack(false);
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceForSearch(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        AnswersFragmentWebView fragment = __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container, R.anim.no_animation, R.anim.slide_out_to_right, R.anim.slide_in_from_right, R.anim.slide_out_to_right);
        return fragment;
    }

    public void clearWebView() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        }
    }



    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (goingBack) {
            return null;
        }
        final MainActivity activity = (MainActivity) getActivity();

        activity.setBackPressListener(this);


        final View view = inflater.inflate(R.layout.fragment_search_answers, container, false);

        if (!NetworkUtils.isOnline()) {
            LayoutUtils.showNoResult(view, R.id.quotes_webview_container);
            return view;

        }

        // setup webview
        webView = (WebView) view.findViewById(R.id.webview);


        webView.setVisibility(View.VISIBLE);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setBackgroundColor(0);
        webView.requestFocus();
        webView.reload();
        webView.getSettings().setSavePassword(true);
        webView.getSettings().setSaveFormData(true);
        webView.getSettings().getSaveFormData();
        webView.getSettings().getSavePassword();
        //WebViewDatabase.getInstance(getActivity()).clearHttpAuthUsernamePassword();
        WebViewDatabase.getInstance(getActivity()).hasHttpAuthUsernamePassword();
        webView.setHttpAuthUsernamePassword(HOST, REALM, USERNAME, PASSWORD);
        webView.setWebViewClient(new AnswersWebView(this,webView));
        webView.loadUrl(URL);



        return view;
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getArguments().getString(AnswersFragmentWebView.SYMBOL);
    }


}

The webview client:

public class AnswersWebView extends WebViewClient {

    private String loginCookie;
    private Context mContext;
    private WebView mWebView;

    public AnswersWebView(AnswersFragmentWebView answersFragmentWebView, WebView webview) {
        super();

        //mContext = answersFragmentWebView;
        mWebView = webview;
    }

    @Override
    public void onPageStarted( WebView view, String url, Bitmap favicon ) {
    }

    @Override
    public void onPageFinished( WebView view, String url ) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(url, loginCookie);
    }

    @Override
    public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
        Toast.makeText(view.getContext(), "ÉyÅ[ÉWì«Ç›çûÇ›ÉGÉâÅ[", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLoadResource( WebView view, String url ){
        CookieManager cookieManager = CookieManager.getInstance();
        loginCookie = cookieManager.getCookie(url);
    }

    @Override
    public boolean shouldOverrideUrlLoading( WebView view, String url ) {
        return false;
    }

    @Override
    public void onReceivedSslError( WebView view, SslErrorHandler handler, SslError error ) {
        handler.proceed();
    }

    @Override
    public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){
        SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
        String userName = manager.getLoginUsername();
        String userPass = manager.getDecryptedLoginPassword();

        if (handler.useHttpAuthUsernamePassword() && view != null) {
            String[] haup = view.getHttpAuthUsernamePassword(host, realm);
            if (haup != null && haup.length == 2) {
                userName = haup[0];
                userPass = haup[1];
            }
        }

        if (userName != null && userPass != null) {
            handler.proceed(userName, userPass);
        }
        else {
            showHttpAuthDialog(handler, host, realm, null, null, null);
        }
    }

    private void showHttpAuthDialog( final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password ) {
        LinearLayout llayout = new LinearLayout((Activity)mContext);
        final TextView textview1 = new TextView((Activity)mContext);
        final EditText edittext1 = new EditText((Activity)mContext);
        final TextView textview2 = new TextView((Activity)mContext);
        final EditText edittext2 = new EditText((Activity)mContext);
        llayout.setOrientation(LinearLayout.VERTICAL);
        textview1.setText("username:");
        textview2.setText("password:");
        llayout.addView(textview1);
        llayout.addView(edittext1);
        llayout.addView(textview2);
        llayout.addView(edittext2);

        final Builder mHttpAuthDialog = new AlertDialog.Builder((Activity)mContext);
        mHttpAuthDialog.setTitle("Basic Authentication")
        .setView(llayout)
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText etUserName = edittext1;
                String userName = etUserName.getText().toString();
                EditText etUserPass = edittext2;
                String userPass = etUserPass.getText().toString();

                mWebView.setHttpAuthUsernamePassword(host, realm, name, password);

                handler.proceed(userName, userPass);
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                handler.cancel();
            }
        })
        .create().show();
    }

}

Thanks! Justin

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
  • There seem to be two distinct times in the code when you exercise HTTP authentication. When the webview is set up, you provide credentials; and also credentials are provided in `onReceivedHttpAuthRequest`. Could you log which is active (maybe both) on first run (which works) and on subsequent runs (which fail) please? – Neil Townsend Aug 26 '13 at 16:20
  • showHttpAuthDialog is completely useless function, can comment it out. However, onReceivedHttpAuthRequest is used to authenticate the page. and the one in the previous class is used to receive the credentials and hostname upon first login.What I am trying to do is I want it to remember these credentials and URL when I switch back and forth between screens.However it seems like it even forgets the URL and "page cannot be displayed" error shows up. Wonder what is missing. –  Aug 26 '13 at 16:38
  • Does `onReceivedHttpAuthRequest` get called when you come back? – Neil Townsend Aug 26 '13 at 19:01
  • yeah , but it still displays page cannot be displayed after a blank –  Aug 26 '13 at 19:13
  • Why dont you store the instance of the WebView client in a static variable and when you need to load the content use that variable to load the content manually or create a session http://stackoverflow.com/questions/11224454/android-share-session-between-webview-and-httpclient – Girish Nair Aug 30 '13 at 12:09

4 Answers4

1

Ok.

you have to add the username/password in the onResume instead of OnCreate

like explain in this Document http://developer.android.com/reference/android/app/Activity.html

  • still no luck, wonder why it isn't remembering the password or the page url the second time –  Aug 22 '13 at 16:35
  • In fact it is the fragment lifecycle here : http://developer.android.com/guide/components/fragments.html. I don't know if the fragment needs a setRetainInstance(true) in the onCreate. But with this webview, i don't think its needed ... – Solostaran14 Aug 29 '13 at 12:58
0

Move the SharedPref code into onClick and report here...

user2606414
  • 718
  • 2
  • 7
  • 13
  • can you please explain programatically? I am unsure what report here means –  Aug 26 '13 at 14:36
0

This is the problem of cookie management.

CASE :~ 1 IF you are visiting other web site (facebook,gmail,etc.) To solve this you have to maintain cookie files which was coming through vebView.

& send back it to next time new page request.

CASE :~ 2 if you are visiting your own web site then there is one another problem solution is you can check on server side (in your web site) device info & compare it to that device info which was at login time.

or you can send hidden data in hidden tag & validate it in your app.

Pulah Nandha
  • 774
  • 4
  • 23
0

In my previous project, I have faces some similar problem. I solve there in this approach - instanciate the blank/default layout in onCreate, then load the configuration from sharedPref and set the parameter value for the layout inside onResume. and before leaving the page save the configure changes(if happens) inside onPause. If this looks good to you can check it in your case.

Pradip
  • 3,189
  • 3
  • 22
  • 27
  • 1 vote up for taking the time to answer :).Please try put this question, if you have any clue :http://stackoverflow.com/questions/18343590/how-do-i-shift-the-include-layout-to-the-bottom-of-the-view/18344303?noredirect=1#comment26937643_18344303 –  Aug 30 '13 at 15:49