WebView error in fragment - android

This code is working fine in Activity but same code doesn't work in Fragments. It gets error of ProgressDialog which can't be applied and another one is can't resolve method onBackPressed()
public class FacebookFragment extends Fragment {
private WebView webView;
public FacebookFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_facebook, container, false);
webView = (WebView)rootView. findViewById(R.id.webView1);
startWebView("https://betanews.in/");
return rootView;
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(FacebookFragment.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
}
// Open previous opened link from history on webview when back button pressed
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}

replace this line progressDialog = new ProgressDialog(FacebookFragment.this); with progressDialog = new ProgressDialog(getActivity());
we need to pass a context to the ProgressDialog constructor, FacebookFragment.this will return object of Fragment, but the expected object is of Activity, you can get the Context of holding Activity.
onBackPressed() is method from class Activity , but here you are extending Fragment
override this method where you actually inflates this fragment. and check for the instance id of the fragment you needed, then do the stuff.
hope it help you

Related

Android keyboard invisible

I have an activity A which has a button. On clicking this button, activity B launches. Activity B has WebView inside an xml layout which loads HTML page stored locally on the device. The whole webpage consist of several CSS(heavy material) and jsons(large in size). At this time the RAM usage is around 90MB. HTML have input fields both text and numeric in it. The problem is after opening and closing the webview 3-4 times, when I click on the input field the keyboard become invisible.
Click here for screenshot
This is my activity code.
public class LaunchActivity extends Activity {
WebView webView;
private final int FILECHOOSER_RESULTCODE = 1;
private Uri mCapturedImageURI = null;
public String mCameraPhotoPath;
String webViewUrl;
public String mMediaType;
public int flag = 0;
public File imageStorageDir;
Bundle bundle;
String mode;
public ProgressDialog progDailog;
int questionToBeLaunch;
Project project;
public void onBackPressed() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launch_survey);
// getting data from intent and creating the url to load.
webView = (WebView) findViewById(R.id.webView1);
setWebViewProperties();
Map<String, String> header = new HashMap<String, String>(2);
header.put("Pragma", "no-cache");
header.put("Cache-Control", "no-cache");
webView.loadUrl(webViewUrl, header);
}
public void setWebViewProperties(){
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
// Javascript enabled on webview
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.addJavascriptInterface(jsInterface, "interface");
// Other webview options
webView.getSettings().setLoadWithOverviewMode(true);
//webView.getSettings().setUseWideViewPort(true);
//Other webview settings
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setSupportZoom(true);
progDailog = new ProgressDialog(LaunchSurvey.this);
//Load url in webview
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progDailog.setMessage("Loading...");
progDailog.setCanceledOnTouchOutside(false);
progDailog.setCancelable(false);
progDailog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.clearCache(true);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
// webView.setOnTouchListener(null);
webView.removeAllViews();
webView.clearCache(true);
webView.clearHistory();
// clearCache(getApplicationContext());
webView.destroy();
webView = null;
}
}
After struggling for many days, finally I figured out the root cause of your problem. It is probably because of the heavy javascript code that webview needs to parse. Try to lighten it a bit and you are all set, the numeric keypad won't get invisible.

“loading” message when launching Android app doesn't disappear

I would like to show a "loading..." message when starting my Android app. It should appear for exactly 3 seconds.
I tried to achieve this with the code below, but the problem is that it keeps displaying the "Loading..." message. It disappears when I click on the background, but it's definitely not what I had in mind when using this code.
Can someone please help me out with this one?
public class MainActivity extends Activity {
//private Button button;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://example.com");
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
//If you will not use this method url links are open in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient() {
//Show loader on url load
ProgressDialog progressDialog;
public void onProgressChanged(WebView view, int progress) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
if(progress==3000 && progressDialog.isShowing()){
progressDialog.dismiss();
progressDialog = null;
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
//Load url in webview
webView.loadUrl(url);
}
// Open previous opened link from history on webview when back button pressed
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
maybe you can do something like this:
progressDialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
}, 3000);
This will dismiss the progress dialog after 3 seconds automatically

Closing a webview on url detection

I have a webview in my activity and I need to close it once the final url is being loaded.
I tried destroy() in the custom Client but that wasn't allowed, finish() closed the entire app, back key closed the app too. Is there a way to just remove the webview and return to the rest of activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
WebView webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(myUrl);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.matches(PATTERN)) {
Matcher matcher = Pattern.compile(PATTERN).matcher(url);
result = matcher.matches() ? matcher.group(1) : null;
// webview.destroy(); //doesn't work as destroy cannot be called from here
return false;
}
view.loadUrl(url);
return true;
}
}
You can just remove webView from parent by:
ViewGroup vg = (ViewGroup)webView.getParent();
if(vg != null)
vg.removeView(webView);
Or try just webView.setVisibility(View.GONE);

Preventing WebView from closing when clicked outside the webview

In my app, I load a WebView where users enter username/password and I don't want the webview to close should the users accidentally click outside of the webview since the page will have to make another network call to load this webview.
I know this can be done for Dialog (like so: dialog.setCanceledOnTouchOutside(true);) but couldn't find similar mechanism for webview.
Thanks!
Here is the code:
#SuppressLint("SetJavaScriptEnabled")
public class LoginDialogFragment extends DialogFragment {
private static final String TAG = LoginDialogFragment.class.getSimpleName();
View mainView = null;
WebView webView = null;
OnLoginSucceeded loginSucceeded = null;
ProgressBar progressBar = null;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.webview, container, false);
if (getDialog() != null)
getDialog().setTitle(getString(R.string.login));
webView = (WebView) mainView.findViewById(R.id.webview);
//display the progress bar
progressBar = (ProgressBar) mainView.findViewById(R.id.user_profile_loading_progress);
progressBar.setVisibility(View.VISIBLE);
//turn caching off
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
});
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i(TAG, "URL received in onCreateView's onPageStarted is: " + url);
new HandleRequest().execute(url);
}
#Override
public void onPageFinished(WebView view, String url) {
}
});
new FetchLoginFormTask().execute();
return mainView;
}
I found my answer here and I just used getDialog().setCanceledOnTouchOutside(false); ensuring that when back key is clicked, the webview is dismissed.
Try with override the method:
#Override
public void setCancelable(boolean cancelable) {
super.setCancelable(false);
}
If your issue is not getting solved by this then please put some code so i can help you.
Feel free for comment.

Webview shouldoverrideurlloading doesn't work

I have this code in my app:
public class Home extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ProgressDialog progressBar;
if(isOnline()){
WebView webView = (WebView) findViewById(R.id.home_web);
webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg)));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere));
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView.loadUrl("http://www.mysite.com/android.php");
}else{
Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("here");
if (Uri.parse(url).getHost().equals("mysite.com")) {
// 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;
}
}
public boolean isOnline(){
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni==null){
return false;
}
return ni.isConnected();
}
}
The shouldOverrideUrlLoading doesn't work, neither print the system.out, it seems to be never called. How can I repair this? I need to open all the link (except the main page www.mysite.com/iphone.php) in the default browser
You've set the WebViewClient twice, thus replacing the first one (shouldOverrideUrlLoading) with the second one (onPageFinished). Combine the two for it to work:
public class Home extends Activity{
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(isOnline()){
progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere));
WebView webView = (WebView) findViewById(R.id.home_web);
webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg)));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://www.mysite.com/android.php");
}else{
Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show();
}
}
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");
if (Uri.parse(url).getHost().equals("mysite.com")) {
// 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;
}
}
}
(Please ignore the bad formatting :p)

Categories

Resources