Wednesday, January 1, 2014

Play youtube video in webview android

In this tutorial  code snippet for play youtube video in webview using youtube video url.

Below is the code snippet using that you can play youtube video in android application.

Put this brlow code in your onCreate() method.

                                WebView mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_INSET);
mWebView.setWebChromeClient(new WebChromeClient() {
});
mWebView.loadUrl("YOUR YOUTUBE VIDEO URL HERE");
mWebView.setWebViewClient(new MyWebViewClient());


Create this class MyWebViewClient in your package.
Put this code snippet in your MyWebViewClient class

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

view.loadUrl(url);
return true;

}


Using this code you can play your youtube video in webview using youtube url.

Network on main thread exception android

Many time we face problem like  NetworkOnMainThreadException in android application.
For easily overcome this solution there is two simple methods.

1)The recommended way of solving this is by Using anAsyncTask so that the network request does not block the UI thread.

2)Or you can override this thread policy by adding the below code into your main activity’s onCreate() method.

StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation

below is the sample code for the second way (Override thread policy).

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = 
    new StrictMode.ThreadPolicy.Builder().permitAll().build();      
        StrictMode.setThreadPolicy(policy);
 }