Computers


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. I even had to buy myself one after hearing how amazing it was. Luckily, I was able to find some pretty good deals online (more right here).

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.


Mobialia Chess Engine for Android

The new version 2.0 adds the support to play online on freechess.org (FICS). You can play against people all around the world and compare your chess knowledge with this engine we’re creating. Thousands of hours of entertainment with this new version.

This needs to be a comprehensive chess engine, with full understanding of all rules and moves along with the ability to vary the level of AI difficulty.

Other features will include 1 and 2 player functionality, choice of board/pieces, undo last move, move animations etc

Please provide details of any previous projects that may be relevant, If we like the look of your work we will reply with a detailed game brief.

Bidders should have previous experience in developing apps and games and be familiar with Android OS. There is the potential for an IOS version at a later date so experience in Xcode would be a bonus.

Require a turnaround within 14 days of accepting project so would be suited to someone who has already developed a similar title.

Also has many improvements on the interface and gameplay, which makes Mobialia Chess 2.0 the best chess app for Androidso you can play it with the best accessories from sites like HotRate online, like headsets or android controllers.

Try it! The LITE version is free, and the complete version is available for only 1.99 EUR at the Android Market and if you like playing more from a desktop computer or laptop you can find out more here about this awesome website for every type of online gaming, so you can start your chess tournament from your android or laptop from home !

Check all the Mobialia Chess for Android features at http://www.mobialia.com/chess


Manifesto: Na defensa dos dereitos fundamentais en Internet

justiciaAnte a inclusión no anteproxecto de lei sobre a economía sostible das modificacións lexislativas que afectan o libre exercicio das liberdades de expresión, de información e o dereito de acceso á cultura a través de Internet, os xornalistas, blogueiros, usuarios, profesionais e creadores de Internet manifestamos a nosa firme oposición ao proxecto, e declaramos que …

  1. Os dereitos de autor non poden estar por riba dos dereitos fundamentais dos cidadáns, incluíndo o dereito á privacidade, a seguridade, a presunción de inocencia, a tutela xurisdicional efectiva e a liberdade de expresión.
  2. A suspensión dos dereitos fundamentais é e debe seguir sendo unha competencia exclusiva do Poder Xudicial. Nin un peche sen unha sentenza. Este anteproxecto, ao contrario do disposto no artigo 20.5 da Constitución, pon en mans dun corpo non xudicial, un organismo dependente do Ministerio de Cultura, a potestade de poder impedir o acceso dos cidadáns españois a calquera páxina web.
  3. A nova normativa vai xerar inseguridade xurídica en todo o sector tecnolóxico español, perxudicando unha das poucas áreas de desenvolvemento e futuro da nosa economía, dificultando a creación de empresas, introducindo barreiras á libre competencia, e trabando a súa expansión internacional.
  4. A nova lexislación proposta ameaza aos novos creadores e dificulta a creación cultural. Coa Internet e os sucesivos avances tecnolóxicos democratízase drasticamente a creación e emisión de todo tipo de contidos que xa non veñen principalmente das tradicionais industrias culturais, se non de moitas fontes distintas.
  5. Os autores, como todos os traballadores teñen dereito a vivir do seu traballo con novas ideas creativas, modelos de negocio e actividades relacionadas coas súas creacións. Tentar de soster con modificacións lexislativas unha industria anticuada que non sabe adaptarse a ese novo ambiente non é xusto nin realista. Se o seu modelo de negocio baséase no control das copias dos traballos e na Internet non é posible sen violar os dereitos fundamentais, terán que atopar un outro modelo.
  6. Cremos que as industrias culturais precisan para sobrevivir de alternativas modernas, eficaces, credíveles, accesíbeles e que atendan os novos usos sociais, en vez de limitacións tan desproporcionadas coma ineficaces para o fin que afirman perseguir.
  7. Internet debe funcionar libremente e sen interferencias políticas patrocinadas por grupos que buscan perpetuar modelos de negocio obsoletos e impedir que o coñecemento humano siga sendo libre.
  8. Demandamos que o Goberno asegure por lei a neutralidade da rede en España, ante calquera presión que poida ocorrer, como un marco para o desenvolvemento dunha economía realista e sostible para o futuro.
  9. Propoñemos unha reforma real dos dereitos de propiedade intelectual co fin de: retornar á sociedade o coñecemento, impulsar o dominio público e limitar os abusos das entidades xestoras.
  10. Nunha democracia as leis e as súas modificacións deben ser aprobadas despóis do debido debate público e de ter consultadas todas as partes implicadas. É inaceptable que se fagan modificacións lexislativas que afectan os dereitos fundamentais nunha lei non orgánica e que trata de outro tema.

Carballo Chess Engine 0.3

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


Opera Mini 5

operaI’ve been using Opera Mini 4 for 1 year and I prefer it over the Symbian integrated browser because is faster, simpler and smaller. Now Opera announced the avaiability of an Opera Mini 5 Beta. The main new features are:

– Speed Dial with captures of the pages, like in the desktop version. I don’t use Opera for the desktop but the “Speed Dial” plugin for Firefox is one of my favourites. Also Is not very intuitive to edit a dial (pressing 1).
– Tabbed browsing: not very usable, too many clicks to change the tab till I discovered the shortcut (* ->).

    Well, it also has touchscreen support but I couldn’t test it in my N95. I didn’t noticed improvements in page rendering: some pages continue to fail (especially with flash), and I need to see them in the Symbian browser.

    The only inconvenience over the previous version is that the time to load the application has increased a lot and that is a bit less fluid; let’s see if with the final release this is solved. The beta can be downloaded at:

    http://www.opera.com/mini/next


    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.


    Port de Sphider a PostgreSQL

    postgresqlAcabo de publicar una modificación del excelente motor de búsqueda Sphider para que funcione con PostgreSQL. Esta modificación  la hicimos en Ingeniería de Prefabricados S.L. para la nueva web coporativa del Grupo Castelo.

    Curioso ver como miles de proyectos dejan de lado a PostgreSQL cuando es muy superior a MySQL (o al menos en mi modesta opinión), lo cual demuestra una vez más, como en la guerra del VHS contra el Beta, que la calidad técnica no está relacionada proporcionalmente con el éxito.


    Yahoo! oneSearch

    onesearchNunca vi muy útil la aplicación de búsqueda de Google que pulsando el botón “lápiz” en los Nokia te abre una caja de texto en la que puedes introducir los términos a buscar.

    No obstante, esta semana he probado una aplicación de Yahoo!, el oneSearh Shortcut, que viene a hacer lo mismo pero con un toque diferente, ya que puedes pulsar el botón verde y dictar lo que quieres buscar, cubriendo mediante reconocimiento de voz el cuadro de búsqueda. Para hacer el procesado del audio se conecta a un servidor de Yahoo!, no con mucho éxito en la mayor parte de los casos, al menos de momento, pero promete.

    Muy útil para no dejarse los dedos en los incómodos teclados de los móviles. ¿Será posible que con iniciativas como esta Yahoo! recupere el esplendor de épocas pasadas?