Showing posts from December, 2009

Opening and Closing Menu Programmatically

API for opening menu programmatically is openOptionsMenu(). If we are in a different context, then we can use this method by,

((Activity) mContext).openOptionsMenu();

For closing menu programmatically, if it opens use this,

((Activity) mContext).closeOptionsMenu();

Reasons for getting java.lang.StackOverflowError

java.lang.StackOverflowError occurs when it does an infinitive autoinvoke.

This StackOverflowError occurs because of two conditions.

-> One is a function calling itself infinite times and
-> When first function calls a second function and second inturn calls the first function. This is a kind of deadlock.

RelativeLayout Programmatically in Android

This article aimed at understanding how we can implement RelativeLayout programmatically. We can initialize the layout normally like

RelativeLayout layout = new RelativeLayout(this);

To position the child to left, right, top or botttom, we have to add rules to the layout params as,


Parsing XML and storing elements in Database in Android

For one of my project I parsed XML file and stored each element in database according to ID. First of all, about parsing, there are three different types of parsing are there in Android as,

-DOM (Document Object Model)
-SAX (Simple API for XML)

A DOM parser works by parsing an XML file into a native data structure matching the hierarchy of the XML file. Most of the processing is done up front and the entire file is looked at, so a DOM parser typically uses the most memory of the three parsers.

A Pull Parser works by creating a loop that continually requests the next event and can then handle that event directly within the loop. The idea with the Pull Parser is that it can easily be stopped at any point, only do processing on demand, and remove the overhead of extra method calls and classes.

SAX parser is an event driven parser. Events are fired, when XML features such as XML text nodes, XML element node etc. are encountered. SAX parsing is uni directional, previously parsed data cann…

Setting Margin for widgets Programmatically

In this tutorial, I am going to explain how we can set margin for widgets programmatically. Using XML, its through layout_marginLeft, layout_marginRight, layout_marginTop and layout_marginBottom.

Actually, I spent a quite some time in this. I tried with this class "android.view.ViewGroup.LayoutParams". But after trying for quite sometime, I realized the actual class, for that is "android.widget.LinearLayout.LayoutParams". We can use any layout, not only LinearLayout. But, it should be from widget package.

The function is setMargins(left, top, right, bottom); the four arguments shows the margin for four sides respectively.

TextView tv = new TextView(this);
LayoutParams params = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.setMargins(100, 20, 0, 0);
layout.addView(tv, params);

The screenshot of the result is,