Android webview ajax - java

I have wep application which some pages have to do ajax requests to get and update that pages without refresh the page.
My problem when I use android WebView to load that wep application. all pages that request ajax doesn't update the page which means the ajax requests don't work.
here is the code of MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_layout);
webView = (WebView) findViewById(R.id.webView);
webView.clearCache(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
new AlertDialog.Builder(view.getContext())
.setMessage(message).setCancelable(true).show();
result.confirm();
return true;
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Toast.makeText(view.getContext(), "onPageStarted", Toast.LENGTH_SHORT).show();
super.onPageStarted(view, url, favicon); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void onPageFinished(WebView view, String url) {
Toast.makeText(view.getContext(), "onPageFinished", Toast.LENGTH_SHORT).show();
super.onPageFinished(view, url); //To change body of generated methods, choose Tools | Templates.
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowContentAccess(true);
webSettings.setUseWideViewPort(true);
webView.loadUrl("http://192.168.1.236:8080/mobile/android.html");
}
and the android.html have ajax request. the android application works fine and load the android.html but without getting the ajax data

Finally I've found the answer after 3 Long days.
the problem was in the page that I request which have this code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
in the response which conflict with android webview and doesn't work with jquery selectors ... Don't know why!!!
but when I removed the above code from response the page and its ajax works fine.
P.S: all my pages are xhtml not html.

Check if you have <uses-permission android:name="android.permission.INTERNET" /> in your AppManifest.xml file.
If javascript in the loaded page makes requests to some site other than http://192.168.1.236:8080 and that site does not allow Cross-Origin XMLHTTPRequests, then these requests will fail due to security restrictions of WebView.

Try this
WebView web=(WebView) findViewById(R.id.webView1);
web.getSettings().setJavaScriptEnabled(true);

You can add AJAX handler into your web-view for handle any website with AJAX.
public class Main2Activity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
webView.getSettings().setJavaScriptEnabled(true);
initWebView();
loadURL();
}
private void loadURL() {
webView.loadUrl("www.google.com");
}
#SuppressLint("JavascriptInterface")
private void initWebView() {
webView.setWebChromeClient(new MyWebChromeClient(Main2Activity.this));
webView.addJavascriptInterface(new AjaxHandler(Main2Activity.this), "ajaxHandler");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
}
});
}
public class AjaxHandler {
private static final String TAG = "AjaxHandler";
private final Context context;
public AjaxHandler(Context context) {
this.context = context;
}
public void ajaxBegin() {
Log.e(TAG, "AJAX Begin");
Toast.makeText(context, "AJAX Begin", Toast.LENGTH_SHORT).show();
}
public void ajaxDone() {
Log.e(TAG, "AJAX Done");
Toast.makeText(context, "AJAX Done", Toast.LENGTH_SHORT).show();
}
}
private class MyWebChromeClient extends WebChromeClient {
Context context;
public MyWebChromeClient(Context context) {
super();
this.context = context;
}
}
}

Related

Unable to Load PDF File in the Webview

i have a question. I developed a project with webview component but i cannot display pdf files in the webview, because in the website link all pdf files opened with new tab and pdf file is authentication with user session. I tested this website link on the Official Android Chrome app all pdf files is opened and automatically downloaded PDF files in the mobile storage but on webview component i cannot display this.
Please could you help me for this topic. Thanks in advance.
My code is:
public class MainActivity extends AppCompatActivity {
private WebView webView = null;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webView = (WebView) findViewById(R.id.webview);
CookieManager.getInstance().setAcceptCookie(true);
this.button = (Button) findViewById(R.id.button);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setDomStorageEnabled(true);
String DESKTOP_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36";
webView.getSettings().setUserAgentString(DESKTOP_USER_AGENT);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#SuppressLint("InlinedApi")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
CookieSyncManager.getInstance().sync();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri videoUri = Uri.parse(url);
intent.setDataAndType( videoUri, "application/pdf" );
intent.setPackage( "com.example.webview" );
startActivity( intent );
view.loadUrl(url);
return true; // to tell the WebView that it should not load the URL because you handled it by yourself
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
showDefaultError();
}
#Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
super.onPageFinished(view, url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
//put your code here if your want to show the progress with progressbar
}
});
webView.loadUrl(“MY LINK”);

Loading created by ProgressDialog wouldn't stop , how to hide progressbar when page is loaded

I'm new to Java and was trying to create a web-view app. The loading widget was created using Progress Dialog but it wouldn't stop. I don't know what is wrong. Please help.
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...",true);
mywebView = (WebView) findViewById(R.id.webview);
mywebView.getSettings().setJavaScriptEnabled(true);
mywebView.getSettings().setSupportZoom(true);
mywebView.getSettings().setBuiltInZoomControls(true);
mywebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
});
mywebView.loadUrl("https://google.com");
mywebView.setWebViewClient(new WvClient());
}
private class WvClient extends WebViewClient
{
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
handler.proceed();
}
}
#Override
public void onBackPressed() {
if(mywebView.canGoBack())
{
mywebView.goBack();
}
else
{
super.onBackPressed();
}
}
}
You have declared setWebViewClient twice , ie after load url you again
declared the setWebViewClient with your custom client , correct answer is
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...",true);
mywebView = (WebView) findViewById(R.id.webview);
mywebView.getSettings().setJavaScriptEnabled(true);
mywebView.getSettings().setSupportZoom(true);
mywebView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if(pd!=null && pd.isShowing())
{
pd.dismiss();
}
}
});
mywebView.loadUrl("https://google.com");
}
#Override
public void onBackPressed() {
if(mywebView.canGoBack())
{
mywebView.goBack();
}
else
{
super.onBackPressed();
}
}
}
Place a breakpoint in
onPageFinished
and see if the listener actually get called?

Reload Same URL in Webview An When Refresh Page

I created a little android app to view a responsive website. I have implemented a pull refresh and it works, however when pulling on refresh it redirect to the home page I put in the LoadUrl. How to refresh by reloading the same url the user is visiting ?
My java code:
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb()
{
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
//tiga baris dibawah ini agar laman yang dimuat dapat
//melakukan zoom
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
//baris dibawah ini untuk menambahkan scrollbar didalam webview-nya
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl("http://example.com");
swipe.setRefreshing(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
webView.loadUrl("file:///android_asset/error.html");
}
#Override
public void onPageFinished(WebView view, String url) {
//ketika loading selesai, ikon loading akan hilang
swipe.setRefreshing(false);
}
});
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
if (webView.getProgress()==100){
swipe.setRefreshing(false);
}else {
swipe.setRefreshing(true);
}
}
});
}
}
Thanks in advance
In Swipe Refresh layout call webView.reload();
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
}
});

Java - WebView What event handles (watches) URL changes - Android

The app does a login to a web application using WebView. Once in the webview, the webview appears to handle everything for you as it should based on the user's clicks. However I need to review on each event if the URL changes to a specific logout URL.
How can I return the user to the app itself when the user logs out on the web application within the webview? I do not want the webview to stay as the active view.
I have tried WebViewClient.shouldOverrideUrlLoading and View.OnTouchListsner.
The class I tried to implement public but it didn't allow me.
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
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
Here's the code before I want to call the method to check the URL;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText phone = (EditText) findViewById(R.id.phone1);
final EditText login = (EditText) findViewById(R.id.uname);
final EditText pass = (EditText) findViewById(R.id.password);
phone.requestFocus();
final Context context = this;
submit = (Button)findViewById(R.id.submit);
sbutton = (Button)findViewById(R.id.loginCred);
chcred = (CheckBox) findViewById(R.id.cBox);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textstring(phone, login, pass);
encPhone = URLEncoder.encode(Phone);
encLogin = URLEncoder.encode(Login);
encPass = URLEncoder.encode(Pass);
if (chcred.isChecked()) {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
prefwrite(editor);
}
pushurl();
clear(phone, login, pass);
}
});
WebViewClient() //Right here is where I want to call it
This can help you:
https://developer.android.com/reference/android/webkit/WebViewClient.html#onPageStarted(android.webkit.WebView, java.lang.String, android.graphics.Bitmap)
The event does not notify you when the url changes, but does when the page starts to load, at that point you only need to verify the current url.
Try This
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
Uri uri = Uri.parse(url);
if (uri.getScheme().contains("google") || uri.getScheme().contains("tel")) {
try {
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if (intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
return true;
} catch (URISyntaxException use) {
Log.e("TAG", use.getMessage());
}
} else {
webview.loadUrl(url);
Log.e("url", url);
}
return true;
}
#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);
}
#Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
String currentUrl=view.getUrl();
}
});
webView.loadUrl(url);
here webView is my WebView and url is the url which I am using in my webview.
If you want to make some changes with the change in url,then go for
#Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
String currentUrl=view.getUrl();
}
you will get the url updation in this call.

How do i make my progress dialog dismiss after webview is loaded?

What do I need to my code to make the dialog dismiss() after the webview is loaded?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new homeClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.loadUrl("http://google.com");
ProgressDialog pd = ProgressDialog.show(Home.this, "",
"Loading. Please wait...", true);
}
I've tried
public void onPageFinshed(WebView view, String url){
pd.dismiss();
}
Didn't work.
:o
webview.setWebViewClient(new homeClient()); homeClient()????
try this
...
...
...
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
webview.loadUrl("http://www.google.com");
}
Update::
this is a good example.
Android WebView and the Indeterminant Progress Solution
This is OK.
public class WordActivity extends Activity {
private WebView webview;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
Bundle objetbunble = this.getIntent().getExtras();
webview = (WebView) findViewById(R.id.webview);
final Activity activity = this;
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Chargement en cours");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
});
webview.loadUrl("http://www.example.com");
}
}
#Jorgesys this is not 100% accurate. If you have several iframes in a page you will have multiple onPageFinished (and onPageStarted). And if you have several redirects it may also fail. This approach i think solves all the problems:
boolean loadingFinished = true;
boolean redirect = false;
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
webView.loadUrl(urlNewString);
return true;
}
#Override
public void onPageStarted(WebView view, String url) {
loadingFinished = false;
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
//HIDE LOADING IT HAS FINISHED
} else{
redirect = false;
}
}
});
How are you accessing pd in onPageFinshed()? (And are you sure it's actually called when the page loads?)
In your onCreate(), try passing pd to your homeClient so that homeClient can take care of dismissing the dialog.
Your homeClient should look like this:
private class homeClient extends WebViewClient {
private ProgressDialog pd;
public homeClient(ProgressDialog pd) {
this.pd = pd;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished (WebView view, String url) {
if (pd.isShowing()) {
pd.dismiss();
}
}
}
In your onCreate():
ProgressDialog pd = ProgressDialog.show(Fbook.this, "",
"Loading. Please wait...", true);
webview.setWebViewClient(new homeClient(pd));
If you simply want to show Progress before webPage loading in WebView. You can simply request for Window Feature Progress like
getWindow().requestFeature(Window.FEATURE_PROGRESS);
before setContentView(R.layout.blahblah);
and show it progress in onProgressChanged like
final Activity context= this;
webview.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView webView, int progress)
{
activity.setProgress(progress * 1000);
}
});
And if you want to add you own ProgressDialog then use WebviewClient
webView.setWebViewClient(new WebViewClient() {
ProgressDialog rogressDialog ;
#Override
public void onPageStarted(WebView view, String url, Bitmap bitmap) {
progressDialog = ProgressDialog.show(context, "Loading...", "Please wait...");//where context = YourActivity.this;
super.onPageStarted(view, url, bitmap);
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog .dismiss();
super.onPageFinished(view, url);
}
});
webView.loadUrl(url);
wv1.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(Entertainment.this, description, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
String webUrl = wv1.getUrl();
}
});
wv1.loadUrl(url);
The above code will show a progress dialogue for every incoming link you navigate to the in webview.

Categories