Where to put URL in StringBuilder (WebView) - android

I am encountering a problem where I cannot put the URL in the stringbuilder. What I am trying to accomplish here is to just get a particular part of the page. Here is the webpage I am trying to get the content off of:
http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA
Here is the part of the website I want to only show in my WebView:
http://oi44.tinypic.com/2ilnhwi.jpg
Here is my code:
public class WebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
StringBuilder builder = new StringBuilder("");
builder.append("javascript:document.getElementById('gb') .style.visibility= 'hidden';");
builder.append("document.getElementById('gb') .style.display = 'none' ;");
builder.append("document.getElementById('appbar').style.visibility= 'hidden';");
builder.append("document.getElementById('appbar').style.display = 'none' ;");
builder.append("document.getElementById('gf-nav').style.visibility= 'hidden';");
builder.append("document.getElementById('gf-nav').style.display = 'none' ;");
view.loadUrl(builder.toString());
}
}
private void AddListenerOnButton() {
spinner = (Spinner) getView().findViewById(R.id.spinner);
final WebView webView = (WebView) getView().findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String text1 = spinner.getSelectedItem().toString().trim();
WebClient wc = new WebClient();
if (text1.equals("US Dollar - USD")) {
//webView.loadUrl("http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA");
wc.onPageFinished(webView, "http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA");
wc.shouldOverrideUrlLoading(webView, "http://www.google.com/finance/company_news?q=CURRENCY%3AUSD&ei=hYbQUcC3LJS80QHnDA");
}
}
I have tried everything, but the whole webpage is still showing. What am I doing wrong? Is it something else that is wrong? Any help would be greatly appreciated.

My current code is wrapped in an entire function() wrapper, which works fine, maybe you could try that out:
builder.append("javascript:(function() {");
builder.append("document.getElementById('gb') .style.visibility= 'hidden';");
builder.append("document.getElementById('gb') .style.display = 'none' ;");
builder.append("document.getElementById('appbar').style.visibility= 'hidden';");
builder.append("document.getElementById('appbar').style.display = 'none' ;");
builder.append("document.getElementById('gf-nav').style.visibility= 'hidden';");
builder.append("document.getElementById('gf-nav').style.display = 'none' ;");
builder.append("})()");
Edit: Forgot a couple of parentheses at the end of the (function(){})

Related

How to get URL from long click links in a webview?

I want to Create a Context Menu for web view in android. My problem is that I cant get the URL from the clicked link. I write this code for log the clicked link:
webView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
WebView webView1 = (WebView) v;
WebView.HitTestResult hitTestResult = webView1.getHitTestResult();
Log.i("LinkClicked", hitTestResult.getExtra());
return false;
}
});
With this code, when long click on links in websites like stackoverflow, log like this:
https://stackoverflow.com/questions
everything is ok, but when long click on google search results, log like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAJFBMVEVHcEz/AAD/AAD/AAD/AAD/AAD/AAD/AAD/g4P/////KCj/7e0I8rGvAAAAB3RSTlMAT0g5Ggp+EilkVQAAAENJREFUGJVjYCAGsDAzggEzC5jLxo4E2BgYWNlRACsDM5jmggkwMzCBaQ5uqBATTICTk4OAAEILhqEY1mI4DNPphAAASIsES4gsgWgAAAAASUVORK5CYII=
it does not return a link. How I can fix this?
public class MainActivity extends AppCompatActivity {
WebView webView;
String URL1 = "https://stackoverflow.com/questions/60577403/how-to-get-url-from-long-click-links-in-a-webview/60577736?noredirect=1#comment107173847_60577736";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
public void onPageFinished(WebView view, String url) {
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
URL1 = url;
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.loadUrl(URL1);
// Register the context menu for web view
registerForContextMenu(webView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the web view hit test result
final WebView.HitTestResult result = webView.getHitTestResult();
// If user long press on url
if (result.getType() == WebView.HitTestResult.ANCHOR_TYPE ||
result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
// Set the title for context menu
menu.setHeaderTitle("\t\t\t\t\t\t\t\t\t\t ◦ ◉ ⦿ Select ⦿ ◉ ◦ \t");
// Add an item to the menu
menu.add(0, 1, 0, " \t \t➤\t Show URL")
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
String Pressed_url = result.getExtra();
Toast.makeText(MainActivity.this, "URL is:-" + Pressed_url,
Toast.LENGTH_SHORT).show();
return false;
}
});
}
}
}
Download Full Code from github.
Output

Android:Open iframe of WebView in Browser/YouTube App

I have some JSON content of a blog which i am displaying using loadDataWithBaseURL in WebView. Many articles of this blog have embedded youtube/vimeo videos.
Currently, all the videos are played inside the webview itself.
What i want to achieve is, when the user clicks to Play the Video, he should get the popup "Complete Action Using" Browser or YouTube App. In short, i dont want the videos to be played inside the webview of app.
I found questions where everyone was trying to avoid this popup.. Dont' know why i am not getting it.
Here is my code
public class DetailFragment extends Fragment {
String strTitle = null;
String strURL = null;
String strContent = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
AdView mAdView = (AdView) getView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
strTitle = getArguments().getString("title");
strURL = getArguments().getString("url");
strContent = getArguments().getString("content");
String contToDisplay = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /></head><body><style type='text/css'> img{width:80%;} .wp-image-42223{display:none;}</style>" + strContent+"</body></html>";
TextView title = (TextView) view.findViewById(R.id.title);
WebView desc = (WebView) view.findViewById(R.id.desc);
WebSettings ws = desc.getSettings();
ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
ws.setJavaScriptEnabled(true);
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
title.setText(strTitle);
// desc.loadData(contToDisplay, "text/html; charset=UTF-8", null);
desc.loadDataWithBaseURL("about:blank",strContent,"text/html", "UTF-8", null);
return view;
}
}
any solution that wold make the videos load in browser or YouTube App would help.
NOTE
The content i am displaying in webview is in HTML format with iframe as one of the elements. Here is the sample data:
"<p>Some text</p>
<p><iframe src=\"https://www.youtube.com/embed/q7uBAtaK15I\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\"></iframe> </p>
<p>some more text</p>
This entire content is displayed in webview. What i want to achieve is when someone clicks on iframe, he should be prompted to complete action using that is, the person shd not be allowed to play the video in webview
I managed to achieve this using regex.
Here is what i did
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
strTitle = getArguments().getString("title");
strURL = getArguments().getString("url");
strContent = getArguments().getString("content");
contToDisplay = "<html><head><meta http-equiv='Content-Type' content='text/html' charset='UTF-8' /><script type='text/javascript'></script></head><body><style type='text/css'> img{width:80%;} .wp-image-42223{display:none;} </style>" + strContent+"</body></html>";
TextView title = (TextView) view.findViewById(R.id.title);
TextView date = (TextView) view.findViewById(R.id.date);
TextView authorName = (TextView) view.findViewById(R.id.auth);
desc = (WebView) view.findViewById(R.id.desc);
setHasOptionsMenu(true);
WebSettings ws = desc.getSettings();
ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
ws.setJavaScriptEnabled(true);
ws.setLoadWithOverviewMode(true);
ws.setUseWideViewPort(true);
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setSupportMultipleWindows(true);
ws.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
title.setText(strTitle);
final String s = strContent;
final String regex = "(?<=<iframe src=\")[^\"]*";
final String regex2 = "<\\s*iframe[^>]*><\\s*/\\s*iframe>";
p = Pattern.compile(regex);
final Pattern p2 = Pattern.compile(regex2);
m = p.matcher(s);
m2 = p2.matcher(s);
evaluate(s,contToDisplay,this);
desc.loadData(value, "text/html; charset=UTF-8", null);
return view;
}
String evaluate(String token,String defaultValue, DetailFragment context){
value=null;
Matcher matcher=p.matcher(token);
if (matcher.find()) {
iframeURL=matcher.group();
String newURL = "Watch the Video Here";
value = m2.replaceAll(newURL);
}
if (value == null) {
value=defaultValue;
}
return value != null ? value : "";
}
Might help someone with similar issue.
This may help.we are loading a new url load in the correct native app.
desc.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url)
{
return true;
}
});
desc.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view,
String url)
{
if(url.contains("youtube.com")){
// Could be cleverer and use a regex return
return super.shouldOverrideUrlLoading(view, url);
}
return true;
});
If the links are embedded in an iframe (as the title suggested) you have to set a WebChromeClient to your webview and override the onCreateWindow-method:
#Override
public boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
WebView targetWebView = new WebView(view.getContext());
targetWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//simple url matching
if (url.contains("youtube.com") == true) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
view.getContex().startActivity(i);
}
view.stopLoading();
}
});
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(targetWebView);
resultMsg.sendToTarget();
return true;
}
And at the websettings of your webview, you have to set:
settings.setSupportMultipleWindows(true);

android remove view from alertdialog

Hi i have a MainActivity class where i have a listview populated by rss items. When i click on item list my app shows me an alertdialog where i can see in message box the item details. My problem is that after i show alertdialog when i close it and open a new item my app crashes giving me this error:
FATAL EXCEPTION: main.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here my java class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView);
wv = new WebView(this);
try {
url = new URL("http://www.unikore.it/index.php/ingegneria-informatica-home?format=feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ReadRssTask().execute(url);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
OptionDialog = new AlertDialog.Builder(MainActivity.this).create();
OptionDialog.setTitle(listview.getItemAtPosition(position).toString());
s = rssItems.get(position).getDescription();
if(s.contains("href=")){
s.substring(0,s.indexOf("</div>"));
wv.loadData(s, "text/html", "UTF-8");
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
OptionDialog.setView(wv);
}else {
OptionDialog.setMessage(s.replaceAll("<[^>]*>", ""));
}
OptionDialog.show();
}
});
}
i tried using OptionDialog.dismiss() method but app crashes anyway.
Thanks
move the instantiation of the WebView just before accessing the object.
s = rssItems.get(position).getDescription();
if(s.contains("href=")){
wv = new WebView(this);
wv.loadData(s, "text/html", "UTF-8");
// other code

Why is my fullscreen for youtube crashing?

I´m new to android and i´m using the first time webview, fragment, drawer...
I have the problem that with my code after pressing fullscreen in the video my app is crashing.
And i have no idea what is going wrong...
WebViewFragmentVideos
public class WebViewFragmentVideos extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.Websitesenglish);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new MyChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
return v;}
class MyChromeClient extends WebChromeClient {
String url = getArguments().getString("url");
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
Intent intent = new Intent(null, LandVideoAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("video", url);
startActivity(intent);
}
}
}
and
LandVideoAct
public class LandVideoAct extends Activity {
WebView webView, fullweb;
String url = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
setContentView(R.layout.landfull);
url = getIntent().getStringExtra("video") + "?fs=1";
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webView = (WebView) findViewById(R.id.fullwebview);
if (Build.VERSION.SDK_INT < 8) {
webView.getSettings().setPluginsEnabled(true);
} else {
webView.getSettings().setPluginState(PluginState.ON);
}
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
LandVideoAct.this.finish();
}
});
webView.loadUrl(url);
}}
I hope you dudes can help me with my problem.
Thank you!!
this piece of line of code is not allowed in android.
Intent intent = new Intent(null, LandVideoAct.class);
coming to your crash problem. Its mainly because of a above line of code. When full screen of video in webview is called , its gives call to android system ie onShowCustomView(View view, CustomViewCallback callback). Where you above line of code is failing.
instead of that use activity context or application context
Intent intent = new Intent(context, LandVideoAct.class);

How can i know what TextView was clickbale?

i have one doubt. I have an iteration of TextViews, and what i want is when i click in one TextView , i want stop the iteration and open a web, who can i know what TextView as been click on? i have this code:
Iterator<TextView> it = text.iterator();
while(it.hasNext()){
test = it.next();
test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
}
});
// condition to stop the iteration when i click on TextView
}
And what i want is the condition to stop the iteration when i click on the TextView that i want see, i try using some methods that are in the TextView and don't work. Anyone can help me? I have the iteration of TextViews because i want to do this dynamic, and i don't know the TextView who as click, and i want to know what TextView was click to stop the iteration, because if i don't stop this, for example if i have 3 TextView they will open the same web.
Thanks and forgive my English
I'm not sure I understand you entirely but from what I understand you want to stop the Iteration when you click on a TextView.
So one way you can do it is. Declare a boolean property for this class to use to control the loop, in this case I called it isStop and initial value with false.
while(it.hasNext() && !isStop){
...
}
then
public void onClick(View v) {
isStop = true;
//mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
So when you click on a TextView the flag will turn off the loop.
The solution to what i wanted:
On the Activity i create this.
OnClickListener s = new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
text = (TextView) findViewById(v.getId());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
}
};
Iterator<TextView> it = text.iterator();
while(it.hasNext())
{
text = it.next();
text.setOnClickListener(s);
}

Categories

Resources