Archive for Java

Android and https

I recently had to deal with using https with Apache’s http libraries. Not a simple task. If you just create a Uri with https in front of it, and your SSL certificate isn’t from a trusted authority, or if you’re using a self-signed certificate, you’re in for a world of hurt.

There’s a lot of solutions out there, and most of them involve trusting everyone, which isn’t so secure. The best solution I found is here:

Crazy Bob: Trusting SSL Certificates

It’s reasonably secure, but in order to use it, you’ll need the 1.6 JDK. You don’t need the Android SDK to create the needed keystore.

[UPDATE]

That method works if you’re only going to one domain. All other domains stop working with that method. A better method can be found at this Stack Overflow question:

http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/6378872#6378872

The code here appends your KeyStores to Android’s list, which is a much better solution. You’ll still need the method for generating a keystore in the first link.

Comments off

Slow Android autocomplete in Eclipse Helios

Eclipse Helios has been slow for me for awhile, and it finally annoyed me enough to try to google a solution.

This guy found a good, relatively easy fix.

Basically, you’re just downloading the Android source, and adding it to your Android SDK directory. Hit the link for full details.

Comments off

Google analytics drops metrics in Android if you send them too quickly

I just ran into this problem with the Google Analytics SDK for Android (v0.8). Basically, if you try to send too many pageviews too quickly, the tracker gets overwhelmed and forgets to track some of them.

My solution was just to space things out a bit with Timers and TimerTasks. I have a small wrapper around the analytics tracker, which has a timer, a static inner TimerTask class, and a long which is the soonest that a pageview should be sent. Whenever you want to send a pageview, you just call recordView, which looks like this:

public void recordView(String metric) {
        // The current time.
        long time = new Date().getTime();
        // We keep track of the next appropriate time to send a metric with sendTime. sendTime only gets updated
        // when we try to send something,
        if (this.sendTime > time) {
                time = this.sendTime;
        }
        this.sendTimer.schedule(new TrackTask(this, metric), new Date(time));
        // I have sendInterval set to 2000, meaning pageviews are sent at a minimum, two seconds apart.
        this.sendTime = time + this.sendInterval;
}

Then, TrackTask looks like this:

protected static class TrackTask extends TimerTask {
        //
        private WeakReference ref;
        private String metric;

        public TrackTask(Metrics met, String metric) {
                // WeakReference to avoid memory leaks.
                this.ref = new WeakReference(met);
                this.metric = metric;
        }

        public void run() {
                // try catch block because our WeakReference has the possibility of being GCed out from under us.
                try {
                        this.ref.get().tracker.trackPageView(this.metric);
                        this.ref.get().tracker.dispatch();
                } catch (NullPointerException e) {
                }
        }
}

Comments off

Android memory leaks

Since I’ve been banging my head against this for the last 12 hours, I thought I’d post a solution here, so other people might stumble across it and benefit.

I ran into two memory leaks in Android itself in WebView, and Typeface. Both are because of bugs in the OS, so if you’re encountering memory leaks, and all your code looks pretty watertight, (Meaning you never pass Activities as a Context to a View, and you use WeakReferences for static inner classes) you might be hitting one of these.

The first bug for WebView is described here.

The solution is just to call destroy() on your webview in the onDestroy() method of the containing activity, then set any references to that WebView to null, just in case. The app I’m working on is webview heavy, so this was causing some grief.

The second bug for Typeface is described here.

The issue was that I was creating a new Typeface from assets in the onCreate method of my activity. Every time I did this, it was allocating around 700k of memory, which then never got released. Big, big problems. The solution in this case is to initialize the typeface object in a static class (You can subclass Application and stick it there if you want, but be aware that you can’t call getAssets() before the first activity gets it’s onCreate method called.) and then use that one instance for any TextViews you may have.

The only way I managed to figure out what was causing the leaks was to go into adb shell, and then use dumpsys meminfo. That showed me a whole lot of bad.

Comments off

Loading images from jar files in windows

In the first version of the server app, I was telling Windows users to start the program by clicking on a .bat file because for some reason, the thing wasn’t starting up when clicking on the .jar file directly.

I’d seen other apps that did start from the jar file just fine, and after a lot of hunting around, I figured out why. When you search google for load image from jar file, most of the hits have you getting a URL object like this:

URL url = this.getClass().getResource("the_image.jpg");

then using that to load the actual image.

This works just fine on OSX, and Linux, but does absolutely nothing on Windows for some reason. Instead, on Windows, you have to get a JarFile object for the jar you’re loading from, then get a ZipEntry (JarEntry, whatever) from that, then get an InputStream from the ZipEntry, turn that into a BufferedInputStream, then pass that off to your default Toolkit to turn into an image.

Of course this means you have to figure out whether the app’s being run in a jar file in the first place or not. This is how I’m doing it:

URL fileURL = this.getClass().getProtectionDomain().getCodeSource().getLocation();
String sBase = fileURL.toString();
if ("jar".equals(sBase.substring(sBase.length()-3, sBase.length()))) {
	MyClass.jar = new JarFile(new File(fileURL.toURI()));
}

after that, you can load the image ike this:

Image imReturn = null;
try {
	if (jar == null) {
		// This is used if you're not loading from a jar
		imReturn = this.toolkit.createImage(this.getClass().getClassLoader().getResource(sImage));
	} else {
		//
		BufferedInputStream bis = new BufferedInputStream(jar.getInputStream(jar.getEntry(sImage)));
		ByteArrayOutputStream buffer=new ByteArrayOutputStream(4096);
		int b;
		while((b=bis.read())!=-1) {
			buffer.write(b);
		}
		byte[] imageBuffer=buffer.toByteArray();
		imReturn = this.toolkit.createImage(imageBuffer);
		bis.close();
		buffer.close();
	}
} catch (IOException ex) {

}
return imReturn;

Comments off

Related Links

Resource Links