Wednesday, July 31, 2013

Weather & Currency Services

Why don't you try these owesome services.

Weather

http://openweathermap.org/api

This service is amzazing for any of your wheather related application. You can get details of weather for the exact location (latitude & longitude) or city or by city code (if you know. its not zip)

Don't forget to get your app id for services for better service.

Currency

 http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&f=sl1d1t1ba&e=.csv

Just put your first and second currency's code to the parametere and you have the currency exchange rates free from Yahoo.
I tried to change the format but unfortunately no documentation is available and you will always receive in csv format.

Friday, January 18, 2013

Get result from popup window + Javascript

Well, rather than I write. Easy with the example.


a.html

<html>
<a href="#"  onclick="window.open('b.html', '','width=220,height=265');">Get Value</a>
<script type="text/javascript">
function HandlePopupResult(result) {
alert('Result of popup is: ' + result);
}
</script>
</html>


b.html

<html>

Make an action
<a href="#" result="Allow" onclick="return CloseMySelf(this);">Allow</a>
<a href="#" result="Disallow" onclick="return CloseMySelf(this);">Don't Allow</a>
<script type="text/javascript">
function CloseMySelf(sender) {
    try {
        window.opener.HandlePopupResult(sender.getAttribute("result"));
    }
    catch (err) {}
    window.close();
    return true;
}
</script>
</html>



Cheers!!!

Thursday, January 17, 2013

WebView + Video Tag (HTML5) + Play click doesn't show video

New day with new challange

I am having device Samsung Galexy Y Android version 2.3. While running my program suddenly I was bit surprised. I had a video tag in my web page which was being shown in the WebView in my application but when I click on the play button, video play didn't start. I said whatttttttttttt is that :-o :-o
When I run this in the phone's browser it opens up a video player application with the URL whichever was mentioned in the video tag. I started investigating and soon found that the WebView of android 2.3 doesn't support all HTML5 tags and only few HTML5 tags are supported with limitations.
Since I had to make video stuff working so I started looking into. I found that while using the native browser when I click on play button on the video shown on web page some "play" log is coming in the LogCat (By native web browser). I thought if some how I become able to trap the play button click event with the video URL then I'll launch the player by myself instead of being dependent on the WebView. I did a trick to solve this problem.

First of all I injected a script interface in the web page like below.
protected void onCreate(Bundle savedInstanceState) {
   ...
   webView.addJavascriptInterface(new VideoURLRetriever(), "FORM_VIDEO_GETTER");
   ...
}
private class VideoURLRetriever {
        
    public void play(String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse(path), "video/*");
        startActivity(intent);
    }
}

This will be called by javascript engine whenever I want. And now time to inject a specific javascript in the page when page loading is done like below.
private class MyWebViewClient extends WebViewClient {

    @Override
    public void onPageFinished(WebView view, String url) {
    final String JS = "javascript: " + 
                      "var video = document.getElementsByTagName(\"video\")[0];"+
                      "if (video == undefined);" + 
                      "else video.addEventListener('play', playHandle,false);" + 
                      " function playHandle() {javascript:window.FORM_VIDEO_GETTER.play(video.currentSrc);video.pause();}" +
        Log.v("Injecting script for video play");
        view.loadUrl(JS);
    }
}

As above javascrpt describs, it first find's the first video element in the page, registers the play click handler as javascript function and which is captured by the java code in your java class like VideoURLRetriever.play(url). You can add more events and can handle it in your code like above.

Well, I know this is not the ethical way to achieve what I wanted but found this solution as the only way to have my video playing :-; . Also a demerit of using above code is that, each time any page is loaded, a javascript is injected in your page. But that's not important as you want your video to be playing :-)

Cheers!!!

Thursday, January 3, 2013

"Debug Certificate Expired"- Android



Today when I am working suddenly I found in eclipse that error is there with details showing as "Debug certificate expired". Well this is a normal scenario and need to to worry much.

In the case you are a windows based user then go the folder
For WindowsXP
   (OS Drive):\Documents and Settings\\.android
   Example C:\Documents and settings\vkumar\.android
For Windows 7
   (OS Drive):\Users\\.android
   Example - C:\Users\vkumar\.android

and delete the debug certificate.

Clean and build the project you were getting the error for and you are done.

Happy Coding Android !!!

Tuesday, September 28, 2010

Android - onItemClick not being called on the item click of List

Well I am back with another classic problems.
I was making a very rich UI. I had to make a list with items containing check boxes, buttons, ImageView and so many like this and few of them like buttons and check boxes were selectable.
When I ran the application and tried to click an Item which was made up of few text, one button and one Image view, I didn't get callback in onItemClick() method.
I really surprised and thought, what the hell is that. Why not getting callback in the method.
I scratched my head, did so much googling and could not found the answer. When I removed button and check boxes it started getting events. Now I also wanted the event for the click on the buttons and checkboxes it was having.

Suddenly I thought I should make the button and checkboxes non-focusable which were actually getting focus when I was pressing down key on any item, and guess it worked. You should make each and every component in the list item as non-focusable then you would get the event for the click on that items as well as the full item click on event in onItemClick

Cheers!!!

Monday, August 2, 2010

Android - Numeric keypad on the webview

Hi all,

I am back with a new problem and its solution.
The one who is developing application in android and using WebView is pretty much aware that there is no support of HTML5 excluding few tags. Well why I am talking about the HTML5?
I was developing an application and I was on a page where I had to show the numeric keypad for the text field. Probably it would have been very easy if HTML5 was supported. Just put But it is true that till android 2.2 there is no support for this type of field. So what can be done if we desperately need to show the numeric keypad on the WebView's Text box.

Keep watching the blog. Will be back soon with the solution.

Cheers!!!

Wednesday, July 28, 2010

Android - Mutual Authentication Using WebView

Hi all,
I am back with new and a great challenge in the android application.
Using the WebView and send the client certificate.
Confused???

Now start searching over the internet and go line by line of the API documentation of the WebView but after spending 2-3-4...8 days where are we... No solution on the internet.

Now start doing reverse engineering. Go to the source of android WebView and finally at a corner you will find that HTTPS connection is being used by Android OS in low level.

Again after a long search you will find that android.net.http.HttpsConnection class is being used by WebView for all the https connection. When you start looking the code of this class you will find that it always sends the hard coded value as null for client certificate in static variable "mSslSocketFactory". So we are again stuck to solve this problem.

Here comes the Java Reflection which can be used to solve this problem. If android has not revealed any API to set this variable then use reflection to set your client certificate which will be recognized by server.
Below source tells how can it be achieved.

Initialize WebView and before calling the

webview.loadUrl("https://www.myserver.com");
call the below method code.

private void setClientCertificateConnectionPicker(InputStream input, String password) {

try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance("X509");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(input, password);
keyManagerFactory.init(keyStore, "changeit".toCharArray());
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {

public java.security.cert.X509Certificate[] getAcceptedIssuers() {
Log.d(TAG, "getAcceptedIssuers--Checking issuers");
return null;
}

public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
Log.d(TAG, "checkClientTrusted--Checking client authentication");
}

public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
//Validate your server here
for (int i = 0; i < certs.length; i++) {
Log.d(TAG, "\t" + certs[i].getIssuerX500Principal().getName());
Log.d(TAG, "\t" + certs[i].getIssuerDN().getName());
}
}
}
};

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new java.security.SecureRandom());
// BELOW STATMENTS USES JAVA REFLECTION TO SET THE CLIENT
// CERTIFICATE AS
// SSL SOCKET FACTORY.

Class c = Class.forName("android.net.http.HttpsConnection");
Field[] fieldlist = c.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
if (fld.getName().equals("mSslSocketFactory")) {
fld.setAccessible(true);
fld.set(null, sc.getSocketFactory());
}
}
} catch (ClassNotFoundException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- Class not found", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- IllegalArgumentException", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- IllegalAccessException", e);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- NoSuchAlgorithmException", e);
} catch (KeyStoreException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- KeyStoreException", e);
} catch (CertificateException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- CertificateException", e);
} catch (IOException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- IOException", e);
} catch (UnrecoverableKeyException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- UnrecoverableKeyException", e);
} catch (KeyManagementException e) {
Log.e(TAG, "--setClientCertificateConnectionPicker-- KeyManagementException", e);
}

}




And here you go.

Write me for any issue in this.

Three Cheers to Authentication!!!