Saturday, October 05, 2013

AndroVM network setup for android apps testing

not sure how i got to, but the idea to have a faster emulation for android apps testing was great so when the time came i decided to put some time and set this up

the original source claimed that setting 'bridged adapter' worked for him so i followed this advice didn't work

this unleashed a couple of hours of testing different variants, scratching my head and searching on the web (btw is getting better, and while the results are not so comprehensive as google's, they still manage to provide the most essential hits, most of the time).

the search lead me to this result at, which in turn got me playing with virtualbox's host-only settings, and then after a moment of tense expectation...nothing...

another search lead me to this article:, where they mention that actually it is not the first adapter that needs to be configured, but the second one...back some testing which again didn't provide anything

i should mention that on virtual box i was looking into the androVM configuration screen, where the IP of the device did show up a couple of times, but i could never connect with adb.
i also installed terminal emulator on the virtual box device - i was surprised an first that it managed to connect to internet and download the app from market.

so after scrapping all the previous advices i started experimenting again and finally one of the combinations worked:

the only one, actually that worked is this:

host-only adapter on Adapter1
bridged adapter on Adapter 2

don't ask me why it worked, but in the end it did.
strange thing is that androVM  configuration screen doesn't show the ip. the terminal shows it in netcfg. also make sure the bridge adapter is bound to the actual working network adapter

now i have to figure out why my ActionBarSherlock application works on 2.2-2.3 devices, but the bar is not shown on 3.0, 4.0 etc... any ideas?

p.s. eclipse has no problem detecting the 'device' started on androVM, just tell it to detect running Android devices, connect to yours and off you go...

Thursday, September 19, 2013

image is rotated after camera preview in portrait mode (android)

this was quite a headache.
in surface preview (portrait) everything is fine, but once you save the image it turns out it is stored rotated on 90 degrees. what the heck?!

it seems a huge problem with some phones and checking some groups, android team has no intention to fix this, claiming it is manufacturer problem. ok.

there are many useful  discussions on (of course) with different suggestions. some of them quite ugly. i tried to go with the one to rotate the image back before saving, but then you cannot do this in every case because in landscape everything seems to work fine...grrrr...

ok, first lets see how may we know what mode we're in (landscape/portrait)

again a bunch of hacks and solutions...
- "width>heigh? you're landscape"
- check in mode the file itself was saved via exifinterface:
             exif = new ExifInterface(file.getAbsolutePath());

- blah blah blah

here's the one that works for me:
        Configuration newConfig = parentActivity.getResources().getConfiguration();
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Log.v(LOG_TAG, "detected landscape mode");
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.v(LOG_TAG, "portrait mode detected");
 so how do we use this info?


now if we rotate the camera (and we're sure we're in the bloody portrait) will it save what is sees correctly? Noooooooooooo, the images is again rotated incorectly

ok, so lets rotate the image as well then

but here is another darn problem; "Out Of Memory" exceptions - first we get the byte[] of the image, then we create a bitmap out of it, and then try to rotate with a Matrix. well, you can't - BOoooM!

at least on my humble device

so you have to come up with some trick i guess

using square's excellent picasso wouldn't do the trick because even if it may rotate the image when it loads it, it cannot save it rotated back to storage.

wait a second, did you say "rotate the image when it loads it"?

so here is how we can trick the trickster - rotate the image on loading!

but we have to know if the image even has to be rotated, what if it has been saved in landscape mode and all is good? do we have to, like, open the file and read some information from it? blah...

well - there is an easier way - just give the file such a name that you'll know it has to be rotated when loaded, then it gets as easy as PI:

        if (filename.contains("MUSTBEROTATED")) {
            Picasso.with(activity.this.getApplicationContext()) //
            .load(new File(filename)) //
            .resize(screenWidth, screenHeight)
        else {
            Picasso.with(activity.this.getApplicationContext()) //
            .load(new File(filename)) //
            .resize(screenWidth, screenHeight)

and thats about it i guess

what remains to be seen is how this will work on devices that do not have this portrait nightmare problem...probably doesn' much for hacking glory...

Tuesday, September 03, 2013

rotate image in android apps

i guess i'm starting to learn a thing or two about organizing my stuff, and as result decided to post the result of one task that is a part of a bigger task, that is a part of an idea that i'm already getting tired of chasing...

my app has to display images and i want to be able to rotate them! sounds simple, and it is! especially with the miracle of Internet, GOOG and

so we have this imageview...
  ImageView imageView = (ImageView) findViewById(;

we're loading some picture onto it...
 Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

and turns out there is this lovely Matrix class, that exists for all kind of math abuses
                 Matrix mat = new Matrix();

so we can take the original bitmap and apply the matrix operation on it
                  Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), mat, true);

and when we set this image on the imageView we expect to see the rotated image, right?

but somewhere something is wrong or some manual has not been read, cause a vital piece is missing: you have to set scale type on the imageView, (before assigning the new image?)

now this will work fine and will leave this highly uninformative post online, so i can remember how i did it!

i simply don't have the time to research the why's and do's - at least not right now that i'm still in prototyping phase and the steam has already began to ...steam away...
i lost a few days (all right - couple of hours over few days) with the rotate images problem and at least it made me learn to split bigger tasks into smaller ones - and how effective and helpful it can be!

Monday, August 26, 2013

android freeze

weirdest thing happened while i was experimenting with api.
i was testing on a 2.2 device and of course there were the problems with
Camera.getNumberOfCameras() missing etc, but when i got to the point to get a handle to the camera with a simple - nothing happened!

literally, because the app froze and nothing would unfroze it. it even blocked other applications trying to use the camera, and that until reboot of the device.

i thought maybe it happened because i was on the ui thread, but even as i pushed the camera code to an AsyncTask,doInBackground(), while the ui thread was responsive there was never response from the async portion

weird, a?

i read this was only fixed about API 5 releases and 3 years later. wow!

the obvious workaround is to use intent as i was originally planning, but is this really such a big, unsolvable problem? certainly there are apps that are using the api so how do they manage to workaround it? or maybe the problem is gone in the method, which is introduced in 2.3

in any case, android is fun. i wonder if you'd agree with this statement if you we're working on it for money under strict client requirements...

UPDATE 2013/09/06:

So there is a way to get handle of the camera, as i suspected in involves SurfaceView which i didn't want to get much into at the time of the previous writing as i was planning to use intent, but actually there are many examples for using SurfaceView out there and here is the code that worked for me:

    protected void onCreate(Bundle savedInstanceState) {


        surface_view = new SurfaceView(getApplicationContext());
        addContentView(surface_view, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

        if (surface_holder == null) {
            surface_holder = surface_view.getHolder();

        sh_callback = my_callback();
    SurfaceHolder.Callback my_callback() {     
        SurfaceHolder.Callback ob1 = new SurfaceHolder.Callback() {

            public void surfaceDestroyed(SurfaceHolder holder) {
                  mCamera = null;

            public void surfaceCreated(SurfaceHolder holder) {
                mCamera =;

                  try {
                  } catch (IOException exception) { 
                        mCamera = null; 

            public void surfaceChanged(SurfaceHolder holder, int format, int width,
                    int height) {
        return ob1;

this is all from the wonderful post at by Bharat Sharma

a very nice example of actually taking a picture is here:, by user jiahao

so stackoverflow has been getting huge over the view years, i still remember one of its founders writing a post about dreaming about such a hub of help for developers/admins and all kinds of people looking for qualified answers - well done!

Tuesday, January 01, 2013

hello github

i posted the code for the android app i mentioned earlier in github here:

since the app itself was my coding test for android platform, a good decision was to use it as test of github :)

must say that github's windows app is pretty cool, although i thought it was capable to do more - tortoiseSvn style maybe? still checking things around so it may turn more powerful yet, for now i'll do mostly with the git console

grasping git easier as i have svn experience, but i realise the two differ a lot, but i guess it is mostly on a higher/architecture level

in any case, it would be nice if someone found the code useful, and maybe even make it better

enjoy and a Happy New Year

2013 yeyyyy!

Thursday, October 04, 2012

my first complete android app

well, what can i say - it is fun to program for android; i enjoy java and the android apis are ok.
my own android phone is quite old, running android 1.5 so i had to write for api level 3.
i see some improvements in the following apis, when i have time i'll probably try to root and upgrade to 2.1 (no intention to buy a new phone yet).

what else can i say - eclipse is great! so great, i started using it at work, instead of kdeveloper. it definitely is an accomplished platform

on the app itself - it irritated me that there was no sound notification for missed calls, so i thought, why not write one myself (it is only a few days ago, about 4 months since i started working on and off on this app that i found out that there already were couple of solutions for this on the droid market - which is absolutely not surprising).

first of course there was the alarm manager api, but i quickly dismissed it.

i decided to go with a service that checks the status of the calls periodically. but how often should this period reoccur? what if we miss some important notifications?

so i decided to hook the incoming calls intent (actually PhoneStateListener). this worked quite well - after the call is finished, if it wasn't answered my app plugged in and started sounding the alarm every few seconds.
this eventually completed the flow.

there was something strange that i observed. actually the biggest horror a developer may stumble upon - the app worked fine in the emulator, but occasionally when deployed on the phone it wouldn't pick the missed call and remain in obscure state.

so what do you do when you don't know what you program does? hook a logger and watch what your program says it is doing. after some staring at the logger output, it turned out that the system database i read phone calls from (android.provider.CallLog.Calls) registers the (missed) call a few seconds later than the call occured. unfortunately this mismatches the app's own timeline and so - the notification never gets to be fired. the fix was to wait a few seconds before quering the database.

so now i have some more confidence in my app and can show it to the world. i don't think anyone will pay attention, but the satisfaction of getting to "do something" and bring it to completion is priceless.

now if i can only find my way around to actually figuring out how to publish to google play market...

Tuesday, October 02, 2012

fun with specialized function templates in c++

i was quite sad a few days ago for a reason some of you may be familiar with all to well:
a program was working fine in debug, but didn't return results in release build. luckily this was not in production (phew).

what valgrind said was that some variables weren't initialized. my setup is such that i had to refactor a templated class and add a few templated methods, which were specialized in a few locations. everything built fine and seemingly the workflow shouldn't have allowed for uninitialized variables when the specialized function templates were called. eventually and only in the impossible case that the base template function was called. which was impossible to happen, because the compiler would now to instantiate the correct specialization, right?

right, but not exactly. a few debug prints proved that in release the impossible happened - the base template function was called instead of the specialization. but why??
all the arguments should be giving clear directions to the compiler which function to create and call, so why wasn't it? why my beautifully crafted specialization functions were not called??!!

ok, i tried not specializing, but overloading - something similar to this GOTW, but it didn't quite fit, so on went the struggle making the compiler SEE the specialized templates. what if the argument is not const, what if the number of argument varies, what if the return value is different.
but you have to remember that in debug build everything works fine, so then the compiler does know about the specialization and invokes it, so it isn't the code, may be it is in the compiler settings, or the linker? or the compiler it self??

btw, a simple test case that is similar to the situation worked fine in debug and release:

struct TestStruct
    int intValue;
    char * charValue;

    TestStruct() : intValue(0), charValue(NULL) {};

unsigned int templatedFunction(const T& value)
    assert(false && "not implemented");
    return std::numeric_limits::max();

class BaseClass
    void callFunction(const CC& value)
#include "template.h"

template <>
unsigned int templatedFunction(const unsigned int& value)
    printf("implemented for unsigned int");
    return std::numeric_limits::max();

template <>
unsigned int templatedFunction(const TestStruct& value)
    printf("implemented for testStruct");
    return std::numeric_limits::max();

int main()
    BaseClass baseClass;

    unsigned int value = 10;
    TestStruct testStruct;

 so what, what, what was happeningggggg

the evident conclusion is in release the compiler decides to ignore the specializations, so can we help it see and use them? turns out the solution is so simple i had to kick myself in the backspace i missed it:

forward declare the specializations in the code location were they will be used

yep, somehow this solved it. i know, it is probably on first page of the book C++ templates 101, but well, how often do you have to write explicitly specialized template functions that will be used in a templated class where one of the template arguments is a function, and the other is the return value of the function?
me, not very often

good luck, keep coding!