Computers


A small problem with the facebook Android SDK

At Mobialia the lasts weeks I was involved on the development of a social app using , among other social networks APIs, the facebook API.

For me it was easier to implement Twitter API access using only the signpost library, for facebook they recommend to download their Android SDK, and I did so. First we need a class attribute with the Facebook object:

Facebook fb = new Facebook(appId);

The problem is during the autentication process: we must call the fb.authorize method…

fb.authorize(this, PERMISSIONS, ACTIVITY_CODE, this);

And wait for the result of this called activity on our onActivityResult method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    fb.authorizeCallback(requestCode, resultCode, data);
}

But, here is the problem, under heavy memory requierements (like testing on a old HTC Magic) the caller activity may be killed, and the status of the Facebook object is not maintained so the call to authorizeCallback is going to fail.

Then I need a method to mantain the Facebook object status, and here comes the hack. I added this method to the Facebook object:

public void setStatus(int mAuthActivityCode, DialogListener mAuthDialogListener){
    this.mAuthActivityCode = mAuthActivityCode;
    this.mAuthDialogListener = mAuthDialogListener;
}

And I call this method on my OnActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    fb.setStatus(ACTIVITY_CODE, this);
    fb.authorizeCallback(requestCode, resultCode, data);
}

Note that the DialogListener is the same Activity. Other solution may be to avoid killing of the caller activity, but I don’t figure how…


Mobialia at LabAndroid

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 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 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. Thousands of hours of entertainment with this new version.

Also has many improvements on the interface and gameplay, which makes Mobialia Chess 2.0 the best chess app for Android.

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 go to:

https://chess.mobialia.com

Check all the Mobialia Chess for Android features at:

http://www.mobialia.com/chess


Manifesto: Na defensa dos dereitos fundamentais en Internet

justicia

Ante 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

    pawn

    Two 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.