Category Archives: Android

Android app: out of memory exception

An android app has some limitations when it comes to memory availability. Unlike a normal Java app, you do not have luxury of expanding memory your application uses, as it will be completely dependent on the device on which the app is running, memory available in the phone, number of applications running simultaneously. We will not have control over these external factors so we will need to optimize memory usage on our end.

Some of the techniques I used in one of my last projects which used a lot of images/ bitmaps and hence ran into many memory issues.

  • Use of flags: Set android:hardwareAccelerated=”true” and android:largeHeap=”true” flags in manifest file. Downside is that these flags are only available after android 3.0. More than 50% of android devices still run on gingerbread (2.3+), so this is not a very reliable solution if you are targeting a larger audience. Though worth a try for high end (3.0+) devices.
  • Memory leakage: DVM grabage collection works n principle of JVM garbage collection, that is it will reclaim the memory for an object if there is no reference to it. So make sure when you are done with an object and do not need it anymore, mark the object reference as null.
  • Use minimum space for an object: Design your classes intelligently, for example if you are handling student data and you address details will not be used frequently, create a separate class and initialize the object only when it is required. Remember, if a char can work, don;t use int or long.
  • Objects are always placed on heap: One of my colleagues was wondering that how can an object occupy space, after the method exits, if the object is declared inside a method. Remember, only references are stored in the stack for method, the actual object is always stored in the heap. So the memory will be freed only when next cycle of garbage collection occurs
  • Use Garbage collection: You can call system.gc(); to initiate garbage collection, but this only suggests JVM/DVM to run a garbage collection, you cannot force it.
  • Playing with Bitmaps/ Images: Bitmaps and images take highest amount of memory, so make sure you recycle() bitmaps as soon as you are done using it. Make sure you have removed all references (imageviews/ objects) to bitmap before calling recycle().
  • Handle Activity Stack: If the app can be used back and forth multiple times, it is better to handle the back-front flow in the code, as default back button handling in android needs to keep a tack of activity stack and uses memory for that. Simplest will be to call previous activity on back button through code and always finish current activity before moving to next.

How to store state of Android Application

Ever wondered how the state (form data/ logins) are maintained in our android app. This article helps explaining different modes of maintaining the state

http://www.eigo.co.uk/Managing-State-in-an-Android-Activity.aspx

Accessing localhost from virtual machine or Android Emulator

Two problems- one solution i.e. 10.0.2.2

Sometime back, I faced an issue that I had installed a virtual machine on mu linux machine. I had a server/ website running which I wanted to access from virtual machine. http://localhost/site simply refused to work. A little googling helped with an answer to use http://10.0.2.2/site

Again faced similar issue. Was trying to access local website from within android emulator. Again localhost refused to work. And guess who was the rescuer? yep 10.0.2.2 again :)

How to check logs in Android app

Where does all the statements from Log.v go when we run an Android app on emulator

Go to platform-tools under android sdk and type ./adb logcat

for example
kamal@ubuntu:~/softwares/android-sdk-linux_x86/platform-tools$./adb logcat

Using Reflection with Android

Faced an interesting problem today. In my android app I needed to show some random strings on the UI (textview).  So obvious solution was to add the strings in string.xml (for supproting i18n), and then fetch the text based on the random number generated.

textView.setText(R.id.text_1);

or if random number is 2

textView.setText(R.id.text_2);

and so on

I realized that only change happening is the last one digit, so this is a good candidate for using reflections.

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(field.get(null)));

But this actually gave an Exception for ClassCast, so I realized that field.get(null) is actually returning the resource Id (as shown in R.java class) instead of string value.

The fix found was to use getResources().getString(resource_id) to fetch the string from the resource id

Class c =  Class.forName("com.startpage.mobile.R$string");
Field field = c.getDeclaredField("tip_"+tip);
tipTextView.setText(getResources().getString((Integer)field.get(null)));

Creating a basic Android app

I am exploring Android application development for some new projects so thought about sharing my notes here. So far it is turning out to be fun and very simple :) .

I am using eclipse for development so first of all we will need to install ADT. Follow the steps mentioned here

http://developer.android.com/sdk/eclipse-adt.html

Once we have ADT installed, creating first android project is pretty simple. Create a new android project (right click->new project->Android project).

In the project creation window, provide details-

Provide name say test_project, Choose target say 2.1, package- com.kamalmeet.android.test and activity- test. Skip test project creation and click Finish

Now we will run this project on emulator. Just go to your project and run as ‘android application’, this will give a “Hello World Test” message.

Now let us see what happened when we created and executed the project. When we created a a new project it created some files. Here are the important ones to get started

We will see AndroidManifest.xml in base project directory. This is the root file of our project. This contains details of the activities, services etc for our project. For now you are seeing only one activity under application node in this xml file. Also note the package declaration in manifest, this is the base package of our project.

Now we will check our package under src/ folder. Lets take a quick look into com.kamalmeet.android.test. We see the activity java file test.java. It extends the  parent android.app.Activity class, and has one method it overrides, that is onCreate. No points on guessing that this is the first method getting called when activity loads. For now it has just one line setContentView(R.layout.main);

To understand meaning of this line, lets move to gen/ folder, which has the same package and a autogenerated R.java file. This file gets automatically generated on compilation. It provides a unique Id to all our visible contents. For example, we can see an inner class as layout which has an int main value.

What does this main value corresponds to? Checkout res/ folder. This has all out UI related stuff like images, view XMLS etc. under res we have res/layout/ folder. This is where we have our UI XML, in this case main.xml. As you can see android supports XML defined UI like just Flex, XAML etc. In addition we can define

You can see one node as LinearLayout and a child node of TextView. This is responsible for what we see on UI. We can see test being set as android:text=”@string/hello”. It picks up value from /res/values/strings.xml. In this XML you can see a string node where name is set as hello with value as “Hello World, test!” Change it to any value say “My first Android app” and re-run the application. Simple. Now we can go ahead and play around with this simple UI app.