Loading a Maps API site in a Native Android Application - android

I'm trying to follow the example from google:
http://code.google.com/apis/maps/articles/android_v3.html
Using the example files from their SVN repo:
(http)gmaps-samples.googlecode.com/svn/trunk/articles-android-webmap/
But although it seems to compile and export it fails; can someone sanity check that its not just me this fails for and any hints as to if its a quick thing to fix, I've been prodding it with try/catch for the last 2 hours to no avail.
Thanks :o)
Forgot to add
It Compiles and Uploads to the emulator (and to my phone) but running it just results in
The Application WebMapActivity (process com.google.android.examples.webmap)
has stopped unexpectedly. Please try again. [Force Close]

Filtered it down to
private void setupWebView() {
/*
final String centerURL = "javascript:centerAt("
+ mostRecentLocation.getLatitude() + ","
+ mostRecentLocation.getLongitude() + ")";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
// Wait for the page to load then send the location information
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl(centerURL);
}
});*/
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl(MAP_URL);
}
Bit easier to filter out the actual issue when you know which bit doesnt work thanks to CommonsWare for the great book, poking through that and test-code that ACTUALLY WORKS made it a bit easier to work out what was going on. And thanks for the debug info :o)

Related

Webview doesn't clear history, cache etc

I have an android application that has native framework and content itself is presented in web format and in webview. The meaning of the application is to allow users to use the device using predefined
services that may require autentication.
How ever when I try to clean up the webview caches after user has completed his/her tasks the webview will remember everything and all e.g. login credentials are in place, history remains etc.
I have tried the following to do the clean up without any success, what I am missing in this ?
(wvfo if the overlay fragment in which the webview is that each service is using)
wvfo.getWebView().clearCache(true);
wvfo.getWebView().clearFormData();
wvfo.getWebView().clearHistory();
wvfo.getWebView().clearMatches();
// wvfo.getWebView().setWebViewClient(new WebViewClient());
// wvfo.loadUrl("javascript:document.open();document.close();");
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
wvfo.destroyWebview();
Any ideas what is wrong with this and why the history doesn't get cleared ?
Thanks in advance
Yes, You have to delete webview default DB also. Check the below code.
static void clearWebViewAllCache(Context context, WebView webView) {
try {
AgentWebConfig.removeAllCookies(null);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
context.deleteDatabase("webviewCache.db");
context.deleteDatabase("webview.db");
webView.clearCache(true);
webView.clearHistory();
webView.clearFormData();
clearCacheFolder(new File(AgentWebConfig.getCachePath(context)), 0);
} catch (Exception ignore) {
//ignore.printStackTrace();
if (AgentWebConfig.DEBUG) {
ignore.printStackTrace();
}
}
}
I hope, this will help you.
Happy codding...

Android WebView with AngularJS application route changes not being detected in shouldOverrideUrlLoading

I have been working on a hybrid android application. Currently a WebView in our application is pointing to an AngularJS 1.5.7 application. When the user hits a button inside of the application that changes the route I was expecting the shouldOverrideUrlLoading function to be called inside of my WebViewClient. However, this is not the case. It looks like shouldOverrideUrlLoading does not get hit on Angualar route changes.
This being the case I have gone down the following rabbit holes:
onPageFinished - Overriding this function in the WebViewClient works, however, it is not being called until after the new route is getting hit. Which is adding to the application loading time and creating a choppy experience. ` #Override
public void onPageFinished(WebView view, String url) {
if (url.endsWith("/#/")) {
signOut();
} else if (url.endsWith("/login")) {
// TODO: show some sort of failure message?
Log.i("Login Route", "The webview just attempted to go to the login route.");
signOut();
} else if (url.endsWith("/security")) {
Intent intent = new Intent(getApplicationContext(), SecurityActivity.class);
startActivity(intent);
}
}`
shouldInterceptRequest - Overriding this function allows you to watch for requests. However, by the time the requests go out from the AngularJS application the web view is showing a new route once again providing a choppy user experience.
onLoadResource - same
JavaScriptInterface - Currently I have set up a JavaScript interface to watch for window.location changes. This seems to catch the route changes quicker than any of the above options, however, there is still a glimpse quick flicker of the web page I do not want to do go to. You can find how to do Javascript bridging on this post
Any suggestions would be greatly appreciated! Thanks.

Android 4.4 giving ERR_CACHE_MISS error in onReceivedError for WebView back

I have a webview in my Layout. By default, a search form is opened in it. On search, a listing section appears below the search form. If any link in the list is clicked, the details page opened. Now I want to controlled the back navigation for the webview. I placed this code in Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d("TYPE", TYPE);
WebView myWebView = null;
if (TYPE.equalsIgnoreCase("REPORT_ACTIVITY"))
myWebView = reportView;
if (TYPE.equalsIgnoreCase("FEEDBACK_ACTIVITY"))
myWebView = feedbackView;
if (myWebView != null)
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up
// to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
private WebViewClient webViewClient = new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("onPageStarted", "onPageStarted");
loadProgressBarBox.setVisibility(View.VISIBLE);
//view.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
Log.d("onPageFinished", "onPageFinished");
loadProgressBarBox.setVisibility(View.GONE);
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.d("Error", "Error code: " + errorCode + "/" + description);
}
}
I have also set a WebViewClient with the WebView. When I going back using back button it is working fine for any version 4.4. But when I am trying in Android 4.4, it is coming back fine from details page to listing page. But as soon as I am trying to go back again, its throwing error code -1 and ERR_CACHE_MISS in description. No page is displayed.
09-04 06:59:05.666: D/Error(1102): Error code: -1/net::ERR_CACHE_MISS
How to solve this problem in Android 4.4?
This error actually stems from outside of your application in most cases (occasionally it's just a missing INTERNET permission, but that doesn't sound like the case here).
I was typing out an explanation, but found a much more straightforward example that doubles as an explanation in this answer to another question. Here's the relevant bits, re-hashed a little:
Joe fills in an order form with his credit card information
The server processes that information and returns a confirmation/receipt page that's marked with no-cache in the header, meaning it will always be requested from the server.
Joe goes to another page.
Joe clicks back because he wants to double check something, taking him to the confirmation page.
The problem arises from that last step. The confirmation page was marked with no-cache, so it has to be requested from the server again. But to show the same page correctly, the same data that was passed the first time needs to get sent again.
This results in Joe getting billed twice, since a new request is being made with the same information as last time. Joe will not be a happy camper when he finds two charges on his account and an extra pair of tents on his doorstep.
It seems this situation was common enough that it is now a standard error across most browsers, and apparently, newer versions of Android. The error actually originates from Chromium, which is why you'll see the same error in Google Chrome, and why you only see it in 4.4 (which introduced a new version of the WebView based on Chromium).
In fact, you have actually probably seen it before, it's the message that shows up in most browsers warning you with something along the lines of "To refresh this page, the browser will have to resend data...yada yada yada".
This is Android 4.4's way warning you of what's going on. How to fix it really depends on what you're connecting to, but if you search for this situation, you'll find that it's fairly common, and has fixes. The exact trigger of the error is actually when the request can't be serviced from cache (in this case, no-cache is causing that).
Depending on the nature of the request, maybe no-cache isn't actually needed.
But from your application's perspective, the main problem is, onReceiveError is a sort of "last resort" for the WebView. Errors you get there have propagated from underlying system. And once you end up there, you can't continue the page load as it stands. So you don't have a chance to allow that resend, and you can't give the user that option, unlike, say Google Chrome does.
I ran into the same issue because in my manifest folder I had the Internet permission capitalized:
I had (error)
<uses-permission android:name="ANDROID.PERMISSION.INTERNET"/>
Should have (no error)
<uses-permission android:name="android.permission.INTERNET"/>
Use
if (Build.VERSION.SDK_INT >= 19) {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
It will fix ERR_CACHE_MISS in the WebView.
Maybe you will need to change it to SDK_INT == 19 after some Lollipop WebView updates, but it works for now.
this permission in your andriodManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>

Robotium Test to Extract Cookies from WebView

My Sign Up Process produces cookies in a WebView, not in native code. All my tests depend on the cookies retrieved from the Webview so I need a way to extract data from a webview inside a Robotium test. How can this be done? Here is my WebView fragment:
public class MyWebViewFragment extends Fragment {
private CookieManager cookieManager;
#ViewById
WebView myWebView;
#AfterViews
void theAfterViews() {
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
CookieSyncManager.createInstance(getActivity());
cookieManager = CookieManager.getInstance();
myWebView.loadUrl(theURL);
myWebView.setWebViewClient(new WebViewClient()
{
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if ((url != null) && (url.equals(theURL)))
{
String theCookies = cookieManager.getCookie(url);
// ######## I need to pull these Cookies out here in the Robotium test. How do I use Solo etc to do this?
}
}
}
}
I need to know how to write a Robotium test that will at the right point pull out the values of the Cookies and save it for the rest of the tests to use. I need to get thiw working or none of my other tests will run. Thanks
The simple answer as i think you may know having seen your other questions is to get hold of the fragment and then ask the fragment for the value. Potentially you might consider mocking this functionality out for your tests or allow your tests a method to be able to set the cookies for itself etc (not sure if this is feasible for your case or not.)

Android webview app and Google Analytics

I have a simple native Android app that is a webview of a website, effectively to make the mobile-ready site native-like if you will. The website already has Google Analytics installed.
What might be a good way to track which visitors are using the app?
I could adding Android Native App Tracking, but I presume that would
double track the users. Unless it's smart enough to connect the visits?
I could pass custom get variable to the site that maybe adds a custom
attribute to the tracking for native app users. But that doesn't
sound very clean.
What might be best for tracking? I feel there's got to be an obvious answer I'm missing.
that should help you:
Now getting back to the Analytics tracking of this web app, I used the code provided by Google here.
So the code becomes somewhat like this.
public class myWebApp extends Activity{
Webview mWebview;
GoogleAnalyticsTracker tracker;
protected void onCreate(Bundle savedInstanceState) {
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker in manual dispatch mode. The following UA-xxxxxxx-x code must be replaced by //your web property ID.
tracker.startNewSession("UA-xxxxxxx-x", this);
mWebview = new WebView(this);
mWebview .setWebViewClient(new myWebViewClient());
mWebview .loadUrl("file:///android_asset/www/index.html");
private class myWebViewClient extends WebViewClient
{
//After the user visits a particular page, send the tracking notification to GoogleAnalytics.
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
tracker.trackPageView( mWebview.getUrl());
tracker.dispatch();
}
}
}
http://www.the4thdimension.net/2011/11/using-google-analytics-with-html5-or.html
And in stats of google analytics you should get some info at least about operating system android.

Categories

Resources