Friday, September 30, 2011

Android sqlite example

Most android apps need persistence of some sort. Sqlite database is one such persistent solution provided by android platform. All android apps can have its own sqlite database.

I have published a new article on my main site Android Sqlite Example which explains how to store and fetch data from sqlite database.

More android tutorials and code samples on zoomified.com

Hi users.

I have launched a new site called Zoomified.com and all these android programming tutorials and much more are available in this site.

Zoomified.com has even more elaborate android code snippets on various topics.

Do provide your support. See you there !!!

Monday, August 29, 2011

Android - Find contact by phone number

In one of my previous article Receiving SMS, I explained how to receive sms and promised to cover how to find the sender contact details.

In this article, I will explain how to lookup an android contact by phone number. There are numerous use cases where you would need this functionality.

private String findContactByNumber(Context ctx,String phoneNumber){
ContentResolver resolver=ctx.getContentResolver();
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
String[] phoneNoProjections = { PhoneLookup._ID,PhoneLookup.DISPLAY_NAME };
Cursor cursor = resolver.query(lookupUri,phoneNoProjections, null, null, null);
try {
if (cursor.moveToFirst()) {
Log.d("Contacts Example:","Contact found");
return cursor.getString(1);
}
Log.d("Contacts Example","lookup completed");
} finally {
if (cursor != null)
cursor.close();
}
return null;
}

In line#7, we specify the fields(columns) that we are interested in. Only these information about a contact will be retrieved. Suppose if you want other information about the contact, then you would have to add it to the array. For a complete list of fields that can be queried refer PhoneLookup API.

Monday, August 1, 2011

Android List view with alternating row colors - contd

In one of previous blog Alternate row colors in ListView, we saw an adapter implementation to achieve alternate row colors. The article failed to explain how to use a custom adapter implementation. Using your own adapter is fairly simple. Look at the below source code for more.

SimpleCursorAdapter mAdapter = new AlternateRowCursorAdapter(this, R.layout.listrowLayout, cursor, columns, to);
this.setListAdapter(mAdapter);

Note that, I am using my own layout file(R.layout.listrowLayout) for laying out each of the row items.

Wednesday, July 20, 2011

How to receive sms in android ?

In this article, I will cover how to write a simple app that can receive SMS. This will also serve as a sample implementation of a broadcast receiver in android.Steps

  • Your receiver class must extend BroadcastReceiver and override onReceive() method. onReceive will be invoked by the android system whenever a sms arrives.

  • To be able to receive sms, you must have the appropriate permissions defined in manifest file.

  • You must register your receiver class in manifest file. You must also specify what intents your receiver is interested in. In our case, its the sms received intent


Source code

public class MessageReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("MyApp:", "Message received");
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
Log.d("MyApp:",str);
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}











for the list of available intents, refer sdk's platform /data/broadcast_actions.txt
Maybe in the next article, I will cover how to find the contact name of the sms sender.

Wednesday, July 6, 2011

How to create dashboard layout in android ?

Ever wondered how to create a dashboard view in android? There is no out of the box layouts to achieve this. But luckily, you don't have to write one. Thanks to Roman Nurik, he has created a custom layout using which you can create a dashboard effect. For other alternatives, you can refer this stackoverflow http://stackoverflow.com/questions/2873568/android-dashboard-pattern question

In this article, i will explain you how to use this layout.

Steps
  • Get the layout source code from https://gist.github.com/882650.
  • Copy the source file to your package. (Be careful about the license and see if it suits you.)
  • Create a layout resource with DashboardLayout as the root layout. See code below.

Source code:



Output:
This will produce something like this.
Do checkout my next article on how to improvise this.

Android - AlertDialog with buttons

In previous article AlertDialog, I explained how to build a simple alert dialogs in android. Here, we will see how to add buttons like yes,no or open,cancel or something of that sort.

Steps:
  • Create your dialog using AlertDialog.Builder
  • Use API methods like setPositiveButton or setNegativeButton or both to add buttons
  • Define handlers or event listeners to the buttons.
Sample code
public class MyActivity extends Activity {
private AlertDialog confirmBox = null;
/*
* Other parts of code,omitted.
*/
private void createDialog(){
confirmBox = new AlertDialog.Builder(MyActivity.this).setTitle("Confirm").setMessage("Are you sure you want to delete this entry?").
setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/**
* TO:DO add code to handle this action.
*/
MyActivity.this.confirmBox.dismiss();
}
}).setNegativeButton("No",null).show();
}
}
As you can see, setNegativeButton() and setPositiveButton() takes two arguments. The first argument is the label/caption for the button. In our case it is the yes and no . The second argument is the onclickhandler. You can also supply null if you want android to take default action applicable. In the above example, we have supplied a handler for positive button and null for negative button.


Result