Categories
Android

A new Android/Windows Mobile phone

I found this on Russian site of AndroidTeam(androidteam.ru) that a company called Compulab is going to release a new phone called Exada which will run both Android and Windows Mobile. This phone will provide left and right click capability. It will provide a large number of control keys (buttons) and has an ethernet port. I wonder if that is supposed to be a replacement for USB or if it’s a regular ethernet port.  Below is the picture of the phone :

Exada
Exada
Categories
Android

Android and Alarms

Since I joined the Android user groups, there have been a lot of questions about 2 things – databases and alarms. I have already written a post about how to use a database in Android and in this one, I will talk about how to use Alarms. If there are any other topics you would like to see a tutorial on, please feel free to let me know. You can leave your requests in the comments section. Oh, and this post (like previous posts) is for Android 1.0.

Alarms in Android are not used in a conventional way. When your application sets an alarm, it’s just telling that alarm service to wake it up at a certain time. The user won’t hear any sounds and the phone won’t vibrate (unless your application plays a sound or makes the phone vibrate after it wakes up). Alarms will work if the device goes to sleep but they are cleared if the device is turned off or restarted. So, you will need to set the alarm again if you want it to “go off” even after a device re-boot.

Our receiver class will be called “AReceiver” (without the quotes, of course). In the manifest file, we will add this line (which is in bold below):

<application android:icon=”@drawable/icon5″ android:label=”@string/app_name”>
<activity android:name=”.SomeApp” android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<receiver android:name=”AReceiver” android:process=”:remote” />

Now, that the alarm receiver is set, lets take a look at the class that will set and cancel the alarms:

package SomeApp.SomeApp;

import java.util.Calendar;

import java.lang.String;

import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.util.Log;

import android.content.Intent;
import android.widget.Toast;

/**
 * When this code is run only one alert will be displayed even though 2 alerts were
 * were setup (as one of them will be cancelled later on
 */
public class SomeApp extends ListActivity {
	/* for logging - see my tutorial on debuggin Android apps for more detail */
	private static final String TAG = "SomeApp "; 

	protected Toast mToast; 

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

		Calendar cal = Calendar.getInstance();

		Intent intent        = new Intent(SomeApp.this, AReceiver.class);
		PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
		PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0);

		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+30000, sender); // to be alerted 30 seconds from now
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+15000, sende2); // to be alerted 15 seconds from now

		/* To show how alarms are cancelled we will create a new 		Intent and a new PendingIntent with the
	 	* same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567.
         	* Note: The intent and PendingIntent have to be the same as the ones used to create the alarms.
         	*/
		Intent intent1        = new Intent(SomeApp.this, AReceiver.class);
		PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0);
		AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE);
		am1.cancel(sender1);

        } catch (Exception e) {
        	Log.e(TAG, "ERROR IN CODE:"+e.toString());
        }
    }

}

You will notice that this is only a “one-shot” alarm. If you want to set a repeating alarm, it is explained in Android’s documentation. However, I will write on that too if there is demand for it. Now, let’s examine the code. For setting an alarm, you will need 4 things:

  • The class that’s setting the alarm
  • The class that will be called when the alarm “goes off”
  • The time at which the alarm should go off
  • A requestCode (which will use as a unique ID to identify the alarms) used in PendingIntent.

For cancelling an alarm, you need 3 things:

  • The class that set the alarm
  • The class that was to be called when the alarm “goes off”
  • The requestCode you used for PendingIntent object.

We have covered 2 things – the declaration of the receiver in our manifest file and the class that sets and cancels alarms. Now, we need to look at the class that will be called when the alarm goes off.

package someApp.someApp;

import java.util.Calendar;

import android.content.Context;
import android.content.BroadcastReceiver;
import android.util.Log;
import android.widget.Toast;

/** All receiver classes must extend BroadcastReceiver */
public class AReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context con, Intent in) {
		try {
			/* Display an alert */
			Toast.makeText(con, "hello my jello ", Toast.LENGTH_LONG).show();
		} catch (Exception r) {
			Toast.makeText(con, "You were supposed to do something"
					+" now but I can't retrieve what it was.",
					Toast.LENGTH_SHORT).show();
			Log.e("ALARM_RECEIVER", r.toString());
		}
	}
}
Categories
Android Uncategorized

G2 on the way?

According to some rumors on IT news websites, some new Android phones will be released in 2009. cellphonesignal.com claims that a phone, G2, is in the making and will be released in January of 2009. Another website claims that it will be released in April. Best of all, G2 will not be locked down to T-Mobile. It will be great to have a phone not locked down to T-mobile but this begs the question : WIll this phone be able to access T-mobile’s 3G services? And if yes, will it also be able to access 3G service of providers from the rest of the world who don’t use 1700 Mhz for 3G? I guess we will soon find out. 

An Australian company had announced the release of an Android based phone called Kogan Agora. It looks something like Samsung Blackjack and has no touch screen (as far as I can tell). A chinese firm, Lenovo, has also announced an Android based phone which will have touch screen but no physical keyboard. It looks something like HTC Touch HD from the front. The phone is called QIGI.

Looks like 2009 has some great things in store for all the phone lovers out there. Happy New Year everyone !

Categories
Android Uncategorized

Tmobile G1, AT&T and 3G

Google has released unlocked versions of Tmobile G1 for developers. It costs about $500 and you have to register with Google as a merchant for Android apps ($25 registration fee). Most developers who were (and still are) enthusiastic about G1 and Android failed to realize that G1’s (and Tmobile’s ) 3G network functions on the 1700 band and all other prodivers in USA (including AT&T) operate their 3G at another band (I think it’s 1900 or 2100). So, if you get G1 and your service provider is not Tmobile, then you wont be able to use the 3G service of your provider (unless their 3G service operates on the 1700 band).

Maybe Google should put a huge disclaimer on their site stating this so developers (and other people) can make an informed decision about getting an unlocked G1.  Having said that, I am not trying to blame Google or TMobile. They haven’t tried to hide the fact that their 3G service works on a different band, and it *is* the consumer’s responsibility to make sure they know what they are getting.

The same problem is with AT&T’s iPhone. You can jailbreak it but you lose some of its functionality (like visual voicemail) because AT&T had to make custom applications to support iPhone’s interaction with it’s network. I hope this doesn’t become a trend where a phone is locked to a provider. It would be a huge step backwards.

Categories
Android Uncategorized

Displaying dialogs in Android 1.0

When I say dialogs, I mean the little alert window that pops up and lets you know about an error that occurred or warns you about something you can’t do. It locks up the whole screen and demands you pay attention to it. I use a dialog to display information about the application.

Android has a few type of alert dialogs. One is a dialog that will not go away unless you make it go away. The other is a dialog that goes away after soem time. We will take a look at both of them here. 

First, let’s look at dialogs that don’t go away unless you tell them to. Here is the code for them :

 

 

public class SomeActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstance)  {
        AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
        dlgAlert.setMessage(“This is an alert with no consequence”);
        dlgAlert.setTitle(“App Title”);
        dlgAlert.setPositiveButton(“OK”, null);
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
    }

The code above will display an alert with a title, a message and an OK button at the bottom. You don’t really have to set the title, the ok button or the message but it helps to do so. If you don’t use an “OK” (or whatever) button, the dialog will never go. The user will have to close the application in order to get out of it. There are other types of buttons that you can use (and you can use multiple buttons also). You can take a look at AlertDialogBuilder’s API for more information here

The second type of dialog is more of a notification alert that is displayed on the main screen. I have used it before in my previous post which spoke about how to set alarms in Android. This alert will be shown for some time and regardless of whether a user responds to it or not, it will disappear after some time. Below is the code that is used to call it (or display it) :

 

Toast.makeText(con, “This is a message from hell. Yes my friend, HELL”, Toast.LENGTH_SHORT).show();

 

The above code will display an alert for a short amount of time and then close it. This alert is very simple and short and doesn’t require much to be displayed. You can also use Toast.LENGTH_LONG to display the alert for a longer period of time. And, like always below are the screenshots of what both of them look like.

 

The dialog that requires user to click something
The dialog that requires user to click something

 

The disappearing alert
The disappearing alert
Categories
Android Uncategorized

Sending email from Android

Sending an email is a very basic functionality (for some applications anyway). Android makes it very easy to do this. All you have to do is create a new intent, setup the content of the email and send it. 

Intent in = new Intent(Intent.ACTION_SEND); 
in.putExtra(Intent.EXTRA_TEXT, “this is the body of the email”); 
in.putExtra(Intent.EXTRA_SUBJECT, “Subject”); 
in.setType(“message/rfc822”); 
startActivity(Intent.createChooser(in, “Title:”));

Categories
Android Uncategorized

Working with a database in Android

Android uses SQLite for its database needs. SQLite is a very fast and lightweight database. It is file based which makes it highly portable and an ideal candidate for use as an embedded database. For those who prefer to just go through the code and learn, the Notebook application example on Android’s website can be very useful. Let’s begin with the tutorial shall we.

First, you will need to make a class that will interact with the database. After that class has been written, you will instantiate it and use it to perform your data operations. This will keep your code encapsulated and easy to maintain. Android tries to encourage its programmers to use the MVC concept and makes it easy to implement it.

Assume your table structure is this :

create tblData (
_id int primary key autoincrement,
alert_text text,

alert_date varchar(20),
alert_time varhcar(20)
);

Setting up Connections and getting everything ready

Our database interaction class will be called DBLayer. It is a public class, so it will need to be in a file called DBLayer.java. Let’s say we have a table with 3 fields and we want to set and get data from it. This is how you set the class up :

/**
 * Database Wrapper
 *
 * DB Schema:
 * ------------------------------------
 * Create table tblData (
 *     _id int primary key autoincrement,
 *     alert_text text,
 *     alert_date varchar(20),
 *     alert_time varchar(20)
 * );
 */
public class DBLayer {

	/*******************************************************
	* These constants refer to the fields in the database.
	* _id is Android's naming convention for ID fields.
	* Our database has 3 fields, so we have 3 constants.
	********************************************************/

	public static final String KEY_NAME  = "name";
	public static final String KEY_VAL   = "value";
	public static final String KEY_ROWID = "_id";

	/*******************************************************
	* This is not needed for the database. It is
	* here to help us tag our logging messages
	*******************************************************/
	public static final String TAG = "AlertDB";

	private DatabaseHelper dbHelper ;
	private SQLiteDatabase db;

	private Context mCtx = null;

	/*******************************************************
	* Some other constants related to our database's
	* information. They should be self explanatory
	********************************************************/
	private static final String DATABASE_NAME = "gAlert_db";
	private static final String DATABASE_TABLE = "tblData";
	private static final int DATABASE_VERSION = 2;
	private static final String DATABASE_CREATE =
	"create table gAlert_alerts ( "
	+ "_id integer primary key autoincrement, "
	+ "alert_text text not null,"
	+ "alert_date varchar(20) not null,"
	+ "alert_time varchar(20) not null"
	+");";

	/********************************************************
	* Think of this as a driver for your database
	* interaction. You can just copy and paste this part in
	* all your database interaction classes.
	*********************************************************/
	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context ctx) {
			super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		}
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP IF TABLE EXISTS "+DATABASE_TABLE);
			onCreate(db);
		}
	}

	/** Constructor */
	public DBLayer(Context ctx) {
		mCtx = ctx;
	}
	/********************************************************
	* This opens a connection to the database but if
	* something goes wrong, it will throw an exception.
	********************************************************/
	public DBLayer open () throws SQLException {
		dbHelper = new DatabaseHelper(mCtx);
		db = dbHelper.getWritableDatabase();
		return this;
	}
	/** Closes a database connection */
	public void close() {
		dbHelper.close();
	}
}

I have read articles which state a different way using databases in Android. From what I can tell these tutorials were for versions prior to 1.0. In version 1.0, you create a class which extends SQLiteOpenHelper and you encase that class in another class which you will call to insert and retrieve data. The comments in the code above should be self-explanatory. If you have any questions I haven’t answered, please leave a comment and I will post a reply.

You don’t need to have a database already set up. If the database you try to open doesn’t exist, then Android will create it. It will run the onCreate() method when it creates the database. And, if the database version changes on the phone. It will run the onUpgrade() method.

Running your Queries

Now the class DBLayer can connect to the database. However, just connecting is of no use unless you can retrieve some data from your database. There are 4 methods you can use in Android and they all perform different functions. They are : query, insert, delete and update. query() is used to retrieve data. The others should be self-explanatory.

Here’s a method that will retrieve multiple rows from the database:

	public Cursor fetchAllAlerts() {
		try {
			return db.query(DATABASE_TABLE,
				new String[] {KEY_ALERT_TEXT, KEY_ALERT_DATE,
				KEY_ALERT_TIME, KEY_ROWID}, null, null,
				null, null, null);
		} catch (Exception e) {
			Log.e("yo", e.getMessage());
			return null;
		}
	}

You will rarely (if ever) find yourself writing any SQL for Android applications. The reason being Android’s framework does all the dirty work behind the scenes. All you have to do is set  your object up and provide the data retrieval, insertion methods with the neccesary information.

Here are some more methods. Everything should be self explanatory.

	public long createAlert(String text, String date, String time) {
	ContentValues vals = new ContentValues();
	vals.put(KEY_ALERT_TEXT, text);
	vals.put(KEY_ALERT_DATE, date);
	vals.put(KEY_ALERT_TIME, time);
	return db.insert(DATABASE_TABLE, null, vals);
}

public boolean deleteAlert(long rowId) {
	return db.delete(DATABASE_TABLE, KEY_ROWID+"="+rowId, null) > 0;
}

public Cursor fetchAllAlerts() {
	try {
		return db.query(DATABASE_TABLE, new String[] {
				KEY_ALERT_TEXT, KEY_ALERT_DATE,
				KEY_ALERT_TIME, KEY_ROWID}, 
					null, null, null, null, null);
	} catch (Exception e) {
		Log.e("yo", e.getMessage());
		return null;
	}
}

public Cursor fetchAlert(long rowId) throws SQLException {
	Cursor ret = db.query(DATABASE_TABLE, new String[] {
				KEY_ALERT_TEXT, KEY_ALERT_DATE,
				KEY_ALERT_TIME, KEY_ROWID},
				KEY_ROWID+"="+rowId, null, null,
				null, null);
	if (ret != null) {
		ret.moveToFirst();
	}
	return ret;
}

public boolean updateAlert(long rowId, String text, String date, String time) {
	ContentValues vals = new ContentValues();
	vals.put(KEY_ALERT_TEXT, text);
	vals.put(KEY_ALERT_DATE, date);
	vals.put(KEY_ALERT_TIME, time);
	return db.update(DATABASE_TABLE, vals,KEY_ROWID+"="+rowId, null) > 0;
}

You can get the code for the whole class here. In this article, there wasn’t much explanation because I didn’t think I needed to explain anymore after pasting the code. I am sure there are people reading this who feel otherwise. Please let me know what needs more explanation and I will elaborate on that topic.

Categories
Android Uncategorized

Debugging errors in Android

Android has a great framework to work in. However, it is in its infancy and debugging my code has been a very big problem for me. Whenever something goes wrong in the code, I always get “source not found” error. It doesn’t tell me I have a nullPointer exception , or string is incomplete.  No matter what’s wrong with the code, I always get “source not found” error. The reason that happens is Android doesn’t pack the source along with the application it sends to the emulator (maybe they should do that for a debugging run). After searching the net for a while, I came across this solution – wrap your code in a try and catch block and then log the exception to console. Here is an example :

public class SomeClass extends ListActivity {
	private AlertDB db ;
	private static final int ALERT_ADD = 100;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	//setContentView(R.layout.alert_list);
	try {
		db = new AlertDB(this);
		Cursor c = db.fetchAllAlerts();
	} catch (Exception e) {
		Log.e("ERROR", "ERROR IN CODE:"+e.toString());
	}
}

Doing that will display a neat little line in your logcat window (look at the screenshots at the bottom). And, instead of getting the annoying “source not found” error. You will know what the actual error is. In Android, you can log three types of events – information, warning and error. Information is just verbose text being written out to the log.  I don’t need to explain warning and errors.

For logging information you can use :

Log.i(TAG, message);

For logging warnings you can use :

Log.w(TAG, message);

I have already shown how to log errors in the code above.

Click to enlarge
Click to enlarge
Click to enlarge
Click to enlarge
Categories
Android Uncategorized

Programming for the beast named Android

Click for original size
Click for original size

I was messing around with Android’s development kit and I have to say, learning to develop an application for Android was much easier than trying to do it for Windows Mobile. I guess proper documentation helps – a lot. Google has put published tutorials on how to do some common tasks needed for making applications, and has  code reference documentation, etcetera which makes it easier to jump into it.

I am a very big fan of MVC and code and design separation in general. I was happy to find out that Android’s API lets you design the user interface in XML and then use that in your program. You can also do the design programmatically but who wants to do that (unless maybe you were adding / removing elements dynamically).

Google also provided an emulator to debug your software. It would have been a nightmare debugging my application without it. Beware of the “source not found” error. Whenever something goes wrong in your application, the debugger tries to reference the source of the place of error. And, the compiler doesn’t include source in the binary from what I understand. So, you get the debugger throws the error “Can’t find source”. There are workarounds for that problem posted on the internet, though.

When I started learning how to program for Windows Mobile (I have a Kaiser so I wanted to an FTP editor for it to edit HTML/PHP/whatever on the go). It took me quite some time to realize that you HAVE to buy Visual Studio if you want to program for it. It took me about a week to get started with Windows Mobile development but it took me a day for Android. And, the studio costs hundreds of dollars so that was out of the question for a hobby. Android, on the other hand, is free so I can use it with no cost at all. Don’t get me wrong. I am not putting Microsoft down. I am a programmer too and I know better than to say all software should be free. People need to make money and without an incentive there won’t be any good software. Visual Studio has great features which make programming very easy. I love their UI designer. I just want to have the choice to be able to program with their SDK without having to shell out 500+ dollars. Maybe if they let me use the SDK for free and asked to be paid for the visual studio, it would be a beter deal.

Anyway, after I got interested in the Android’s SDK, I decided to write some useful applications for it. I’m sure there will be enough users of Tmobile’s G1 phone who will want to use my application *fingers crossed*. Maybe I will make another post of what I plan to make that application do (hint: it will use geo-location service, run in the background and have a UI for settings and such).

Links:

Android’s home page :
http://www.android.com/

Resources for developers :
http://code.google.com/android/

Tutorials on various android related things :
http://developerlife.com/tutorials/?p=304