How do I display ProgressDialog using Fragment - android

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");

Related

Android App Linking not working inside the WebView

When I try with the phone browser it opens the app. but not inside of the app webview.
public class WebViewPayNowFragment extends Fragment implements AdvancedWebView.Listener {
private View rootView;
private AdvancedWebView mWebView;
private String link, tid;
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("asdajsda : "+url);
if (url != null && url.startsWith("ptcl://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
public WebViewPayNowFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
link = bundle.getString(Constants.LINK, null);
tid = bundle.getString(Constants.TRANSACTION_ID, null);
System.out.println("asdiahsdhakjshdkah : " + link);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_web_view, container, false);
mWebView = rootView.findViewById(R.id.webview);
mWebView.setListener(getActivity(), this);
mWebView.setWebViewClient(new MyBrowser());
if (link != null) {
String postData = null;
try {
postData = "TransactionID=" + URLEncoder.encode(tid, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mWebView.postUrl(link, postData.getBytes());
} else {
}
return rootView;
}
Here is my code inside the fragment.
I created a inner class extending WebViewClient. and set the setWebViewClient but im still having the problem.
Solution:
I encountered this situation myself. This is what I did:
First create a inner class and extend it with WebViewClient:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
....
}
}
then:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("ptcl://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
Lastly,
webView.setWebViewClient(new MyBrowser());
Try it, Hope it helps.

WebView save and restore state issue with postUrl

I am using the following components in my application
Activity
Fragment
WebView
Goal - I don't want to reload the webview on orientation change.
Issue - Currently I see the following error on orientation change "Webpage was not available. The webpage at https://fakeurls.org could not be loaded because net::ERR_CACHE_MISS"
Steps to Reproduce
Application was opened in device portrait mode.
Content of given URL was loaded in webview successfully
Device was turned to landscape mode
Webview shows error
Code - Android application makes a post request in a webview to url https://fakeurls.org. Below is the code for MyActivity and MyFragment class
MyFragment.java
public class MyFragment extends Fragment {
private ProgressBar mProgressBar;
private WebView mWebView;
private String mUrl = null;
private String mPostData = null;
public MyFragment() {
// Required empty public constructor
}
public static MyFragment newInstance(#android.support.annotation.NonNull String url, String postData) {
MyFragment MyFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("URL", url);
bundle.putString("POSTDATA", postData);
MyFragment.setArguments(bundle);
return MyFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
instantiateWebView(view);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
Bundle args = getArguments();
if (args == null) {
return;
}
mUrl = args.getString("URL");
mPostData = args.getString("POSTDATA");
mWebView.postUrl("https://fakeurls.org/", EncodingUtils.getBytes(mPostData, "BASE64"));
}
}
#Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
if (mWebView != null) {
mWebView.saveState(outState);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.destroy();
}
private void instantiateWebView(View view) {
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
}
}
MyActivity.java
public class MyActivity extends AppCompatActivity {
private MyFragment mMyFragment;
#NonNull
public static Intent createIntent(Context context, String url, String postData) {
return new Intent(context, MyActivity.class).putExtra("URL", url)
.putExtra("POSTDATA", postData);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_link_viewer);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mMyFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_frame);
if (mMyFragment == null) {
final String url = getIntent().getStringExtra("URL");
final String postData = getIntent().getStringExtra("POSTDATA");
mMyFragment = MyFragment.newInstance(url, postData);
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_frame, mMyFragment)
.commitNow();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void finish() {
mMyFragment.cancelTasks();
super.finish();
}
}
Please let me know how to resolve the issue and not reload the webview but retain display on orientation change. Any help is appreciated.

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);

Android Webview loads images from cache every second time only

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);
}
});
}
}

Android-Webview loadurl in next activity

I am having a WebView and i am getting data in it from a WebService.
my problem is, there are so many url's in the data i am getting and when a user click on it, then it should load on a WebViewon next page not on a browser.
How can i achieve that.? I tried shouldOverrideUrlLoading but it's not working.
Try this.
public class WebViewActivity extends Activity {
private ProgressDialog progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = ProgressDialog.show(this, "Hi", "me");
WebView webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://www.mysite.com/android.php");
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("here");
//Upadated code..........
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("NextUrl", url);
Intent i = new Intent(WebViewActivity.this, NextActivity.class);
i.putExtras(bundle);
startActivity(i);
//-----------------------
Log.i("Hi", "WEb nextttt");
return true;
}
}
}
NextActivity
public class NextActivity extends Activity {
WebView wv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Bundle bundle = getIntent().getExtras();
//Extract the data…
String url = bundle.getString("NextUrl");
Log.i("Hi", "Get next");
wv1 = (WebView) findViewById(R.id.webView1);
wv1.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
wv1.getSettings().setSupportZoom(false);
wv1.getSettings().setSupportMultipleWindows(false);
wv1.setHorizontalScrollBarEnabled(false);
wv1.setVerticalScrollBarEnabled(false);
wv1.getSettings().setUseWideViewPort(true);
wv1.getSettings().setLoadWithOverviewMode(true);
wv1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView viewx, String urlx) {
viewx.loadUrl(urlx);
return false;
}
});
try {
wv1.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources