I'm new to Android studio.
So I have been writing some code that helps my job.
When the imgView and Layout clicked the app will go into WebView
On the WebView they will fill the form, after that the web should automatically downloading the .pdf file.
When I Opened it with chrome, chrome will make a new tab/pop up with some link that triggers downloading files.
How this webView could download the pdf file too? because When I opened it on the Web View, the WebView will go back to previous activity.
public class biling extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biling);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 1);
}
}
webView = findViewById(R.id.bilingweb);
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// if want to download pdf manually create AsyncTask here
// and download file
return true;
}
return false;
}
});
webView.loadUrl("https://sse2.pajak.go.id");
webView.setDownloadListener(new DownloadListener()
{
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()){
v.requestFocus();
}
break;
}
return false;
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setDisplayZoomControls(true);
webSettings.setAllowFileAccess(true);
webSettings.setSupportMultipleWindows(true);
Toolbar toolbar = findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("e-Biling");
getSupportActionBar().setSubtitle("Bayar Pajak Online");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){webView.goBack();}
else
{super.onBackPressed();}
}
}
Related
I'm building a webapp (html, css, js) with Firebase backend. If the site is opened from the browser, everything is working well, if the user is logged in, it redirects the user to another page. However if I'm using the same site from an android app (which is using webview), the redirecting doesn't work. Any idea why?
The code I'm using in android studio:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
setContentView(R.layout.activity_main);
web = findViewById(R.id.webView);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
web.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return false;
}
});
web.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
});
web.loadUrl("http://mywebsite.com/login");
web.getSettings().setAppCacheEnabled(false);
web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
web.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
}
And this is how the redirecting works:
function loginUser() {
emailVal = document.getElementById("email").value;
passwordVal = document.getElementById("password").value;
firebase.auth().signInWithEmailAndPassword(emailVal, passwordVal)
.then((userCredential) => {
var user = userCredential.user;
})
.catch((error) => {
});
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
window.location.replace('http://mywebsite.com/home');
}
});
So, after having some google search, I've found this StackOverflow topic:
firebase google authentication in web does not work on android app webview
The problem was that I hadn't enabled the DOM storage. By inserting these two lines to my Java code solved the problem:
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true); // localStorage
I have two webviews in my android app one webview deletes content based on given javascript function and other one is remaining same even I give javascript function by id. The main webview working perfectly and other one not and now i may integrating another webview if my second webview works perfectly.
here is my first webview it's working perfectly
#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("url");
webView.getSettings().setDomStorageEnabled(true)
public class myWebClient extends WebViewClient
{
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() {document.getElementById('mainHeader').style.display='none';" + "document.getElementById('footerRights').style.display='none';" + "document.getElementById('navTrail').style.display='none';" + "document.getElementById('threeColumns').style.display='none';" + " })()");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
}
#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();
}
}
}
my second webview
public class webview2 extends AppCompatActivity {
private WebView webVIEW;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
webVIEW = (WebView) findViewById(R.id.webVIEW);
webVIEW.setWebViewClient(new WebViewClient());
webVIEW.getSettings().setJavaScriptEnabled(true);
webVIEW.loadUrl("example url");
webVIEW.getSettings().setJavaScriptEnabled(true);
webVIEW.getSettings().setDomStorageEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public class webVIEW extends WebViewClient {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() { " + "var element = document.getElementById('hplogo');" + "element.parentNode.removeChild(element);" + " })()");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon ) {
super.onPageStarted(view, url, favicon);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed(){
if (webVIEW.canGoBack()) {
webVIEW.goBack();
}else {
super.onBackPressed();
}
}
}
webview2.java
its being remaining same no javascript excution now i need to integrate another webview and it also needs the same as first webview
Thanks in Advance
I have solved my question using kotlin class by this i can inject java script in one or more webviews
class webview2 : AppCompatActivity() {
private lateinit var webVIEW: WebView
#SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)
webVIEW = findViewById<WebView>(R.id.webVIEW) as WebView
webVIEW.settings.javaScriptEnabled = true
webVIEW.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
injectJS()
}
}
webVIEW.loadUrl("https://example/login")
}
val progressBar = findViewById<ProgressBar>(R.id.progressBar3)
override fun onBackPressed() {
if (webVIEW.canGoBack()) {
webVIEW.goBack();
} else {
super.onBackPressed()
}
}
private fun injectJS() {
val jsContent: String?
jsContent = try {
val inputStream = assets.open("style.js")
val fileContent = inputStream.bufferedReader().use(BufferedReader::readText)
inputStream.close()
fileContent
} catch (e: Exception) {
null
}
jsContent?.let { webVIEW.loadUrl("javascript:($jsContent)()") }
}
}
I have a WebView and I wanted to when someone click on a link it should open in a browser not in my app. How can I do that?
I want to show a webpage but when someone click on it it should open in a new browser that's all I want. How can i do that?
Here is the code that I am using
public class tab2 extends Fragment {
WebView webView ;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2, container, false);
webView = (WebView) view.findViewById(R.id.webview1);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar1);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://facebook.com");
return view;
}
public class myWebClient 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
progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}
Instead of
view.loadUrl(url);
You could try to use:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
I'm trying to make the javascript work in android for this page:
http://test.swiss-impulse.com/scratch_card_game/index.html
But i have issues regarding the browser.
This is the parameters set for the webview:
webView1.setWebChromeClient(mClient);
webView1.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
webView1.addJavascriptInterface(new JavaScriptInterfaceForTitle(this, mPasswordStrength, webView1), "HtmlViewer");
webView1.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String cookie = CookieManager.getInstance().getCookie(url);
if (url.equals(getContentUrl() + "addcomment")) {
webView1.stopLoading();
Intent addcommentIntent = new Intent(mContext, AddCommentActivity.class);
addcommentIntent.putExtra("url", previousUrl);
startActivity(addcommentIntent);
} else {
previousUrl = url;
((BaseActivity) mContext).showLoadingDialog();
if (!urlStackList.contains(url)) {
urlStackList.add(url);
}
super.onPageStarted(view, url, favicon);
}
}
#Override
public void onPageFinished(WebView view, String url) {
((BaseActivity) mContext).hideLoadingDialog();
if (url.contains("content/shows/") || url.contains("content/tips/")) {
counter = 0;
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('" + mContext.getString(R.string.title_name) + "').innerHTML);");
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('name_en').innerHTML);");
view.loadUrl("javascript:window.HtmlViewer.showHTML(document.getElementById('name_zh').innerHTML);");
} else {
mStateBar.setShowTitle(mContext.getString(R.string.tv_drama));
}
super.onPageFinished(view, url);
}
});
webview1.setWebChromeClient(mClient);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.getSettings().setPluginState(PluginState.ON);
webView1.getSettings().setPluginsEnabled(true);
webView1.getSettings().setAppCacheMaxSize(httpCacheSize);
webView1.getSettings().setSupportZoom(false);
webView1.getSettings().setBuiltInZoomControls(false);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
Am i missing some parameters to make this work on android webview ? I checked chrome browser and there it works with no problems, so i'm sure i missed something and cannot find what.
EDIT:
class MyChromeClient extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
mCustomViewCallback = callback;
mTargetView.addView(view);
mCustomView = view;
mContentView.setVisibility(View.GONE);
mTargetView.setVisibility(View.VISIBLE);
mTargetView.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
mCustomView.setVisibility(View.GONE);
mTargetView.removeView(mCustomView);
mCustomView = null;
mTargetView.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
mContentView.setVisibility(View.VISIBLE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
TvDramaActivity.this.startActivityForResult(Intent.createChooser(i, "Chooser"), 100);
}
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
}
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mClient.onHideCustomView();
}
This works for me :
In your WebView Activity class :
WebView webView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView1 = (WebView) findViewById(R.id.web);
webView1.setWebChromeClient(new WebChromeClient());
webView1.getSettings().setJavaScriptEnabled(true);
webView1.getSettings().setPluginState(PluginState.ON);
webView1.getSettings().setSupportZoom(false);
webView1.getSettings().setBuiltInZoomControls(false);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView1.loadUrl("http://test.swiss-impulse.com/scratch_card_game/index.html");
}
Your layout file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/web"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
Don't forget to add <uses-permission android:name="android.permission.INTERNET"/> in manifest file.
Hope this helps.Thanks.
you can try below code
mWebView.setWebChromeClient(new WebChromeClient());
//support JavaScript
mWebView.getSettings().setJavaScriptEnabled(true);
I am not able to call web service or no alert is being shown:
my activity code:
mWebView = (WebView)findViewById(R.id.webViewRootAciviy);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.loadUrl("file:///android_asset/splashscreen.html");
html code:
<html>
<body>
this is a demo html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js">
$.ajax({
type: 'GET',
url: 'http://192.168.11.50/ar/service.svc/ProductCategories?$format=json',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data)
{
alert("success");
},
error: function (error)
{
alert("error");
}
});
</script>
</body>
</html>
Also given the Internet permission. Please help me find what i missed.
Edit:
We have our own server in our company and service is hosted on it. I am using wifi to access internet and server is also connected to the same wifi router with ethernet cable.
Update: I dont know why this happened. The problem was arised due to the type of service created. The web service was created using WCF Data service, but after creating web service again using normal WCF Service, the URL is working fine now.
apply this to your webview.
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
} else {
return false;
}
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(give your url);
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}