java


Using two location providers on Android 2


Android has two kinds of accuracy on location:

  • Fine: provided by the GPS, needs some time to be obtained
  • Coarse: location determined with the cell of the mobile network

This location methods can be enabled or disabled by the user on the preferences or with some widgets.

Initially on our apps we used only one LocationProvider with “Fine” accuracy:

  • If the GPS was disabled it used automatically network-based location
  • But if GPS was enabled, the location used it needing some time to be determined

As the data couldn’t be obtained until the location is determined, the app didn’t showed data, receiving this kind of error reports from some users.

The best solution that I found is to mantain two separated providers, with different precisions and receive location updates using both.

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);       

criteria.setAccuracy(Criteria.ACCURACY_FINE);
String providerFine = manager.getBestProvider(criteria, true);

criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String providerCoarse = manager.getBestProvider(criteria, true);

if (providerCoarse != null) {
    manager.requestLocationUpdates(providerCoarse, 5*60000, 100, this);
}
if (providerFine != null) {
    manager.requestLocationUpdates(providerFine, 5*60000, 100, this);
}

You can also check if providerFine and providerCoarse are the same provider. When receiving location, the one received from providerFine must take precedence over the one from providerCoarse. Location’s provider can be obtained with location.getProvider():

public void onLocationChanged(Location location) {
     if (location.getProvider().equals(providerFine)) {
     ...

This is a trick that we are using on our Gas Stations Spain app and also on Wikiplaces (open sourced).


Mobialia at LabAndroid 1

This week I was speaking at LabAndroid, a spanish initiative about Android devices, apps and development.

I developed a special app for this event called “Wikiplaces” and I made the code avaiable as open source on Google Code.

This app shows on a map or on a list places from Wikipedia near your location. I tried to include on it small code snippets for common things like styles on layouts, obtaining location, launching Google Maps Navigation, etc.


Dealing with the “Bitmap Size Exceeds VM Budget” error

One of the most common errors that I found developing Android Apps is the “java.lang.OutOfMemoryError: Bitmap Size Exceeds VM Budget” error. I found this error frecuently on activities using lots of bitmaps after changing orientation: the Activity is destroyed, created again and the layouts are “inflated” from the XML consuming the VM memory avaiable for bitmaps.

Bitmaps on the previous activity layout are not properly deallocated by the garbage collector because they have crossed references to their activity. After many experiments and consulting with the cost of an ecommerce website, I found a quite good solution for this problem.

First, set the “id” attribute on the parent view of your XML layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@+id/RootView"
>
...

Then, on the onDestroy()  method of your Activity, call the unbindDrawables() method passing a refence to the parent View and then do a System.gc()

@Override
protected void onDestroy() {
	super.onDestroy();

	unbindDrawables(findViewById(R.id.RootView));
	System.gc();
}

private void unbindDrawables(View view) {
	if (view.getBackground() != null) {
		view.getBackground().setCallback(null);
	}
	if (view instanceof ViewGroup) {
		for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
			unbindDrawables(((ViewGroup) view).getChildAt(i));
		}
		((ViewGroup) view).removeAllViews();
	}
}

This unbindDrawables() method explores the view tree recursively and:

  • Removes callbacks on all the background drawables
  • Removes childs on every viewgroup

This solved the problem on many of our Mobialia apps.

UPDATE 2011-03-30:

Today @luiskap from SpartanBits told me another good solution: if you don’t need different layouts for portrait and landscape modes, you can make your activity react to orientation changes (avoiding activity destroy) adding to your activity’s manifest: android:configChanges="keyboardHidden|orientation" and overriding the onConfigurationChanged method, calling setContentView reusing the already created views. There is a good explanation on StackOverflow.


Google DevFest 2010

As many of you know, this year I’m involved on Android with my project Mobialia. On February I was on the Android Developer Lab at Madrid and today I returned for the Google DevFest.

The event started with Dave Burke presenting Google Technologies in general. Many jokes about the iPhone (to show the Chrome2Phone extension he send a page about iPhone unlocking from Chrome to a Nexus One). He made the typical Sunspider Javascript Test comparation between a Nexus One with Froyo and an iPad. It also was quite impressive so see GWT Quake2 Port running on Chrome at 50 FPS and the new voice/camera input fields on HTML5.

Then the sessions where split on two lines, I assisted to the Android, Chrome&HTML5 and Maps related.

Our beloved Reto Meier was speaking at the Android Sessions, much more technical than on February’s Android Developer Lab (good!). On his first session he made a great presentation about good and bad practices developing Android Apps (I suggest every android developer to see it!), on the second he speaked in detail about Cloud to Device Messaging and vice-versa. He gave me lots of app ideas using this feature. Finally he swowed us proudly his new Samsung Galaxy Tab and encouraged us to adapt our applications to the new tablet devices.

There were also very short presentations of spanish app developers (eAdventure, LibreGeoSocial, Inmobilia, Sicad and great the one of AnderWeb!).

Next, Paul Kinlan speaked about Chrome Apps and Extensions, the App Store and HTML5 on detail. I’m also very happy to see the progression of HTML5 and how Chrome is leaveraging the innovation towards a better web. Quite funny to see a modified Pacman Doodle controlled with the acceleromers of the iBook. There was also a presentation of Fiabee showing their HTML5 app and Chrome extension.

On the last sessions with Josh Livni talking about maps and presenting the Google Maps API v3, I was very impressed with maps customization, Fusion Tables and the new Google Street view API possibiliting the creation of 360º photos and adding them on specific locations (as inside a bar!).

All the sessions where recorded on video and will be avaiable at the Google DevFest Madrid web site.


Tales of a chess engine developer 1

Chess engine development is one of the most brain-crushing activities I’ve been involved on the last years. Last nigths I was working again on my Carballo Chess Engine with some advances.

First of all I decided to leave Negamax and go with Principal Variation Search (PVS). Also decided to implement separate methods for root nodes, PV nodes and null window searches. On previous experiments PVS was performing worse than Negamax, but I discovered the reason: the aspiration window has some implementation issues with PVS: when the search for a move fails low at the root node the move must be researched enlarging the window.

I was very stranged of why Futiliy Pruning was not working for me, but finally discovered the reason: a simple sign change after evaluation was the reason! Also implemented to store the evaluation values on the Transposition Table (TT).

The next step: why Carballo searched much less depths than other engines, it was due to quiescence search. I was generating checks for the first 4 PLY’s of quiescence, but some other engines not, so this was the reason. I decide to generate only checks on the first PLY of quiescence and only for PV nodes. Also modified a bit the move generation to optimize for quiescence.

During this time also found many interesting bugs, I was storing on the TT the bound and not the score when failing high/low, also on PV nodes is better to use only the TT for ordering and not to return scores from it, this helps avoiding draws. Also found a serious bugs involving time management (was taking as reference opponent’s time) and with contempt factor on IID searches corrupting TT entries. Finally added a Pawn Push Extension and removed the Recapture Extension and now some extensions now depend of the node type.

Running some test tournaments, I hope to get some good results soon and add the improved engine to my Mobialia Chess.


Great GWT UI for Carballo Chess Engine

libgwtsvg-chessLukas Laag has written me about his new  GUI for the Carballo Chess Engine  using the Google Web Toolkit (GWT) and his SVG Graphics Library for GWT, libgwtsvg.

GWT is provided from Google to develop applications in Javascript programming in Java. It conterts the Java code to Javascript, and the application is run on the browser, without any additional plugin.

This interface is quite better than the sample Applet from Carballo, it has move history, legal move hightlighting, and SVN graphics. It can be used from:

http://www.vectomatic.org/gwt/libgwtsvg-chess/libgwtsvg-chess.html

He also wrote an article explaining the difficulties of his project. Thanks Lukas for your work.


Carballo Chess Engine 0.3 2

pawnAt last, the first “stable” release of my chess engine. The main new features are:

  • Static Exchange Evaluator (SEE): the biggest change,  affects move ordering introducing more move generation phases, also affects LMR, etc.
  • New “experimental” evaluation function, with King Safety, X-Ray attacks and improved mobility
  • Recapture extension, also changed a lot the extension mechanics adding fractional extensions
  • Quiescense search now only generate checks the first 4 PLYs and follows only good captures
  • UCI Options: can configure Hash Size, Book, LRM, IID, extensions, the evaluator to use, etc.
  • Bugs with draw detection by the 50 move rule (I was doing at 50 PLY), and lots of other small bugs solved

Finally the Negascout code did not improve results at tournaments, so all the Negascout code is commented in the SearchEngine. I’ll continue to investigate.

With this release I include an package to run the program from chess GUIs like Arena, so now it can be included in “official” tournaments.

ELO at tests had a big increase from last version. Now scores over 2330 ELO points at BT2630 test (from the 2100 of Carballo 0.2). Also the positions solved of the “win at chess” test are now 275 of 300 (from the previous 237/300), well, also helped that the EPD parser had a bug and didn’t work well with positions with more than one solution. In LCT II also scores 2300 ELO. All the tests results are in the SVN, at the folder “testresults”.

But at tournament (playing against other java chess engines), the improvement is not so much. Now I think is over BrembroCE, but remains behind Jonathan Pettersson’s Mediocre, Alf and Frank Walter chess engines. I will center the next testing in tournament play.

Play Against Carballo Chess Engine


Carballo Chess Engine

pawnTwo months ago I read a post about Toledo Nanochess in Microsiervos, and remembered my failed attemps to make a chess program in Pascal/Assembler when I was younger. So 13 years later I wrote my chess program from scratch in Java. I did it in two months at after-hours, reading a lot at the Chess Programming Wiki, and here is the result:

Play Against Carballo Chess Engine

It is a work-in progress, but a good framework to test some ideas in chess programming and good enought to play some interesting games against it (well, actually I am not able to win it, but I am a very poor chess player).

Now I’m mounting my kitchen from Ikea, so I haven’t time to improve Carballo, but in a near future I’ll continue working on it.


Diseño de interiores con Sweet Home 3D 1

Sweet Home 3DEn el mundillo de diseño de hogares es una alegría encontrarse ¡al fin! con uno open source, y que además está hecho en mi lenguaje de programación favorito, Java. Se trata de una aplicación muy fácil de usar, muy apropiada para no profesionales y aunque sólo vale para interiores, la mayoría de la gente es lo que tiene que decidir de su casa, la decoración interior, ya que las paredes y el exterior suelen venir impuestos.

Mediante la tecnología Java Web Start, el programa se puede ejecutar directamente desde su propia página web, http://sweethome3d.sourceforge.net/, siempre que se tenga Java instalado.

Hay una gran cantidad de modelos de objetos para utilizar con el programa, muchos descargables desde varias webs dedicadas al tema, por lo que se puede utilizar para el diseño integral de baños, cocinas, etc. En definitiva, una buena alternativa a otros programas 3d para el diseño de casas.