Thursday, December 31, 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();

Monday, December 28, 2009

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.

Thursday, December 24, 2009

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,


params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

Wednesday, December 23, 2009

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)
-Pull
-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 cannot be re-read without starting the parsing operation again. A SAX parser works by having the user implement a class with method handlers for various events.

DOM Parser in Android

Syntax for DOM Parsing is,


InputStream is = context.getResources().openRawResource(R.raw.xmlfile);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);


This is the basic syntax for DOM parsing, then according to our requirement, we can take the node, node values, attribute values etc.


NodeList scrNodes = doc.getElementsByTagName("note");
If the node have any attributes, then , we can get it using
NamedNodeMap nnm = scrNodes.item(0).getAttributes();
To get the value of the node,
String value = scrNodes.item(0).getNodeValue();


Pull Parser in Android

XML Pullparser we can directly get through,


XmlPullParser xpp = ctx.getResource().getXml(R.xml.sample);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG)
{
// parse stuff
}
else if (eventType == XmlPullParser.END_TAG)
{
// parse stuff
}
eventType = xpp.next();
}


SAX Parser in Android

Syntax for SAX parser is,


SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
SaxHandler saxHandler = new SaxHandler();
xr.setContentHandler(saxHandler);

public class SaxHandler extends DefaultHandler{
}


Storing XML elements in Database

For storing in database, first open the database and I used proper sql statement through execSQL() for storing elements in database.

The code is,


SQLiteDatabase datbase = ctContext.openOrCreateDatabase("MyDatabase", Context.MODE_PRIVATE, null);
database.execSQL("CREATE TABLE IF NOT EXISTS MyTable (id int(3), value varchar)");
database.execSQL("INSERT INTO MyTable (1, "")");

Thursday, December 3, 2009

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,

Sunday, November 15, 2009

Creating EditText Programmatically in Android

In this tutorial, I am going to explain how to create a EditText programatically, and the different properties, that we can assign to it in Android.

If we want, our EditText to take only numbers. Then the code is,


edit.setInputType(InputType.TYPE_CLASS_NUMBER);


For password style implementation, for the editText, the code is,


edit.setTransformationMethod(new android.text.method.PasswordTransformationMethod()
.getInstance());


For putting, all letters in caps, the code


InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.AllCaps();
edit.setFilters(filter);


For restricting, only upto this much characters to enter in the editText, the code is,


InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.LengthFilter(15);
edit.setFilters(filter);


In this, I am restricting the characters upto 15 characters.

For moving the editText horizontally or vertically, the code is,


edit.post(new Runnablepublic void run() {
edit.offsetLeftAndRight(50);
edit.offsetTopAndBottom(100);
}
});

Tuesday, November 10, 2009

Creating Menu & SubMenu in Android

In this tutorial, I am going to explain, how to create options menu, subMenu etc..

From Activity class, just override the method, onCreateOptionsMenu(). Then inside the method, create the menu, according to our wish.

Then, override another method called, onOptionsItemSelected. In this, if we select any, menu, what we have to do, will code in this. That means, menu events will be handled in this method.


public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case 0: Toast.makeText(this, "clicked Menu 1",
Toast.LENGTH_SHORT).show();
break;
case 1: Toast.makeText(this, "clicked Menu 2",
Toast.LENGTH_SHORT).show();
break;
case 2: Toast.makeText(this, "clicked Menu 3",
Toast.LENGTH_SHORT).show();
break;
}
return true;
}



The screenshot will be look like this.



For adding submenu, we have to use the function called addSubMenu(), in the Menu class

the code is,


public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SubMenu sub = menu.addSubMenu(0,1,0, "SubMenu");
sub.add(0,11,0,"SubMenu 1");
sub.add(0,12,0,"SubMenu 2");
sub.add(0,13,0,"SubMenu 3");
return true;
}



The screen shot of this is like this..



When click in the sub menu, we will see the screen like this..


Saturday, October 24, 2009

Creating SubActivity, Passing data to SubActivity and Retrieving data from SubActivity

In this tutorial, I am going to explain about the subactivity in Android.

The basic thing that I am going to explain in this tutorial is,

From a main activity calling another activity or subActivity, passing data to the subActivity using startActivityForResult() and retrieving information from the subActivity using the callback function called onActivityResult().

The UI contains TextView, EditText and a button. Whatever we type in the editText will appear in the next activity.

First we will pass data from main Activity to subActivity using Bundle. We can put all primitive data types and String to bundle. Bundle will take data as Key/Value pair. Then we will put this bundle into the Intent using intent.putExtras(bundle). We will pass this intent object to startActivityForResult() with a REQUEST_CODE.

In subActivity, we will retreive the data using


Bundle bundle = this.getIntent().getExtras();

Then by passing the desired key, we will get the values using get method.

Seems so easy, right ??

The final part is retrieving information from subActivity :: This is done through the method called setResult()

Same like in mainActivity, whatever we want to retrieve, will put in bundle, then in intent. Pass this intent to setResult() with a RESULT_CODE. In mainActivity we will receive the information in onActivityResult().

The source code of the program is,

Code for mainActivity,


public class PassingData extends Activity {

EditText text;
Button next;
String name;
TextView statText, retData;
static int REQUEST_CODE = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

statText = (TextView) findViewById(R.id.stat);
retData = (TextView) findViewById(R.id.retdata);
statText.setVisibility(TextView.INVISIBLE);
retData.setVisibility(TextView.INVISIBLE);

text = (EditText) findViewById(R.id.text);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
name = text.getText().toString();
text.setText("");
Bundle bundle = new Bundle();
bundle.putString("name", name);
Intent intent = new Intent(PassingData.this, RetrievePage.class);
intent.putExtras(bundle);
startActivityForResult(intent, REQUEST_CODE);
}
});
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Req code : "+requestCode, "Req code : "+requestCode);
Log.i("Result code : "+resultCode, "Result code : "+resultCode);
statText.setVisibility(TextView.VISIBLE);
retData.setVisibility(TextView.VISIBLE);
retData.setText(data.getCharSequenceExtra("Value"));
}
}





Code for subActivity,



public class RetrievePage extends Activity {

String retrievedData;
TextView viewData;
static int RESULTCODE = 2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieivepage);
Bundle bundle = this.getIntent().getExtras();
if(bundle != null) {
retrievedData = bundle.getString("name");
viewData = (TextView) findViewById(R.id.redata);
viewData.setText(retrievedData);
}
Bundle b = new Bundle();
b.putString("Value", retrievedData);
Intent intent = new Intent();
intent.putExtras(b);
setResult(RESULTCODE, intent);
}
}

Friday, October 23, 2009

Blinking effect on an Image

In this tutorial, I am going to explain blinking an image using Handler. Actually, this is an extension of SplashScreen.

In nutshell, what this tutorial is going to explain is,
An Image will be visible for one second and for the next second, it will be invisible. I am doing this using two handlers. One for making the image visible and another for making the image invisible.

First in onCreate() method, I am calling the first handler called "splashHandler" using sendMessageDelayed() method. I am passing an object of Message and variable of data type "long", its for how long the image has to invisible. Then from "splashHandler", I am calling another handler called "resumeHandler" for making the image visible. In this also, I am passing an object of Message and a variable of long type to the sendMessageDelayed() function.

Then from "resumeHandler", again calling "splashHandler with the message object and a variable of long type. So this will run continously and have a blinking effect on the image.

The source code is,


public class SplashScreen extends Activity {

ImageView img;
private final int STOPSPLASH = 0;
private final int RESUMESPLASH = 1;
private final int SPLASHTIME = 1000;
private Message stopMessage, resumeMessage;

private Handler splashHandler = new Handler() {

public void handleMessage(Message msg) {
switch(msg.what) {
case STOPSPLASH:
img.setVisibility(ImageView.GONE);
resumeMessage = new Message();
resumeMessage.what = RESUMESPLASH;
resumeHandler.sendMessageDelayed(resumeMessage, SPLASHTIME);
}
}
};

private Handler resumeHandler = new Handler() {

public void handleMessage(Message msg) {
switch(msg.what) {
case RESUMESPLASH:
img.setVisibility(ImageView.VISIBLE);
stopMessage.what = STOPSPLASH;
splashHandler.sendMessageDelayed(stopMessage, SPLASHTIME);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView) findViewById(R.id.img);
stopMessage = new Message();
stopMessage.what = STOPSPLASH;
splashHandler.sendMessageDelayed(stopMessage, SPLASHTIME);
}

}


I am just taken an image and explaining the flow of the application. The screen shot is just putting for your reference,



For one second, the image will be visible and in the next second, will disappear, so, will have a blinking effect on the image.

Thursday, October 22, 2009

Setting Wallpaper

In this tutorial, I am going to explain, how to set wallpaper through android application. The code for this is,


Intent intent = new Intent();
intent.setAction(Intent.ACTION_SET_WALLPAPER);
startActivity(intent);


We have to give permission also in Manifest file as


uses-permission android:name="android.permission.SET_WALLPAPER/>


The screen-shot for the above program will be as,

Calling a Number

In this tutorial, I am going to explain, how to call to a number through android application. The code for that is,


Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:5556"));
startActivity(intent);


The code is self explanatory, nothing big in it. Then, in the Manifest file we have to give permission too.


<uses-permission android:name="android.permission.CALL_PHONE"/>


The screen-shot of the program - Emulator 5554 calling emulator 5556 in this application as,


Sunday, October 4, 2009

Sending SMS in Android

In this tutorial I am going to explain sending text message from one android mobile to another.

The UI of our application contains just two Editexts, one for sender's number and another for the message body. Then one "SEND" button.

I am going to demonstrate this by opening two different emulators(5554 & 5556). The phone number is the number that we see on top left side of the emulator, ie, here, 5554 & 5556 respectively.

Launch the SMS application on both emulators and start SMSing. You will get the notifcation on top of other emulator.


Now, how to implement the SMS Application. The main part of the application is the method sendSMS() and it takes two parameters, Sender's number and the content of the SMS.

sendSMS() contains, one object of PendingIntent and a BroadCastReceiver to send SMS.
PendingIntent contains an Intent and a target action and the return object can be handed on a different application, so that, the action that we described can be performed at a later stage. Then, the BroadcastReceiver to broadcast our SMS, textmessage.

The sourcecode for sendSMS() is,


public void sendSms(String phoneNumber, String message) {
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
// after SMS sending
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}

}
}, new IntentFilter(SENT));

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, sentPI,
null);
}



We need to do one last thing, we have to put permission in Manifest file for sending and receiving SMS as,


<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>


In this, emulator, 5554, sending a message to 5556.





and, emulator 5556, replying to 5554 as,

Friday, October 2, 2009

Rotating a bitmap in Android





Here, we have an image of globe and I am going to rotate it.

In Android, we can rotate a bitmap in canvas. Its simple, but we have to know the save() and restore() methods in Canvas class.

We can load a bitmap using


Bitmap globe = BitmapFactory.decodeResource(context.getResources(), R.drawable.globe);


in onDraw() method,

we can rotate the bitmap using

canvas.roatate() method. But here the problem is, the whole canvas will rotate. But by using, save() and restore() we can solve this problem.

Before rotating the, just call


canvas.save() then, call
cavas.rotate(degree)
degree+=5;

then, draw the image. After drawing the image, just call canvas.restore().

This will solve the problem of rotating the whole canvas.

To show, canvas is restored, I am drawing a text after drawing bitmap in canvas by,
canvas.drawText("Here our globe is rotating", 50, 400, textColor);
In the end of onDraw, just call invalidate();

Now, our globe will rotate.





and the text under the globe is static.

This will do.

If you have any queries, about my post, feel free to contact @ nithin.warier@gmail.com

Happy to help You....

Sunday, September 27, 2009

Include attribute in Android

Include tag in android is used to add an layout XML file to another file. Here I am showing a simple way, to do this.


<include layout="@layout/newfile"/>

Here, "newfile" is the name of another layout file

Happy Coding...

Thursday, September 24, 2009

Reading Contacts from mobile and calling

Before coming to Contacts, first I will touch a bit on Content provider in Android

Content Provider

ContentProvider in android is mainly used to share data between applications. Android has some built-in ContentProviders. They are


-Contacts
-CallLog
-MediaStore
-Browser
-Settings
-SMS


We store data into contentProvider using contentprovider base class. We will store data in any way, generally, using Sqlite database.

We will retrieve data from contentprovider using a single interface called ContentResolver. We can get a object of contentResolver using getContentResolver().

One main thing we require for retrieving data from content provider is the URI.
To get contact list, to the query(), just pass "People.CONTENT_URI".


Cursor c = getContentResolver().query(People.CONTENT_URI, null, null,
null, null);


We will receive the contact details in a cursor. Its better to use startManagingCursor(c). Because then Android ,itself will take care of the cursor, means when activity is stopped, it will call deActivate() automatically on the given cursor. When activity restarts, it will call requery() and at the time of destroying an activity, all the cursors will be closed automatically.

In this program, I am just showing the name and number of the persons in the contact list. We can display lot of data about contact persons like email, notes, ringtone assigned, photo assigned etc. For displaying data, I am first putting all the data in a listAdapter using,

ListAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c, new String[] {
Phones.NAME, Phones.NUMBER }, new int[] {android.R.id.text1,android.R.id.text2 });

The output will look like this in emulator,





Next part is calling the displayed numbers by just clicking on the list. For that, I am going to use onListItemClick(). To know which item in the list, the user clicked, I am using, listAdapter.getItem(position), will give the item clicked. Intent.ACTION_CALL is used for calling a particular. For dialing a number, we have to
use the Uri "tel:".

Another important thing is, we are going to start a new task(Calling), so we have to add the flag "Intent.FLAG_ACTIVITY_NEW_TASK" to the intent.

When we click on any contact, the dial screen will look like this,



After call ends, when we click back button, it will come back to our application.

The full source code is,


public class AndContacts extends ListActivity {

private ListAdapter listAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Cursor c = getContentResolver().query(People.CONTENT_URI, null, null,
null, null);

startManagingCursor(c);
listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c, new String[] {
Phones.NAME, Phones.NUMBER }, new int[] {
android.R.id.text1, android.R.id.text2 });
setListAdapter(listAdapter);
}

protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = ((Cursor) listAdapter.getItem(position));
long phoneNumber = c.getLong(c.getColumnIndex(People.NUMBER));
String num = "tel:";
num += Long.toString(phoneNumber);
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(num));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}

Wednesday, September 23, 2009

Gradient In Android



Gradient are drawn in android using GradientDrawable.

The code is,


GradientDrawable grad = new GradientDrawable(Orientation.LEFT_RIGHT,
new int[]{0xffffffff, 0xffff00ff, 0xffffff00,
0xff0000ff, 0xf0f0f0f0, 0xfefefefe});
grad.setBounds(0, 0, 320, 480);


then, in onDraw(), just call

grad.draw(canvas);

The entire source code is,


public class AndGradient extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new ViewGradient(this));
}

class ViewGradient extends View {

GradientDrawable grad;
public ViewGradient(Context context) {
super(context);
grad = new GradientDrawable(Orientation.LEFT_RIGHT,
new int[]{0xffffffff, 0xffff00ff, 0xffffff00,
0xff0000ff, 0xf0f0f0f0, 0xfefefefe});
grad.setBounds(0, 0, 320, 480);
}

public void onDraw(Canvas canvas) {
super.onDraw(canvas);
grad.draw(canvas);
}
}
}

Thursday, September 17, 2009

Creating dashed circle and bulls eye(Marker)





In this tutorial, I am going to explain how to create dashed line or circle.

All we have to do for dashed circle, create a paint object with some special settings. To paint object we have to set some properties. Android have a class called "DashPathEffect".


DashPathEffect dashPath = new DashPathEffect(new float[]{5,5}, 1};


Then to paint object, we have to attach this "dashPath" by,


paint.setPathEffect(dashPath);

then

paint.setStyle(Style.STROKE);
paint.setStrokeWidth(3.0f);

Then in onDraw(), use this paint object in the drawCircle().

The complete source code is,


public class AndDashedLine extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new ViewDashedLine(this));
}

class ViewDashedLine extends View {

Context mContext;
Paint linePaint;
Paint dotPaint;
Paint linePaint1;
DashPathEffect dashPath;
public ViewDashedLine(Context context) {
super(context);
mContext = context;
dashPath = new DashPathEffect(new float[]{5, 5}, 1);

linePaint = new Paint();
linePaint.setAntiAlias(true);
linePaint.setARGB(255, 255, 0, 0);
linePaint.setPathEffect(dashPath);
linePaint.setStyle(Style.STROKE);
linePaint.setStrokeWidth(3.0f);

dotPaint = new Paint();
dotPaint.setAntiAlias(true);
dotPaint.setARGB(255, 255, 0, 0);
dotPaint.setStyle(Style.FILL);

linePaint1 = new Paint();
linePaint1.setAntiAlias(true);
linePaint1.setARGB(255, 255, 0, 0);
linePaint1.setStrokeWidth(3.0f);
}

public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(160, 200, 40, linePaint);
canvas.drawCircle(160, 200, 20, linePaint);
canvas.drawCircle(160, 200, 4, dotPaint);

canvas.drawLine(160, 160, 160, 130, linePaint1);
canvas.drawLine(160, 240, 160, 270, linePaint1);
canvas.drawLine(200, 200, 230, 200, linePaint1);
canvas.drawLine(120, 200, 90, 200, linePaint1);
}
}
}

Creating Static Label




In this tutorial, I am going to explain custom label.

For drawing label, we have to draw two same round rectangle with two differnt paint objects. First paint object will fill the inside color


Paint textDialog = new Paint();
textDialog.setARGB(255, 220, 220, 220);
textDialog.setAntiAlias(true);


and second paint object for the border color, here I am giving green color for border,


Paint borderDialog = new Paint();
borderDialog.setARGB(255, 0, 255, 0);
borderDialog.setStyle(Style.STROKE);
borderDialog.setStrokeWidth(3.5f);


Now, for drawing in onDraw(), we have to draw two round rectangle as,


canvas.drawRoundRect(rectDialog, 7, 7, textDialog);
canvas.drawRoundRect(rectDialog, 7, 7, borderDialog);

rectDialog, is the area on which, I am going to draw, here its

RectF rectDialog = new RectF(100, 100, 200, 130);

and 7 is the radius for the round rectangle.

For drawing inside the label, I am creating another Paint with some other funcionalities.

Paint textPaint = new Paint();
textPaint.setARGB(255, 0, 0, 255);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setTextSize(15);
textPaint.setAntiAlias(true);

Then, in onDraw, I am writing the text as,

canvas.drawText("Androidians", 105, 120, textPaint);

The complete source code is,


public class AndLabel extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new ViewLabel(this));
}

class ViewLabel extends View {

Paint textDialog;
Paint borderDialog;
Paint textPaint;
RectF rectDialog;
public ViewLabel(Context context) {
super(context);
textDialog = new Paint();
textDialog.setARGB(255, 220, 220, 220);
textDialog.setAntiAlias(true);

textPaint = new Paint();
textPaint.setARGB(255, 255, 0, 0);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setTextSize(15);
textPaint.setAntiAlias(true);

borderDialog = new Paint();
borderDialog.setARGB(255, 0, 255, 0);
borderDialog.setStyle(Style.STROKE);
borderDialog.setStrokeWidth(3.5f);

rectDialog = new RectF(100, 100, 200, 130);
}

public void onDraw(Canvas canvas) {
super.onDraw(canvas);

canvas.drawRoundRect(rectDialog, 7, 7, textDialog);
canvas.drawText("Androidians", 105, 120, textPaint);
canvas.drawRoundRect(rectDialog, 7, 7, borderDialog);
}
}
}

Tuesday, September 15, 2009

Creating View from XML layout

We can create a view from the XML layout file. the way to do this is using,


LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflater(R.layout.main, true);

Wednesday, September 9, 2009

Drawing customized shapes and basic shapes in Android



By extending the View Class, we can draw lot of shapes like circle, triangle, rectangle, rounded rectangle, bitmap, gradientdrawable, customized shape etc. Here I am explaining a few things about that.

Drawing circle, rectangle are straight forward, triangle we can draw using three lines. For customized shapes, we can use "Path" class in Android.

Example :


Path path = new Path();
path.moveTo(160.0f, 240.0f);
path.lineTo(140.0f, 200.0f);
path.addArc(new RectF(140, 180, 180, 220), -180, 180);
path.lineTo(160.0f, 240.0f);
path.close();

This path, we will draw in canvas using,

canvas.drawPath(path, paint);

Monday, August 31, 2009

Intents

Intent objects are a bundle of information. It is used to launch the essential components of an android application, like


-startActivity(intent) for launching an activity
-startService(intent) for launching a service
-sendBroadcast(intent) for launching a Broadcast Receiver


The primary pieces of information of an Intent are


-action and
-data

Action means the action to be performed by the intent like, ACTION_DIAL, ACTION_SET_WALLPAPER etc.

Data means, the data to be operate on.


Two types of intent are
-Explicit Intent
-Implicit Intent


In explicit intents, we explictly define the target component
eg: Intent intent = new Intent();
intent.setClass(this, NextScreen.class);
startActivity(intent);
In this, we explicitly define to go to the NextScreen activity.

In implicit intents, no target component will be there. Actually, it is launching components of other application.

eg: Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
startActivity(intent);

Friday, April 10, 2009

Database Creation in Android

Steps for creating a database , creating table into it, inserting value and fetching the values and displaying in a listActivity

Step-I

First of all, create an object of a database, using,

SQLiteDatabase myDB = null;
myDB = databaseAct.this.openOrCreateDatabase("MyDatabase",
MODE_PRIVATE, null);



Here, "MyDatabase" is the name of database. MODE_PRIVATE is file creation mode. In this mode, only created file can be accessed by the calling application or all application sharing the same userID.

Step - II

Next step is, creating a table in the database. Here, our table name is "MyTable". The command is,

myDB.execSQL("CREATE TABLE IF NOT EXISTS MyTable (lastName varchar, "
+ "firstName varchar, age INT(3));");

Now, we created a table with three fields such as lastName, FirstName and Age.

Step - III

Inserting values into the table using the function, execSQL() executes a SQL statement, not a query

myDB.execSQL("INSERT INTO MyTable VALUES ('Guna', 'Boss', 23)");


Include two more sql statements,

myDB.execSQL("INSERT INTO MyTable VALUES ('Sibi', 'Crazy', 21)");
myDB.execSQL("INSERT INTO MyTable VALUES ('Linodh', 'Shaktiman', 20)");



Step - IV

Now we have to fetch data from database and display in a listActivity.

Cursor cursor = myDB.query("MyTable", null, null, null, null, null, null);


Here, query() function executes a SQL query and return a cursor over the resultSet. And we are passing only table name, second argument is string array, where we can specify which all field we need like this,

Cursor cursor = myDB.query("MyTable", {"firstName", "age"}, null, null, null, null, null);


Step - V

Now we have to store the values in arraylist for displaying.
the code snippet is,

int count = 0;
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
count++;
//fetching from database and adding to arrayList
results.add(count+" :"+cursor.getString(cursor.getColumnIndex("lastName"))
+" "+cursor.getString(cursor.getColumnIndex("firstName"))
+" ("+cursor.getInt(cursor.getColumnIndex("age"))+")");

}


Step - VI

last step is displaying in the screen is,

this.setListAdapter(new ArrayAdapter(databaseAct.this,
android.R.layout.simple_list_item_1, results));


The full source code is,

public class databaseAct extends ListActivity {

SQLiteDatabase myDB = null;
ArrayList results = new ArrayList();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


//creating database
myDB = databaseAct.this.openOrCreateDatabase("MyDatabase",
MODE_PRIVATE, null);
//creating table
myDB.execSQL("CREATE TABLE IF NOT EXISTS MyTable (lastName varchar, "
+ "firstName varchar, age INT(3));");
//inserting into table
myDB.execSQL("INSERT INTO MyTable VALUES ('Guna', 'Boss', 23)");
myDB.execSQL("INSERT INTO MyTable VALUES ('Sibi', 'Crazy', 22)");
myDB.execSQL("INSERT INTO MyTable VALUES ('Linodh', 'Shakthiman', 20)");

Cursor cursor = myDB.query("MyTable", null, null, null, null, null,
null);
int count = 0;
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
count++;
//fetching from database and adding to arrayList
results.add(count+" :"+cursor.getString(cursor.getColumnIndex("lastName"))
+" "+cursor.getString(cursor.getColumnIndex("firstName"))
+" ("+cursor.getInt(cursor.getColumnIndex("age"))+")");
}

//display in screen
this.setListAdapter(new ArrayAdapter(databaseAct.this,
android.R.layout.simple_list_item_1, results));

}
}

Androidians