How to Open PPT/Presentation file in webview in android? - android

I have a URL of a presentation and i want to show this in the webview in android. I have tried the below code but it is redirecting in google drive app.
String url1 =
"https://docs.google.com/presentation/d/1nL5yO1HX_";
And my Webiew code is below:
WebView mywebview = findViewById(R.id.webview);
WebSettings settings = mywebview.getSettings();
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
settings.setAllowFileAccess(true);
settings.setJavaScriptEnabled(true);
mywebview.loadUrl(url1);

Use setWebViewClient and getHitTestResult.It is use to get the url which will be going to open and then check whether it is ppt file or not.
First XML File :-
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"></WebView>
Main Activity :-
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request)
{
try{
if(webView.getHitTestResult().getExtra().endsWith(".pptx"))
{
try
{
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("url",webView.getHitTestResult().getExtra());
startActivity(intent);
return true;
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, e+"", Toast.LENGTH_SHORT).show();
}
return true;
}
else
{
webView.loadUrl(request);
return true;
}}
catch (Exception e)
{
return false;
}
}
Then in new activity get value of intent :-
public class Main2Activity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent=getIntent();
String t=intent.getStringExtra("url");
String s="http://docs.google.com/viewer?url=";
s=s.concat(t);
webView=(WebView)findViewById(R.id.webView);
webView.loadUrl(s);
}
#Override
protected void onResume()
{
this.finish();
super.onResume();
}
Second XML File :-
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

I have used webclient and it worked for me
public class WebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}

Related

How to disable webview navigate to another page?

Please help me. How to disable webview open new page ? I want to disable this behaviour, so if I click on a link, don't load it. I've tried this solution and edited a bit for myselft, but not worked. My webviewclient code:
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://example.com");
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
In your WebViewClient, you can load only specific url that you want as below,
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equals("my url")) {
view.loadUrl(url);
}
return true;
}
Firstly you use web view you create web activity like this:
xml layout:-
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
WebView Activity:-
public class WebViewActivity extends AppCompatActivity {
#BindView(R.id.webView1)
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
// i am using intent getting the value from like this
Intent intent2 = getIntent();
Bundle bundle = intent2.getExtras();
String link = bundle.getString("Agreement_URL");
Log.e("link---",""+link);
String file_type=bundle.getString("file_type");
if(file_type.equals("PDF"))
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://docs.google.com/gview?embedded=true&url="+link);
setContentView(webView);
}
else
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(link);
}
}
/** Method on BackPressed Button click*/
public void onBackPressed(){
super.onBackPressed();
/** Activity finish*/
finish();
}
pass the value like this from previous activity
Intent intent =new Intent(context, WebViewActivity.class);
intent.putExtra("Agreement_URL","http://54.183.245.32/uploads/"+ finalUploadDoc);
intent.putExtra("file_type","PDF");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.e("ggg",""+ finalUploadDoc);
context.startActivity(intent);
try this it helps you

how to start third activity if url is same in webview

how to start third activity if url is same in webview
for example i have webview
in my webview if url is like this
http://example.com/access.html
then start thirdactivity
how can i do this please help me to fix this issue
thanks
in advance
here is my webview code
public class SecondActivity extends AppCompatActivity {
private WebView wv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String url = getIntent().getStringExtra("url");
wv1=(WebView)findViewById(R.id.webView);
wv1.setWebViewClient(new WebViewClient());
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.loadUrl(url);
}
}
here is xml file of secondactivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#color/colorPrimaryDark"
tools:context="com.shuvro.barcodescanner.BarcodeScannerActivity">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap
favicon) {
super.onPageStarted(view, url, favicon);
// write your logic here.
if (url.equals(pdfWebURL)) {
loadingIndicator.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loadingIndicator.setVisibility(View.GONE);
}
});
please write your logic in onPageStarted.
Please try below code
public class WebView extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String weburl) {
if (weburl.equals("YOURLINK")) {
Intent i = new Intent(getContext(), YourActivity.class);
startActivity(i);
return true;
} else {
view.loadUrl(url);
return true;
}
}
}

Webview not loading url on Nexus Devices

Earlier webbview works fine but today strange problem came that showing this when I load url..
Code for this is....
public class ShowSubjectListItemsInWebView extends ActionBarActivity {
private WebView webView;
private Toolbar mToolbar;
private SessionManager sessionManager;
private Security security;
private ProgressDialog dialog;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_subject_list_items_in_web_view);
this.initViews();
this.setToolBar();
try{
sessionManager = new SessionManager(getApplicationContext());
security = new Security(getApplicationContext());
boolean isInternetPresent = security.isConnectingToInternet();
if (isInternetPresent) {
//I hide url due to some privacy contents
loadWebView(url);
} else {
showCustomToast("Internet not available \n Please check your internet connection");
}
}catch(Exception ex){
showCustomToast("Something went wrong");
}
}
//initializes all views
private void initViews() {
webView = (WebView) findViewById(R.id.filesWebView);
}
//show Url in WebView
public class myWebClient extends WebViewClient {
#JavascriptInterface
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
dialog = new ProgressDialog(ShowSubjectListItemsInWebView.this);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.setCancelable(false);
dialog.setMessage(Constant.KEY_PLEASE_WAIT);
dialog.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
public void loadWebView(String decryptedUrl) {
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setVisibility(View.VISIBLE);
webView.loadUrl(decryptedUrl);
}
}
I tested this code on lenovo, moto and MI devices...works fine but when I choose nexus device for loading url it gives the above stated error.

Android : Progressbar to load url, continues to load

In my application, i'm using a webview to open a url. The url is very simple, it just takes secs to load. But the progress bar doesn't hide when the url loads completely. I'm not able to figure out whats wrong. please help me. Below i'm posting the code.
WebView Class
public class noti_cse extends BaseActivity {
private WebView webView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noti_cse);
// overridePendingTransition(0, 0);
// webView = (WebView) findViewById(R.id.webcse);
// webView.setWebViewClient(new MyWebViewClient());
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
webView = (WebView) findViewById(R.id.webcse);
webView.setWebViewClient(new CustomWebViewClient());
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
startWebView("http://notify.php");
}
// webView.getSettings().setJavaScriptEnabled(true);
// startWebView("http://notify.php");
// webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
// webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource(WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(noti_cse.this);
progressDialog.setMessage("On the Way!!!");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(noti_cse.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
}
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_placements)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
You are setting 2 WebViewClient.
First:
webView.setWebViewClient(new CustomWebViewClient());
And after that, you are calling
startWebView()
which sets a new WebviewClient.
You can change your method like below:
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(noti_cse.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
//Show loader on url load
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(noti_cse.this);
progressDialog.setMessage("On the Way!!!");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
And remove this line form onCreate() method:
webView.setWebViewClient(new CustomWebViewClient());

How to add a progressbar to the android webview

I am trying to add a progress bar in the android webview based app. I have added following code but not working when tested.
Note: index.html have redirect tag which loads random URL. Everything is working fine except the progressbar.
MainActivity.java
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
ProgressBar Pbar;
private final int ID_MENU_EXIT = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
Pbar = (ProgressBar) findViewById(R.id.pB1);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new MyAppWebViewClient());
if (isNetworkAvailable())
mWebView.loadUrl("file:///android_asset/www/index.html");
else
mWebView.loadUrl("file:///android_asset/www/404.html");
}
public class myWebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Pbar.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//get the MenuItem reference
MenuItem item =
menu.add(Menu.NONE,ID_MENU_EXIT,Menu.NONE,R.string.exitOption);
//set the shortcut
item.setShortcut('5', 'x');
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//check selected menu item
if(item.getItemId() == ID_MENU_EXIT)
{
//close the Activity
this.finish();
return true;
}
return false;
}
}
Activity_main.xml
<ProgressBar android:id="#+id/pB1"
style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:padding="2dip">
</ProgressBar>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Well,
Use this code for Progress Bar when your WebView waiting for loading WebView. :
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Activity:
public class MapActivity extends MenuActivity {
private final static String TAG = "HearingTest";
private WebView webView;
private String urlString;
private ProgressDialog progressDialog;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
context = MapActivity.this;
urlString = getString(R.string.location_url);
WebViewSettings();
LoadWebPage(urlString);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Please wait.");
//progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
public void LoadWebPage(String url){
try {
webView.loadUrl(url);
Log.d(TAG, "URL" + url + "connected");
}
catch (Exception e) {
Log.d(TAG, "URL: " + url + " couldn't connect.");
}
}
public void WebViewSettings(){
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals(urlString)) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
#Override
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
});
}
protected void DisplayProgressBar(){
}
}

Categories

Resources