Android Webview loads images from cache every second time only - android

Below is my code, I want to load webpage from cache if there's no internet connection, but when there is no connection the page loads without images on the first time and then when I try again its loads, and next time it doesn't load images. Its like its working fine every even time.
public class school extends Fragment {
private WebView webView;
public Main2Activity main2activity;
public static school newInstance() {
return new school();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_school, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
webView = (WebView)
getView().findViewById(R.id.mywebview);
main2activity = (Main2Activity) getActivity();
String url=getResources().getString(R.string.urlSchool);
//String postData = "schoolId="+main2activity.txtschoolId+"&phoneNumber="+main2activity.txtphoneNumber+"&password="+main2activity.txtpassword;
startWebView(url);
}
public void startWebView(final String url) {
int state=0;
ConnectivityManager connMgr = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
state=1;
} else {
state=0;
}
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
}
});
if(state==1) {
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}
else{
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
webView.post(new Runnable() {
#Override
public void run() {
webView.loadUrl(url);
}
});
}
}

Related

How to clear Http Basic Auth username and password from cache - android webview

I am using android webview to display a web page that requires basic authentication. I have the code that takes in username and password and allows successful login to the web page. But I want to clear the username and password from cache when the user visits the webview again. Looks like once you enter username and password for basic auth, it keeps that in cache and logs you in automatically.
I have tried
WebViewDatabase webViewDB = WebViewDatabase.getInstance(getActivity());
webViewDB.clearHttpAuthUsernamePassword();
I have also tried webview.clearFormData, webview.clearCache
But it doesn't seem to work. It logged me in automatically without the prompt to enter username and password.
Here is my full code for webview fragment.
public class WebViewFragment extends Fragment {
private static final String LOG_TAG = WebViewFragment.class.getName();
private ProgressBar progressBar;
private View footerV;
private String urlToLoad;
private int footerVisibility;
private int failureCount = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container, false);
try {
init(rootView);
} catch (Exception e) {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
}
return rootView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (footerV != null) footerV.setVisibility(footerVisibility);
}
private void init(View rootView) {
Bundle bundle = getArguments();
ConstraintLayout navBarCL = (ConstraintLayout) rootView.findViewById(R.id.navBar);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
if (bundle.getBoolean(BundleConstants.WEB_HIDE_HEADER)) {
navBarCL.setVisibility(View.GONE);
} else {
navBarCL.setVisibility(View.VISIBLE);
ImageView backButtonIV = (ImageView) rootView.findViewById(R.id.backButtonImage);
backButtonIV.setOnClickListener(view -> navigateBack());
String title = bundle.getString(BundleConstants.WEB_HEADER_TEXT);
TextView headerTextTV = (TextView) rootView.findViewById(R.id.headerText);
headerTextTV.setText(title);
}
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(getClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
super.onCloseWindow(window);
navigateBack();
}
});
footerV = getActivity().findViewById(R.id.footer);
footerVisibility = footerV.getVisibility();
if (bundle.getBoolean(BundleConstants.WEB_SHOW_FOOTER)) {
footerV.setVisibility(View.VISIBLE);
} else {
footerV.setVisibility(View.GONE);
}
urlToLoad = bundle.getString(BundleConstants.WEB_URL);
Log.d(LOG_TAG, "Opening url :" + urlToLoad);
webView.loadUrl(urlToLoad);
}
#NonNull
private WebViewClient getClient() {
WebViewDatabase webViewDB = WebViewDatabase.getInstance(getActivity());
webViewDB.clearHttpAuthUsernamePassword();
return new WebViewClient() {
#Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
++failureCount;
showProgressBar();
LoginDialog loginDialog = new LoginDialog(getContext(), getFragment(), handler, failureCount);
loginDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
hideProgressBar();
}
};
}
public void hideProgressBar() {
if (progressBar != null) progressBar.setVisibility(View.GONE);
}
public void showProgressBar() {
if (progressBar != null) progressBar.setVisibility(View.VISIBLE);
}
private WebViewFragment getFragment() {
return this;
}
public String getUrlToLoad() {
return urlToLoad;
}
protected void navigateBack() {
footerV.setVisibility(footerVisibility);
getFragmentManager().popBackStack();
}
}
Please provide some suggestions.
Try this
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.clearCache(true);

How can i block or avoid popup in webview?

the webpage have some popup ads is there any way to prevent the popup from loading when the popup loads the main site doesnt appears is there any way to load the main page with out popups and how can i add a download handler l mean the webview should support downloading .torrent file
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
private LinearLayout layoutProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
webView.setVisibility(View.GONE);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDisplayZoomControls(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
webView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(false);
super.onPageFinished(view, url);
}
public void but(View v){
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
super.onPageStarted(view, url, favicon);
}
});
if(isOnline()) {
webView.loadUrl("http://testsite.com/");
} else {
String summary = "<html><body><font color='red'>No Internet Connection</font></body></html>";
webView.loadData(summary, "text/html", null);
toast("No Internet Connection.");
}
}
private void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
public void but(View v){
webView.loadUrl("http://testsite.com/");
}
}
if the url changes then use shouldOverrideUrlLoading with some regex
so
List<String> validUrls = new LinkedList<>();
validUrls.add("https://www\\.google\\.com/*");
validUrls.add("https://www\\.facebook\\.com/*");
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isValidUrl(url)) {
return false;
}
return true;
}
private boolean isValidUrl(String url) {
for (String validUrl : validUrls) {
Pattern pattern = Pattern.compile(validUrl, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return true;
}
}
return false;
}
would match against any www.google.com or facebook.com urls
You can intercept the urls that are opened from the webview, I don't know if it would work with the popup:
WebViewClient client= new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if (url.equals("popupURL"){
return true;
}
return false;
}
}
webView.setWebViewClient(client);

How to add a progressbar to the android webview

I am trying to add a progress bar in the android webview based app. I have added following code but not working when tested.
Note: index.html have redirect tag which loads random URL. Everything is working fine except the progressbar.
MainActivity.java
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
ProgressBar Pbar;
private final int ID_MENU_EXIT = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
Pbar = (ProgressBar) findViewById(R.id.pB1);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new MyAppWebViewClient());
if (isNetworkAvailable())
mWebView.loadUrl("file:///android_asset/www/index.html");
else
mWebView.loadUrl("file:///android_asset/www/404.html");
}
public class myWebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Pbar.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//get the MenuItem reference
MenuItem item =
menu.add(Menu.NONE,ID_MENU_EXIT,Menu.NONE,R.string.exitOption);
//set the shortcut
item.setShortcut('5', 'x');
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//check selected menu item
if(item.getItemId() == ID_MENU_EXIT)
{
//close the Activity
this.finish();
return true;
}
return false;
}
}
Activity_main.xml
<ProgressBar android:id="#+id/pB1"
style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:padding="2dip">
</ProgressBar>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Well,
Use this code for Progress Bar when your WebView waiting for loading WebView. :
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="fill_parent" />
</RelativeLayout>
Activity:
public class MapActivity extends MenuActivity {
private final static String TAG = "HearingTest";
private WebView webView;
private String urlString;
private ProgressDialog progressDialog;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
context = MapActivity.this;
urlString = getString(R.string.location_url);
WebViewSettings();
LoadWebPage(urlString);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Please wait.");
//progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
public void LoadWebPage(String url){
try {
webView.loadUrl(url);
Log.d(TAG, "URL" + url + "connected");
}
catch (Exception e) {
Log.d(TAG, "URL: " + url + " couldn't connect.");
}
}
public void WebViewSettings(){
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals(urlString)) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
#Override
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
});
}
protected void DisplayProgressBar(){
}
}

Check Data Connection before open webView

i am looking for method which will check data connection is enable or disable .
if data enable then open a link in webView else toast (Data is disable).
Below my code which handle webview
public class Question_web extends Activity {
/** Called when the activity is first created. */
WebView webview;
ProgressBar progressBar;
int a;
String value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webcontent);
value = getIntent().getExtras().getString("url");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
WebView engine = (WebView) findViewById(R.id.webviews);
engine.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
Toast.makeText(getBaseContext(), "downloading", Toast.LENGTH_SHORT).show();
i.setData(Uri.parse(url));
startActivity(i);
}
});
engine.setWebViewClient(new FixedWebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progressBar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url)
{
progressBar.setVisibility(View.GONE);
}
});
engine.getSettings().setJavaScriptEnabled(true);
engine.loadUrl(value);
}
public void onBackPressed() {
WebView engine = (WebView) findViewById(R.id.webviews);
String url = engine.getUrl();
if (url.equals(value) ||
url.equals(value)) {
// exit
super.onBackPressed();
} else {
// go back a page, like normal browser
engine.goBack();
}
}
private class FixedWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
We can check to see whether a network connection is available using getActiveNetworkInfo() and isConnected() of NetworkInfo class.
This is example is available on Android doc,
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
See here and here for details.
Remember to add permissions in manifest. Follow this step by step tutorial.

How do I display ProgressDialog using Fragment

I have a Fragment activity that has a ListFragment on the left and a Fragment on the right that has a WebView. The functionality works fine but I would like to display a progress dialog showing "Loading..." while the web page finishes loading. How can I accomplish this seemingly trivial task?
Below is my code:
public class ArticleListActivity extends FragmentActivity implements
ArticleListFragment.OnArticleSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articlelist_fragment);
}
public void onArticleSelected(String contentLink) {
ArticleViewerFragment viewer = (ArticleViewerFragment) getSupportFragmentManager()
.findFragmentById(R.id.articleview_fragment);
if (viewer == null || !viewer.isInLayout()) {
Intent showContent = new Intent(getApplicationContext(),
ArticleViewerActivity.class);
showContent.setData(Uri.parse(contentLink));
startActivity(showContent);
} else {
viewer.updateUrl(contentLink);
}
}
}
Here is my FragmentActivity
public class ArticleViewerActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articleview_fragment);
Intent launchingIntent = getIntent();
String content = launchingIntent.getData().toString();
ArticleViewerFragment viewer = (ArticleViewerFragment) getSupportFragmentManager()
.findFragmentById(R.id.articleview_fragment);
viewer.updateUrl(content);
}
}
and here is my Fragment
public class ArticleViewerFragment extends Fragment {
private ProgressDialog progressBar;
private WebView viewer = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
viewer = (WebView) inflater.inflate(R.layout.webview_layout, container, false);
viewer.loadUrl("file:///android_asset/default.html");
return viewer;
}
public void updateUrl(String newUrl) {
if (viewer != null) {
viewer.loadUrl(newUrl);
}
}
}
Use this code:
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);
pd.setCancelable(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
}
});
webview.loadUrl("file:///android_asset/default.html");

Categories

Resources