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

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

Related

calling intent WebView in fragment

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

How to go back to previous page if back button is pressed in WebView in Fragment?

public class PrimaryFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.primary_layout, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webView);
WebSettings webSettings = heroespage.getSettings();
webSettings.setJavaScriptEnabled(true);
heroespage.setWebViewClient(new MyBrowser());
heroespage.loadUrl("http://beritagresik.com");
return rootView;}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url ){
view.loadUrl(url);
return true;
}}}
This is sample my application, plis help for resolve this problem
thanks for ur help
If you open a web url in webview and inside is you open another link and so on.
now you want to come back by page , you can use webView.goBack();
Try out this code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (heroespage.canGoBack()) {
heroespage.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Progress bar doesn't show up while webview is loading

I have written sample webview code by looking at examples found from internet. I want to show progressbar till webview loads a page in my fragment.
My activity contains toolbar, frame that shows fragments and navigation drawer. When i select an entry from navigation drawer, new fragment is shown which contains progress bar and webview and the fragment simply tries to load the page below is the code for fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_full_page, container, false);
//int view_num = getArguments().getInt(ARG_SECTION_NUMBER);
progressBar = (ProgressBar)rootView.findViewById(R.id.webviewProgress);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) rootView.findViewById(R.id.webView1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String urlString = getArguments().getString("URLSTRING");
final Boolean clickable = getArguments().getBoolean("CLICKABLE");
Boolean networkAvailable = Utils.isNetworkAvailable(super.getActivity().getApplicationContext());
if(networkAvailable == true) {
webView.loadUrl(urlString);
} else {
webView.loadUrl(Utils.DEFAULT_URL_PAGE);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//progressBar.setVisibility(View.VISIBLE);
if (clickable) {
view.loadUrl(url);
return false;
} else {
return true;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
});
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
Below is fragment_full_page.xml
<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=".FragmentFullPage" >
<ProgressBar
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center|top"
android:id="#+id/webviewProgress"
/>
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
web page is taking time to load (tried with wifi and 3g) but progress bar is not showing any time.
To test if progressbar actually shows in the middle of the fragment_full_page, I removed webview code and just kept progress bar then it is showing.
made something wrong with the code that is not showing progress bar while webview is loading which i am unable to figure out.

Override back button while viewing webview (fragment)

I created a WebView using Fragment; here is my code:
public class MyWebView extends Fragment {
private WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
String url = args.getString("url");
webView = (WebView) getView().findViewById(R.id.webView);
webView.setWebViewClient(new MyBrowser());
WebSettings webSettings = webView.getSettings();
webSettings.setSaveFormData(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.web_view, container, false);
view.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}
}
return false;
}
});
return view;
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
I tried to override onBackPressed() but it seems not to work with Fragment. So I used setOnKeyListener() but it doesn’t work.
Can you tell me why the back button closes the app instead of going back to the previous web page?
The Fragment doesn't receive a callback of the OnBackPressed event. You'll have to make your Activity state aware when your fragment is displayed and communicate back and forth between the activity and the fragment.
You could make your code you're calling in on key a public boolean function for instance and if the fragment is present you interact with it, you continue to return true or false in a similar way which allows you to know on the activity if you should continue with it naturally if there are no more pages to go back.

WebView inside Fragment - Back button?

I created a small Android 4 application with fragments.
In all these fragments I have some webviews and if I click a different fragment I want a different website to load.
I have right now TabOne.java ; TabTwo.java ; TabThree.java and so on.
I was also wondering : Can I make this application without needing a TabOne.java, TabTwo.java and so on; only from MainActivity.java? I mean, to have a single WebView, and when clicking different Tabs, this WebView to load different Url (according to the selected Tab).
If this is not possible, can you tell me what is wrong here (TabOne.java) :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tabone, container, false);
myWebView = (WebView) view.findViewById(R.id.webview);
myWebView.getSettings().setPluginsEnabled(true);
myWebView.loadUrl("http://m.stirileprotv.ro");
myWebView = new WebView(getActivity());
myWebView.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
{
myWebView.goBack();
return true;
}
return false;
}
});
myWebView.setWebViewClient(new WebViewClient() {
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("m.stirileprotv.ro")) {
myWebView.loadUrl(url);
return true;
}
else
{
return false;
}
}
});
return view;
}
This is what i did.
In the fragment, declare the webview reference as static-
public static WebView mWebView;
public WebFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_web, container, false);
mWebView = (WebView) v.findViewById(R.id.webview);
mWebView.loadUrl("https://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 v;
}
public boolean canGoBack() {
return mWebView.canGoBack();
}
public void goBack() {
mWebView.goBack();
}
}
Now, In the parent activity -
#Override
public void onBackPressed() {
WebFragment fragment = new WebFragment();
if (fragment.mWebView.canGoBack()) {
fragment.mWebView.goBack();
} else {
super.onBackPressed();
}
}
What I did was implement it within the activity and then have a public static so:
In the main activity:
public class MainActivity extends FragmentActivity{
public static WebView myWebView;
...
#Override
public void onBackPressed() {
if (getSupportFragmentManager().findFragmentByTag("yourtag") != null) {
if(myWebView.canGoBack())
myWebView.goBack();
else {
super.onBackPressed();
}
}
else
super.onBackPressed();
}
...
}
and to reference it within the fragment:
MainActivity.myWebView = (WebView) getView().findViewById(R.id.webview);
and be sure when you create the fragment you add a tag
transaction.replace(R.id.yourfragid, newfragment, "yourtag");

Categories

Resources