I am trying to use a fragment to make some buttons that when clicked will open in a Webview with different URLs. Eg. when i click the first button i go to "https://google.com/", second button to "https://fb.com" and so on.
I have made methods like so for each redirect (as I was using intents to redirect to a web browser in previous version):
private void goToGoogle(View view) {
this.view = view;
goToUrl("https://google.com");
}
The goToURL(String URL) method is simply an intent to open the browser with the URL as parameter.
Now, I have been asked to implement an in-app webview. I have the following code:
public void openWebView (String url){
mWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl(url);
mWebView.setWebViewClient(new WebViewActivity());
}
which I call with openWebView(String.valueOf(R.string.googleURL));.
My onCreateView method is declared as follows (example for 1 button, there are 16 on the real thing):
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_imp_links, container, false);
LinearLayout activityLayout = new LinearLayout(getActivity());
Button1 = view.findViewById(R.id.goToGoogle);
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToGoogle(v);
}
});
I have also got this class in my app to handle the WebView:
public class WebViewActivity extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
I am getting java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
Any help you can provide is highly appreciated. Thank you.
Definition of mWebView: private WebView mWebView = new WebView(getContext());
To get a string from the resources, do not use String.valueOf(R.string.googleURL).
Instead use Context#getString(R.string.googleURL).
Related
In my app there is a WebView displaying Html content and a back button to let the user navigate back in the browser history. In the WebChromeClient, I get the Html page title in onReceivedTitle() and display it in my app.
The user is shown the first page and the first page title is displayed. The user can then click a hyperlink in the Html to get to the next page. The second page has a different title, and this is correctly displayed. The problem is if the user than clicks the Back button, the first page is diaplayed from the history but onReceivedTitle() is not called again. So my fist page is displayed with the wrong title from the second page.
How can I get the title of the page being that was loaded by the call to goBack()?
Here is some simplified code to demonstrate. Imagine a layout with a TextView, WebView, and Button. Also, imagine two Html files in the assets folder where pageone.html links to pagetwo.html and the two pages have different titles.
public class MyActivity extends Activity {
WebView webView;
TextView title;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webView);
title = (TextView) findViewById(R.id.title);
webView.loadUrl("file:///android_asset/pageone.html");
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String titleText) {
super.onReceivedTitle(view, titleText);
title.setText(String.format("Title: %s", titleText));
}
});
final Button button = (Button) findViewById(R.id.backButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (webView.canGoBack()) {
webView.goBack();
}
}
});
}
}
Apparently, this is a bug in certain builds of Android and used to work correctly.
I had been using the suggestion from https://stackoverflow.com/a/12154530/90236, but I think the answer for me is to not use onReceivedTitle() because it isn't called after a goBack.
onPageFinished() in the WebViewClient seems to be better if you need to handle goBack().
This seems to be working:
public class MyActivity extends Activity {
WebView webView;
TextView title;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.webView);
title = (TextView) findViewById(R.id.title);
webView.loadUrl("file:///android_asset/pageone.html");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
title.setText(String.format("Title: %s", view.getTitle()));
}
});
final Button button = (Button) findViewById(R.id.backButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (webView.canGoBack()) {
webView.goBack();
}
}
});
}
}
However, this changes the timing of when the Android app is notified of the title. What I have found is:
WebChromeClient.onReceivedTitle occurs first. However, this event does not occur when webView.goBack() is used to navigate to a page.
Then the html page loads and the DOM window.onload occurs
Finally WebViewClient.onPageFinished occurs
If you use Javascript to update the page title, using onPageFinished may have quite different behavior than onReceivedTitle because of the event timing.
I am trying to open webview with an imagebutton. I was able to do with an intent and uri.parse like so:
twbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("website"));
startActivity(browserIntent);
But it exits the application and opens the browser. I want it to open up without leaving the application
fbbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rootView = inflater.inflate(R.layout.fragment_socialmedia, container, false);
WebView myWebView = (WebView) rootView.findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("website");
}
});
but I get the error:
W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
Are you sure to have the element webview inside the layout fragment_socialmedia.xml ?
View rootView = inflater.inflate(R.layout.fragment_socialmedia, container, false);
WebView myWebView = (WebView) rootView.findViewById(R.id.webview);
thats the reason for what you are getting this exception : android.webkit.WebSettings android.webkit.WebView.getSettings()' on a null object reference
You need to swap these two lines:
myWebView.loadUrl("website");
myWebView.setWebViewClient(new WebViewClient());
Set WebViewClient before doing the load:
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("website");
How can I load a web view into a fragment?
I've tried the obvious but it opens a new browser and my nav disappears:
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
View mainView = (View) inflater.inflate(R.layout.frag_a, group, false);
myWebView = (WebView) mainView.findViewById(R.id.webview);
myWebView.loadUrl("http://www.bbc.co.uk");
return mainView;
}
I've also search stack overflow and the web, tried some of the examples but they do not work either, any help would be appreciated.
Thanks
I often had such situation, when after redirect page was opened in an external browser. Try to set WebViewClient with overriden shouldOverrideUrlLoading method which returns false.
Try:
public class DetailsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return(inflater.inflate(R.layout.details_fragment, container, false));
}
public void loadUrl(String url) {
((WebView)(getView().findViewById(R.id.browser))).loadUrl(url);
}
}
Setting a new WebViewClient to you webView will let the WebView handle urls internally.
webViewer = (WebView) mainView.findViewById(R.id.webview);
webViewer.setWebViewClient(new WebViewClient());
this is supported by the documentation:
http://developer.android.com/guide/webapps/webview.html
Im updating some of my older projects and using fragments to update the look of things. I tried to use a fragment to launch a webview but when I try to run it I get the following error in my logcat.
E/Web Console(22464): Uncaught TypeError: Cannot read property 'addEventListener' of null at
http://m.yahoo.com/?.tsrc=yahoo&mobile_view_default=true:1
The way I used to use a webview was to just create a class that was its own activity that took place in a webview but I would like to have a small view within a fragment and then when I wanted to use the class I would launch it via intent and pass anything I needed to the webview like a url and other parameters in extras within the intent. I tried just setting up a webview within a fragment but I havent gotten it to work yet. This is the code Im using for the moment.
public class WebViewer extends Fragment {
WebView Wv;
String url = "http://www.yahoo.com";
Activity act;
public WebViewer(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.act = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.webview, container);
Wv = (WebView) mView.findViewById(R.id.webview1);
Wv.getSettings().setJavaScriptEnabled(true);
Wv.getSettings().setRenderPriority(RenderPriority.HIGH);
Wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
Wv.getSettings().setDomStorageEnabled(true);
Wv.setWebViewClient(new HelloWebViewClient());
Wv.getSettings().setBuiltInZoomControls(true);
Wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
act.setTitle("Loading...");
act.setProgress(progress * 100);
if(progress == 100)
getActivity().setTitle(R.string.app_name);
}
});
Wv.loadUrl(url);
return mView;
}
}
And then this is the layout for the activity that uses this fragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bggreydotted"
>
<fragment
android:id="#+id/webFragment"
android:layout_width="150dip"
android:layout_height="match_parent"
android:name="my.proj.WebViewer"></fragment>
</LinearLayout>
So how can I get a webview to open inside a fragment I can use in a view.
Have you thought about just extending WebViewFragment?
I am kind of lost here so please give me some help.
I've been working on an app on ICS 4.0.2 for my GNex.
As of yet my app structure is as follows :
DemoActivity extends Activity contains three fragments that show up as tabs :
MapFragmentTab extends Fragment
SettingsFragmentTab extends Fragment
AboutFragmentTab extends Fragment
In the map fragment, I want to have a WebView display Google Maps.
This is my MapFragmentTab :
public class MapFragmentTab extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View mainView = (View) inflater.inflate(R.layout.map, container, false);
WebView webView = (WebView) mainView.findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://maps.google.com");
return mainView;
//return inflater.inflate(R.layout.map, container, false);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Right now, it seems to be working, however Google Maps ( although the page frame does load ) won't load.
I use Chrome Beta, haven't tried the default browser yet.
I'm really confused when it comes to WebViews, WebViewFragments and Fragments...
any help would be appreciated.
You need to enable JavaScript specifically on WebView, as it is disabled by default. Use something like: webView.getSettings().setJavaScriptEnabled(true);
From: http://developer.android.com/reference/android/webkit/WebSettings.html#setJavaScriptEnabled(boolean)
http://developer.android.com/resources/tutorials/views/hello-webview.html