calling intent WebView in fragment - android

Hi I'm trying to call a webview fragment when an item of recyclerview is clicked, I made a fragment with it's layout for the webview, and I have an adapter to call the fragment but it shuts down the APP:
public class WebViewFragment extends Fragment {
public WebView mWebView;
public WebViewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mWebView = (WebView) mWebView.findViewById(R.id.webview);
mWebView.loadUrl("google.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
return inflater.inflate(R.layout.fragment_web_view, container, false);
}
}
And the adapter:
#Override
public void onClick(View view) {
int position = (int) view.getTag();
News news =newsItems.get(position);
Uri uri = Uri.parse(news.getLink());
Intent intent = new Intent(mACtivity, WebViewFragment.class);
mACtivity.startActivity(intent);
}
Layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="tech.amro.amro.WebViewFragment">
<!-- TODO: Update blank fragment layout -->
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"/>
</FrameLayout>
I know I'm not sending the url to the webview yet but I'm just testing to load the view first then sending the url. but when the item is clicked it shuts down the APP. and gives this error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tech.amro.amro, PID: 18958
android.content.ActivityNotFoundException: Unable to find explicit activity class {tech.amro.amro/tech.amro.amro.WebViewFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1932)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1615)
at android.app.Activity.startActivityForResult(Activity.java:4472)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
at android.app.Activity.startActivityForResult(Activity.java:4430)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
at android.app.Activity.startActivity(Activity.java:4791)
at android.app.Activity.startActivity(Activity.java:4759)
at tech.amro.amro.adapters.NewsAdapter.onClick(NewsAdapter.java:73)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Application terminated.

If you don't have a specific reason to use a WebView you could just use an Intent to start a web browser as follows.
#Override
public void onClick(View view) {
int position = (int) view.getTag();
News news = newsItems.get(position);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(news.getLink()));
startActivity(i);
}
Note you probably would need to check if the device can handle the URI - some people might not have a browser installed which will result in an ActivityNotFoundException.
If you do need to use the WebView you have a couple of issues:
Fragments can't be started the same way you start an activity, to display a fragment you need to use the FragmentManager in order to add it into your Activity.
Regarding your Fragment, the onCreateView code won't work. You need to inflate the xml first that contains your webview and then find the webview from that layout.
At the moment you're trying to find the webView from the webView which will result in a NullPointerException.
You should also prefer onViewCreated to find and load the WebView url.
Your fragment should probably look something like the following
public class WebViewFragment extends Fragment {
private static final String NEWS_LINK_KEY = "NEWS_LINK";
private String newsLink;
public static WebViewFragment newInstance(String uri) {
Bundle args = new Bundle();
args.putString(NEWS_LINK_KEY, uri);
WebViewFragment webViewFragment = new WebViewFragment();
webViewFragment.setArguments(args);
return webViewFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
newsLink = this.getArguments().getString(NEWS_LINK_KEY);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.web_view, container, false)
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WebView webView = (WebView) view.findViewById(R.id.webview);
// Enable Javascript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(newsLink);
}
}
This could be started from the onClick method as follows:
#Override
public void onClick(View view) {
int position = (int) view.getTag();
News news = newsItems.get(position);
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, WebViewFragment.newInstance(news.getLink()))
.commit();
}

Related

Hyperlink click in WebView within fragment should open in new WebView in activity (tricky)

I am using fragment with WebView. Webview opens up correctly. My intention is as follows: Visitor clicks on any of the links within WebView inside the Fragment. Clicked link opens up in new WebView within new Activity. Tricky part - all links are from the same web site, there are no external links. Tricky for me, at least. Many thanks for your help in advance! :)
Here is my WebView code from Fragment:
public class HomeFragment extends Fragment {
#SuppressLint("SetJavaScriptEnabled")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_naslovna, container, false);
WebView webView = view.findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://mywebpage.com/");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
return view;
}
}
Please try this:
WebViewClient webClient = new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if( url.equals("http://test.com") ){
// do whatever you want e.g. open up activity with web view and pass the url
}
return true;
}
}
It took 6 more hours u puzzle work, but this is how it got fixed at the end.
public class HomeFragment extends Fragment {
WebView webView;
SwipeRefreshLayout swipeToRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_naslovna, container, false);
webView = view.findViewById(R.id.webView1);
final String pageUrl = "https://mywebpage.com/";
swipeToRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swiperefresh);
swipeToRefreshLayout.setOnRefreshListener(new RtvTkSwipeToRefreshListener(webView, swipeToRefreshLayout));
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != pageUrl) {
startNewActivity(url);
}
return true;
}
});
webView.loadUrl(pageUrl);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
return view;
}
private void startNewActivity(String url) {
Intent myIntent = new Intent(getActivity(), NewActivity.class);
myIntent.putExtra("url", url);
getActivity().startActivity(myIntent);
}
}

preload webview in DialogFragment

The DialogFragment has a webview.
Everytime show the DialogFragment,the webview will take some time to load the webview, and before the webpage finished loading, the webview will show the background color. This will affect the user experience. So i want to use some method to preload webview. But really get me there is that m_webviewDialog.show will start two function onCreateDialog and onCreateView. So is there anyway make the webview preload and then add in the onCreateView fucnion?
main activity show code:
public void showWebviewDialog()
{
FragmentManager fragmentManager=getFragmentManager();
if(m_webviewDialog!=null&&m_webviewDialog.isAdded())
{
m_webviewDialog.getDialog().show();
}
else {
m_webviewDialog=mcWebViewDialog.newInstance();
m_webviewDialog.set_loadurl("file:///android_asset/input.html");
m_webviewDialog.show(fragmentManager,"mcWebDialog");
}
}
DialogFragment code:
WebView m_webView;//WebView component
String m_loadurl;
static mcWebViewDialog newInstance()
{
mcWebViewDialog f=new mcWebViewDialog();
return f;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// other code
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
m_webView = new WebView(getActivity());
//other code
return m_webview;
}
I had an issue, that webview (in DialogFragment) is minimized to zero height althogh it has data. so I used relaod. you must be sure that WebView has data, or you will go to non-ending loop becouse reload leads to onPageFinished and vise versa.
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (view.getContentHeight() == 0){
view.reload();
}
}
...
}

Menu Button on ViewPager toasts wrong position

I am loading local htmls in webview using Viewpager. This works fine and the right page is loaded from the WebViewFragment into viewpager activity. Scroll or swipe works fine, but I added a menu button to get the title of the current webview, and to toast it. This menu button returns the webview title of the next 2 webview pages in the viewpager.
Reducing the setOfScreenLimit to 1 toasts the webview title of the next webview page in the viewpager. I cant setOfScreenLimit to 0. What is the most probable way to get the current item's webview title when the menu button is clicked. I need to get this and save to a DB.
Code:
ViewPager
ViewPager pager = (ViewPager) findViewById(R.id.pager);
TabsPagerAdapterEnglish pageAdapter = new TabsPagerAdapterEnglish(getSupportFragmentManager());
Bundle extras = getIntent().getExtras();
int value = 0;
if (extras != null) {
value = extras.getInt("keyHTML");
}
pager.setAdapter(pageAdapter);
pager.setCurrentItem(value);
pager.setOffscreenPageLimit(1);
Adapter
public class TabsPagerAdapterEnglish extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3
public TabsPagerAdapterEnglish(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return WebFragmentEnglish.newInstance(0, "file:///android_asset/page1.html");
case 1:
return WebFragmentEnglish.newInstance(1, "file:///android_asset/page2.html");
case 2:
return WebFragmentEnglish.newInstance(2, "file:///android_asset/page3.html");
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
}
}
WebFragment
public class WebFragmentEnglish extends Fragment {
// newInstance constructor for creating fragment with arguments
public static WebFragmentEnglish newInstance(int position, String url) {
WebFragmentEnglish fragmentFirst = new WebFragmentEnglish();
Bundle args = new Bundle();
args.putInt("page_position", position);
args.putString("keyHTML", url);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
if (null != toolbar) {
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
}
position = getArguments().getInt("page_position", 0);
url = getArguments().getString("keyHTML");
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().finish();
case R.id.action_addtofav:
webView = (WebView) getActivity().findViewById(R.id.webView1);
htitle = webView.getTitle();
saveData();
Toast.makeText(getActivity(), htitle + " added to favorite",
Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
webView = (WebView) view.findViewById(R.id.webView1);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setMax(100);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return true;
}
});
webView.setLongClickable(false);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.loadUrl(url);
return view;
}
ViewPager will load the current page and the next page(s) up to the offScreenLimit. To get the name of the current page you need to get the current position of the adapter.
It's hard to give more specific help without having code posted. But you can use the ViewPager getCurrentItem method to get the visible index. From there you can either compare it to the index of the page you're displaying (this works if the view pager is static and pages are known in advance), or you can use that index to get the Fragment from the PagerAdapter and call a method on it to save the name.
I was able to solve the problem with the ViewPager.
I removed the toolbar instance from the fragment to use the one in the viewpager's activity. Then in my options menu, you would notice I used
webView = (WebView) **getActivity().**findViewById(R.id.webView1);
I removed the this completely, since i have already defined it in the onCreateView, I think maybe its because of the getActivity field I added to locate the webview ID.
I was updating an old code, I'm glad I was able to solve this. Thank you #Chisko and #Ben

Go back in webview by pressing "back button"

How can I go back one page while in webview? For example: I am on my app in activity and browsing pages in webview, but once I press back button it will exit the app or just goes back in activity instead of the page..
I have done my research and overriding onBackPressed function doesnt work.
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
Whole fragment code:
public class FragmentTwo extends Fragment {
public FragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment2, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
WebView webView = (WebView) getActivity().findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webView.setScrollbarFadingEnabled(false);
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://myapp.com");
}
}
Any suggestions of how to achieve it?
onBackPressed() is method of Activity, not of a Fragment, so this code will never be invoked. If you want to do something on back press, your parent activity must let your fragment know about it - you must implement onBackPressed() in parent activity and in that method you should call fragments' method (or fire event on event bus, or use listeners, callback, whatever).
Also right method name is onCreateView(), not onViewCreated() - this one won't be called either.
Inside of the your OnCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.your_layout, container, false);
webView = (WebView) view.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(expertsUrl);
return view;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Ok! In your MainActivity you will write it:
#Override
public void onBackPressed() {
if(yourname_Fragment.webView!=null){
if (yourname_Fragment.webView.canGoBack()) {
yourname_Fragment.webView.goBack();
}
}
}
yourname_Fragmen.java= This is your nameFragment that content the Webview
webView= The name of your WebView (id)
Now. Inside of your Fragment you have to declare static global variable
public static Webview webView;
NOTE: If you have more than one fragment you have to check if this instance is different of NULL;
And that's it! Good luck!

Android: How can I Open a WebView in a Popup Window?

I already have a WebView with content loaded and I need to select text that will open a new WebView in a popup window. The popup will contain a form which I will submit and when I hit enter it will save data and close the popup. At this stage, I need help in opening the WebView popup by selecting text or clicking button.
I have tried the answer from https://stackoverflow.com/a/9173368/2341601 but this crashes the app when I do
WebView wv = new WebView(this);
LogCat message:
Process: com.example.user.testapp, PID: 13984
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.testapp/com.example.user.testapp.MainActivity}: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.AndroidRuntimeException: requestFeature() must be called before adding content
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.webview_layout);
WebView wv = (WebView) dialog
.findViewById(R.id.webview);
wv.loadUrl("http:\\www.google.com");
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
dialog.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss();
}
return false;
}
});
webview_layout.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Avoid request future crash.
DialogFragment.java
public class DialogFragment extends android.support.v4.app.DialogFragment {
private boolean isModal = false;
public static DialogFragment newInstance()
{
DialogFragment frag = new DialogFragment();
frag.isModal = true; // WHEN FRAGMENT IS CALLED AS A DIALOG SET FLAG
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(isModal) // AVOID REQUEST FEATURE CRASH
{
return super.onCreateView(inflater, container, savedInstanceState);
}
else
{
View view = inflater.inflate(R.layout.dialog_webview, container, false);
setupUI(view);
return view;
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_webview, null);
builder.setView(view);
WebView wv = (WebView) view.findViewById(R.id.webView);
wv.loadUrl("http:\\www.google.com");
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
return builder.create();
}
}

Categories

Resources