App not getting longitude and latitude from HTML and JAVA script - javascript

I have a simple APP that calls a HTTPS page and latitude and longitude don't work when calling https://www.mypage.com/getlonlat.html from within my APP. It works when calling page from IE, Chrome, Firefox ect. getlonlat.html has javascript that uses GeoLocation to calculate longitude and latitude. This page HAS a valid SSL.
package com.mywebsite.webview;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class GeoWebViewActivity extends Activity {
public class GeoWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public class GeoWebChromeClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
}
WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new GeoWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.setWebChromeClient(new GeoWebChromeClient());
mWebView.loadUrl("https://www.mywebsite.com");
if (mWebView.canGoBack()) {
mWebView.goBack();
}
}
#Override
public void onBackPressed() {
// Pop the browser back stack or exit the activity
if (mWebView.canGoBack()) {
mWebView.goBack();
}
else {
super.onBackPressed();
}
}
private void postUrl(byte[] postData,
String url) { mWebView.goBack();
}
}
Index.html
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
document.getElementById("getlat").value = position.coords.latitude;
document.getElementById("getlon").value = position.coords.longitude;
}
</script>

As it turns out, my SSL certificate was not set up properly with my hosting company. The code above works perfectly now. How nifty, call a HTML, PHP, JAVA page from an APP without having to re-write the whole page in android.

Related

Closing dialog inside shouldOverrideUrlLoading() or ignoring in project, when is custom url open

I am trying to auth google user in WebView, I found a good solution for these days, it works fine for google login, but I cannot disable dialog in other urls like (, sms: , smsto:)
Example Situation: User click on telephone number in my app, it will open the phone dial, but when he returns back.. there is a empty dialog window with close button, i use it for google login with JS.
How can i close this dialog message inside the shouldOverrideUrlLoading()? Or is there any better solution to not open other links in the dialog? How can i improve my code to solve my problem? Thank you guys!
package com.example.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.lang.reflect.Field;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends Activity {
private WebView mWebView;
private String userAgent;
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userAgent = System.getProperty("http.agent");
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAppCacheEnabled(false);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUserAgentString(userAgent+ "com.example.app");
mWebView.clearCache(true);
// REMOTE RESOURCE
mWebView.loadUrl("https://example.eu/");
mWebView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
final Context myApp = this;
class CustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
webViewPop = new WebView(contextPop);
webViewPop.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:"))
{
webViewPop.destroy();
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//view.getContext().startActivity(intent);
return false;
}
});
// Enable Cookies
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
cookieManager.setAcceptThirdPartyCookies(webViewPop, true);
cookieManager.setAcceptThirdPartyCookies(mWebView, true);
}
WebSettings popSettings = webViewPop.getSettings();
// WebView tweaks for popups
webViewPop.setVerticalScrollBarEnabled(false);
webViewPop.setHorizontalScrollBarEnabled(false);
popSettings.setJavaScriptEnabled(true);
popSettings.setSaveFormData(true);
popSettings.setEnableSmoothTransition(true);
// Set User Agent
popSettings.setUserAgentString(userAgent + "Your App Info/Version");
// to support content re-layout for redirects
popSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// handle new popups
webViewPop.setWebChromeClient(new CustomChromeClient());
// set the WebView as the AlertDialog.Builder’s view
builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
builder.setTitle("");
builder.setView(webViewPop);
builder.setButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
webViewPop.destroy();
dialog.dismiss();
}
});
builder.show();
builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webViewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
//Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
try {
webViewPop.destroy();
} catch (Exception e) {
Log.d("Webview Destroy Error: ", e.getStackTrace().toString());
}
try {
builder.dismiss();
} catch (Exception e) {
Log.d("Builder Dismiss Error: ", e.getStackTrace().toString());
}
}
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
#Override
public boolean onJsAlert(WebView view, final String url, String message,
JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
})
.setCancelable(false)
.show();
result.cancel();
return true;
}
}
}

How to Load Interstitial Ads from Webview

I am new to android, recently I developed an application which runs on WebView means in my activity I placed a webview doing the gamin activity through html,js pages by loading those to webview.
Here my request is "How to load the Interstitial Ads from the webpage files(html,js) I googled most of the suggestions related to Ionic App but my app is AndroidStudio related.
so please help
Loading an ad from WebView isn't that straightforward but could be done. So let's take the following example:
class MainActivity extends AppCompatActivity {
protected InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load interstitial ad
mInterstitialAd = new InterstitialAd(getContext());
mInterstitialAd.setAdUnitId("YOUR_AD_ID");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
WebView browser = findViewById(R.id.webview);
browser.addJavascriptInterface(new InterceptorJavaScript(context), "Interceptor");
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
browser.setWebViewClient(new CapturingWebViewClient());
browser.loadUrl("http://website.com");
}
/**
* This class will handle all JS events from the UI back to
* Java code and will trigger the Interstitial ad
*/
private class InterceptorJavaScript {
Context webViewContext;
/**
* Instantiate the interface and set the context
*/
InterceptorJavaScript(Context webView) {
webViewContext = webView;
}
#JavascriptInterface
#SuppressWarnings("unused")
public void startInterstitial() {
// we need to run it on the main UI thread
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
#Override
public void run() {
if (MainActivity.mInterstitialAd.isLoaded()) {
MainActivity.mInterstitialAd.show();
}
// preload new ad
BrowserFragment.mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
}
private class CapturingWebViewClient extends WebViewClient {
/**
* This method will inject the JavaScritp that will trigger
* your Java code and show the interstitial in the main UI thread
*/
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl(
"javascript:Interceptor.startInterstitial();"
);
// Attach JS event to your button so you can call the JS function. I've used jQuery just for simplicity
view.loadUrl(
"javascript:$('#btn').on('click', function(){ Interceptor.startInterstitial(); });"
);
}
}
}
hello this is the code....
import android.os.Bundle; import android.view.Window; import android.view.WindowManager;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class a4 extends AppCompatActivity {
AdView mAdView;
InterstitialAd mInterstitialAd;
WebView WebViewWithCSS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_a4);
WebViewWithCSS = (WebView)findViewById(R.id.webView);
WebSettings webSetting = WebViewWithCSS.getSettings();
webSetting.setJavaScriptEnabled(true);
WebViewWithCSS.setWebViewClient(new WebViewClient());
WebViewWithCSS.loadUrl("file:///android_asset/4.html");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
adRequest = new AdRequest.Builder()
.build();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
showInterstitial();
}
});
}
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
private void showInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}

how to properly open google play links on html page in android webview with setWebViewClient?

Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it out so i'll explain in deep detail...Any help would be much appreciated!!!
i have a webpage at http://s-ka-paidbeats.com/app_tree/ourotherapps it lists a bunch of apps i have made in google play.in the webpage html i have them listed with standard links like - https://play.google.com/store/apps/details?id=com.yesorno.app.yesorno
i've created a tab in ALL the android applaications that i've made called "My Other Apps"this tab is a webview window that shows the same html page i was talking about above- http://s-ka-paidbeats.com/app_tree/ourotherapps
the problem is when a user visits the webview window in any of my android applications and clicks on any of the apps i have listed on the html webpage (https://play.google.com/store/apps/details?id=) it takes them to google play in the webview window and asks them to login to google play in the webview window (even if they are already logged in to google play on their device)... this is extremely ugly and annoying for users to face.
i want to make it so when a user visits the "my other apps" tab in any of my applications, and clicks on one of the apps in the webview window it opens the actual google play application (if google play is installed) or opens in the default browser installed on the device (if google play is not installed)
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page and then visited the webview window again in my app however this time when i click on any of the apps listed i just get a page error "page does not exist" window
i have looked into setWebViewClient and i am sure that there is someway to do this using something like the code posted below
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getScheme().equals("market")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Activity host = (Activity) view.getContext();
host.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
// Google Play app is not installed, you may want to open the app store link
Uri uri = Uri.parse(url);
view.loadUrl("http://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery());
return false;
}
}
return false;
} });
I tried adding the code above to my current code but now my loading dialog box wont close when the webview is loading.... it just stays loading forever.... so i took the code snippet above out of my code again because i dont think i am placing it in the right place or that i am integrating the two codes together properly....
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one....... I HAVE NO CLUE where to begin and i have been reading for hours....
Here is my current code
package com.yesorno.app.yesorno;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.yesorno.app.yesorno.NetorkConnection;
#SuppressLint("SetJavaScriptEnabled")
public class OtherApps extends AppCompatActivity {
private WebView webView;
NetorkConnection ntwrk_con = new NetorkConnection(this);
ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView toolsresources5 = (TextView)findViewById(R.id.feedbacktextview);
toolsresources5.setVisibility(View.INVISIBLE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
webView = (WebView) findViewById(R.id.activity_main_webview);
dialog = new ProgressDialog(OtherApps.this);
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
dialog_box_for_internet();
}
}
public void dialog_box_for_internet() {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
// dismis_dialog_box_for_internet = true;
AlertDialog.Builder builder = new AlertDialog.Builder(
OtherApps.this);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_custom_titile, null);
TextView title = (TextView) view.findViewById(R.id.myTitle);
title.setText("Unable To Connect");
builder.setCustomTitle(view);
builder.setMessage("No Internet Connection")
.setCancelable(false)
.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (ntwrk_con.isConnectingToInternet()) {
webView();
} else {
new Thread_for_internet().execute();
}
// dialog.cancel();
}
})
.setNegativeButton("Okay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
// Gridview.super.onBackPressed();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
class Thread_for_internet extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading..Please wait.");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected Boolean doInBackground(String... args) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Boolean result) {
dialog.dismiss();
dialog_box_for_internet();
}
}
public void webView() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
});
dialog.setMessage("Loading All Our Apps...\nPlease wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
webView.loadUrl("http://s-ka-paidbeats.com/app_tree/ourotherapps.html");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean bRet=false;//set true is menu selection handled
switch (item.getItemId()) {
case R.id.action_settings_3:
Toast.makeText(this, Html.fromHtml("<big><b>Develeped By S-Ka-Paid</b></big><br>© 2016 S-Ka-Paid"), Toast.LENGTH_LONG).show();
bRet=true;
break;
case R.id.action_settings_4:
Intent intent2 = new Intent(Intent.ACTION_VIEW);
//Try Google play
intent2.setData(Uri.parse("market://details?id=com.yesorno.app.yesorno"));
startActivity(intent2);
bRet=true;
break;
default:
bRet=super.onOptionsItemSelected(item);
}
return bRet;
} }
Basically My question is HOW CAN I POSSIBLY PUT THESE TWO CODES TOGETHER TO FUNCTION PROPERLY!!! this is killing my trying to figure it outAny help would be much appreciated!!!
i have tried to change all the (https://play.google.com/store/apps/details?id=) links to (market://details?id=) links on the html page
Don't do that. Use the google play URLs you started with.
i noticed my current code already has a setWebViewClient defined so im not sure if im allowed to have two in the same code or if i am suppose to try and combine it with the current one
You combine them. You create one WebViewClient to handle all the needs of one WebView. It's not difficult:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});
for anyone looking for the answer to this... here is the correct code
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// is this a play store URL?
String partialUrl = "/store/apps/details?id=";
if (url.contains(partialUrl)) {
// extract the app id from the URL
int pos = url.indexOf(partialUrl) + partialUrl.length();
String appId = url.substring(pos);
try {
// open the google play app
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + appId));
OtherApps.this.startActivity(intent);
return true; // we overrode the url load
} catch (ActivityNotFoundException e) {
// no google play app, load URL in device browser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
OtherApps.this.startActivity(intent);
return true;
}
}
return false; // no override, let the webview load this url
}
});

Can I show progress dialog and error message while parsing XML using JavaScript?

I am developing android web application for a blog like website.
For this I am showing HTML page contenting list of categories which when clicked shows articles related to that category.
I am fetching this articles from website's RSS feeds which is in XML format and by using JavaScript I am parsing it to display on HTML page.
This process of parsing XML takes lot of time to load a page.During this period I am getting blank screen.I have implemented progress dialog which works fine when page is loading for the first time but when XML is getting parsed by JavaScript it does not appear.
Here is how I implemented Process dialog.
Activity.java:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
webview.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.loadUrl("file:///android_asset/HomePage.html");
// WebChromeClient give progress etc info
webview.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
How can I show progress dialog while XML is being parsed by JavaScript?
Also I want to show an error message if no internet connectivity available for same thing is their any way to do so?
I have used call function as "tel:phone number" which was working but after I added de
public boolean shouldOverrideUrlLoading it is not working? what's i done wrong?
for your questions You can use following code in your activity.java file
package com.package name;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class Myactivity extends Activity {
TextView myLabel;
WebView wv;
final Activity activity=this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
wv=(WebView)findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
return true;
}else{
view.loadUrl(url);
return true;
}
}
});
wv.loadUrl("file:///android_asset/page.html");
// WebChromeClient give progress etc info
wv.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
if (AppStatus.getInstance(this).isOnline(this)) {
Toast t = Toast.makeText(this,"Welcome !!!!",8000);
t.show();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(
CafeNashikActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("No Internet");
// Setting Dialog Message
alertDialog.setMessage("Internet Connection not available!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyActivity.this.finish();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
Hope this will help you.

Binding JavaScript code to Android code

Im trying to invoke a method in java from javascript, but this doesn't happen when I run the application in the emulator, the application stops when it is suppose to call the method in java. here is the java code:
import android.os.Bundle;
import android.webkit.WebView;
import com.phonegap.*;
public class App extends DroidGap {
WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(this);
webView.addJavascriptInterface(new message(), "Show");
super.loadUrl("file:///android_asset/www/index.html");
}
class message {
String msg() {
return "Hello World!!";
}
}
}
here is the javascript:
<script type="text/javascript">
{
alert("Start");
alert(Show.msg());
alert("End");
}
</script>
It shows the first alert but nothing thereafter, can anyone help?
Your problem is that you're half using PhoneGap and half not. You're creating a separate WebView class from PhoneGap's. The WebView class that you added "Show" to never gets used. Instead the WebView class that is a member of the super (DroidGap) is.
You should do one of two things.
Use PhoneGap's plugin structure (see examples here)
Don't use PhoneGap at all and have a class that looks more like the following:
public class act extends Activity {
WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
// Set JS alert() hook
webView.setWebChromeClient(new WebChromeClient() {
public boolean onJsAlert(WebView view, String url, String message, JsResult result)
{
return false;
}
});
webView.loadUrl("file:///android_asset/www/index.html");
// Add JS libraries
webView.addJavascriptInterface(new message(), "Show");
}
class message {
public String msg() {
return "Hello World!!";
}
}
}
Note that the method msg needs to be public
Why not just use AlertDialog?
private void showDialog(int title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}

Categories

Resources