Android soup with SQLiteDatabase, ListActivity and Options Menu

Have some Android soup made with SQLiteDatabase, ListActivity and Options Menu as ingredients! In this latest encounter with Android I create a small database that holds a list of Train numbers and names. The contents of this list is displayed to the user. The user is also given a menu to “add”, “delete” and “deleteAll” the records.

To get started I create a SqlOpenHelper class which extends the SQLiteOpenHelper. This class has the methods to create the SQLiteDatabase.

publicvoid onCreate(SQLiteDatabase db) {

createDatabase(db);

}

publicvoid createDatabase(SQLiteDatabase db) {

//Create TRAIN_TABLE

String CREATE_TRAIN_TABLE = “CREATE TABLE IF NOT EXISTS ” +

TRAINS_TABLE + “(” + TRAIN_ID + ” INTEGER PRIMARY KEY,” +

TRAIN_NO + ” INTEGER , ” + TRAIN_NAME + ” TEXT” + “)”;

Log.d(“Creating: ” , CREATE_TRAIN_TABLE);

db.execSQL(CREATE_TRAIN_TABLE);

}

Besides there are methods to

1) To add a train record

// Add a train method

publicvoid addTrain(int trainNo,String trainName) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(TRAIN_NO, trainNo);

values.put(TRAIN_NAME, trainName);

// Insert a new row

db.insert(TRAINS_TABLE, null, values);

db.close(); // Closing database connection

}

2) To delete a train record

// Delete a single train

publicvoid deleteTrain(Train train) {

SQLiteDatabase db = this.getWritableDatabase();

db.delete(TRAINS_TABLE, TRAIN_ID + ” = ?”,

new String[] { String.valueOf(train.getID()) });

db.close();

}

and to display all the trains in the database. The entire list is returned as a List.

3) Display all trains

// Getting all trains in SQLiteDB

public List<Train> getAllTrains() {

//Create a List

List<Train> trainList = new ArrayList<Train>();

// Create the “Select query”

String selectQuery = “SELECT * FROM ” + TRAINS_TABLE;

//Open the DB in read mode

SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.rawQuery(selectQuery, null);

// loop through all rows and add trains to the List

if (cursor.moveToFirst()) {

do {

Train train = new Train();

train.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(TRAIN_ID))));

train.setTrainNo(cursor.getString(cursor.getColumnIndex(TRAIN_NO)));

train.setTrainName(cursor.getString(cursor.getColumnIndex(TRAIN_NAME)));

// Adding contact to list

trainList.add(train);

} while (cursor.moveToNext());

}

//Close DB

db.close();

// return the train list

return trainList;

}

To get started the DB has to be created with the following method in the MainActivity class

SqlOpenHelper helper = new SqlOpenHelper(this);

//Open SQLiteDB

db = this.openOrCreateDatabase(“train_no.db”, MODE_PRIVATE, null);

After creating the DB the MainActivity switches to the displayTrains activity which display the current list of of trains in the DB as follows.

 list

SqlOpenHelper helper = new SqlOpenHelper(this);

int count = helper.getTrainCount();

Log.d(“Count:”, “value =” + count);

results = populateResults();

listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results);

this.setListAdapter(listAdapter);

The list is displayed by creating displayTrains as a ListActivity using the simple_list_item_1

In order to provide a add,delete & deleteAll function I added an Options Menu. To do this create an Option Menu in XML under res/menu

<menuxmlns:android=http://schemas.android.com/apk/res/android&#8221;>

<item android:id=“@id/add”

android:icon=“@drawable/add”

android:title=“@string/add” />

<item android:id=“@id/delete”

android:icon=“@drawable/delete”

android:title=“@string/delete” />

<item android:id=“@id/deleteAll”

android:title=“@string/deleteAll”

android:icon=“@drawable/deleteall”/>

</menu>

This is then inflated in displayTrains activity in which I wanted the Options Menu to appear as follows

publicboolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.options_menu, menu);

returntrue;

}

Icons for the Options Menu have to added in the drawable folder.

options

For some reason icons do not show up in my ADT but when I debugged on my phone it shows.

When the Add Option is clicked it takes it to the addTrains activity which inputs the Train Number & Train Name. The user is then given the option to save.

add

This returns the activity to display Trains where the entire list is redisplayed.

The delete option was a little tricky. The selected record is deleted as follows

helper.deleteTrain(selectedItem);

where the selectedItem selects a row in which we have to determine the trainID and delete the record with that ID. This is done as below

publicvoid deleteTrain(Train train) {

SQLiteDatabase db = this.getWritableDatabase();

db.delete(TRAINS_TABLE, TRAIN_ID + ” = ?”,

new String[] { String.valueOf(train.getID()) });

db.close();

}

After deleting the record from the DB the list has to be refreshed. I repopulate the listAdapter and pass it to the ListActivity as bwlow. I am not sure if this is the most efficient methid.

r = populateResults();

listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,r);

this.setListAdapter(listAdapter);

listAdapter.notifyDataSetChanged();

Finally the deleteAll deletes all the records in the DB as shown below

publicvoid deleteAllTrains() {

SQLiteDatabase db = this.getWritableDatabase();

db.delete(TRAINS_TABLE, null, null);

db.close();

}

This was some fun. The entire code can be downloaded at DB.zip

Find me on Google+

Unity(full) android App: With bells and whistles

In this post I discuss a fairly complete Android App – Unity which is a simple unit converter. The android app has all the good stuff from Android including activities, intents, spinners, launch icons and a splash screen to boot as below. Download it from Google Play : Unity – Unit Converter . To know more about the app read on …

compasses

I have enhanced my earlier basic Unity app to start with a Splash Screen before moving onto an initial screen with buttons for various unit conversion like mass,length,volume etc

This is shown below

unity-1

When any of these buttons are clicked it goes to the appropriate conversion screen. This is done by starting the appropriate activity. An activity is invoked by the intent which starts the activity.

Hence the MainActivity.java has an intent and activity for each of the buttons mass,length,volume in the addListenerOnButton as follows

publicvoid addListenerOnButton() {

//Mass activity

massButton = (Button) findViewById(R.id.button1);

massButton.setTextAppearance(context,R.style.ButtonFontStyle);

massButton.setOnClickListener(new OnClickListener() {

publicvoid onClick(View arg0) {

Intent intent = new Intent(context, massActivity.class);

startActivity(intent);

}

});

//Length activity

lengthButton = (Button) findViewById(R.id.button2);

lengthButton.setTextAppearance(context,R.style.ButtonFontStyle);

lengthButton.setOnClickListener(new OnClickListener() {

publicvoid onClick(View arg0) {

Intent intent = new Intent(context, lengthActivity.class);

startActivity(intent);

}

});

When the “Mass button” is clicked it activates a new intent based on the massActivity.java class.

The massActivity.java file performs the following main functions

  1. Changes the layout to the one defined in mass.xml under res/layout.mass.xml
  2. Instantiates a massAdapter as an ArrayAdapter
  3. Passes the massAdapter to both the spinners in the View
  4. A convert method is invoked when the Convert button is clicked. This method does the actual calculation
  5. Finally a ‘Home’ button is used to go back to the MainActivity class

publicclass massActivity extends Activity {

String[] massUnits = {“gram”,“kilogram”,“ounce”,“pound”,“ton”};

//double massConversion[][] = new double[5][5];

doublemassConversion[][] = newdouble [][]{

{1.0,0.001,3.527e-2,2.205e-3,1.102e-6},

{1000.0,1.0,35.27,2.205,1.102e-3},

{28.35,28.38e-2,1,6.25e-2,3.125e-5},

{453.6,0.4536,16.0,1.0,.0005},

{9.072e-5,907.2,3.2e4,2000.0,1}

};

protectedvoid onCreate(Bundle savedInstanceState) {

ArrayAdapter<String> massAdapter = new ArrayAdapter<String> (this,

android.R.layout.simple_spinner_item,massUnits);

sp1 = (Spinner) findViewById(R.id.spinner1);

sp1.setAdapter(massAdapter);

sp1.setOnItemSelectedListener(new OnItemSelectedListener() {

publicvoid onItemSelected(AdapterView<?> argo0, View arg1,

int arg2, long arg3) {

intitem = sp1.getSelectedItemPosition();

}

publicvoid onNothingSelected(AdapterView<?> arg0) {

}

});

sp2 = (Spinner) findViewById(R.id.spinner2);

sp2.setAdapter(massAdapter);

sp2.setOnItemSelectedListener(new OnItemSelectedListener() {

publicvoid onItemSelected(AdapterView<?> argo0, View arg1,

int arg2, long arg3) {

intitem = sp2.getSelectedItemPosition();

/

}

});

}

publicvoid convert(View view) {

double inputValue = Double.parseDouble(text1.getText().toString());

int item1 = sp1.getSelectedItemPosition();

int item2 = sp2.getSelectedItemPosition();

double value = massConversion[item1][item2];

double convertedValue = inputValue * value;

txtConvertedValue.setText(String.valueOf(convertedValue));;

}

The Home button takes back to the Main screen

publicvoid home(View view) {

final Context context = this;

Intent intent = new Intent(context,

MainActivity.class);

startActivity(intent);

}

The mass.xml screen has 1 Textfield for input, a TextView for output, 2 spinners for handling the fromUnit & toUnit and a Convert & a Home button. The mass.xml is shown below

<TableLayout xmlns:android=http://schemas.android.com/apk/res/android&#8221;

android:layout_width=“fill_parent”

android:layout_height=“fill_parent” >

<TableRow

android:id=“@+id/tableRow1”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content” >

<TextView

android:id=“@+id/textView1”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:layout_column=“0”

android:layout_span=“4”

android:text=“@string/massConversion”

android:textAppearance=“?android:attr/textAppearanceMedium” />

</TableRow>

<TableRow

<TextView

android:id=“@+id/textView2”

/>

<EditText

android:id=“@+id/editText1”

android:inputType=“numberDecimal” />

</TableRow>

<TableRow

<TextView

android:id=“@+id/textView3”

android:text=“@string/convertedValue” >

<TextView

android:id=“@+id/txtConvertedValue”>

</TableRow>

<TableRow

android:id=“@+id/tableRow5”

<Spinner

android:id=“@+id/spinner1”>

</TableRow>

<TableRow

android:id=“@+id/tableRow6”

<Spinner

android:id=“@+id/spinner2”>

</TableRow>

<TableRow

android:id=“@+id/tableRow11>

<Button

android:onClick=“convert”

android:text=“@string/Convert” />

<Button

android:onClick=“home”

android:text=“@string/home” />

</TableRow>

</TableLayout>

unity-5

Note: Ensure that you add this new activity massActivity to AndroidManifest.xml

As shown

<application

<activity

android:name=”com.example.test.massActivity”

android:label=”@string/app_name” >

</activity>

</application>

</manifest>

Similar code can be replicated for the other buttons and other conversion units.

Once this is done your application is ready. It is now time to create a suitable “icon” for your android app. I found GIMP utility extremely useful in creating icons. GIMP cam be downloaded from http://www.gimp.org. This requires some learning ramp-up. So I took the easy route and downloaded ready made icon from OpenClipArt.org which has a huge collection of icons.

The specified dimensions for the icons based on the resolution of the android device is given in http://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html

and should be

  • Low density screens (ldpi): 36x36px, 120dpi
  • Medium density screens (mdpi): 48x48px, 160dpi
  • High density screens (hdpi): 72x72px, 240dpi
  • Extra high density screens (xdpi): 96x96px, 320dpi

Copy all the icons to the directory below and rename the png files to ic_launcher.png

  • Low density icon : res/drawable-ldpi
  • Medium density icon : res/drawable-mdpi
  • High density icon : res/drawable-hdpi
  • Extra high density icon : res/drawable-xdpi

WhenyoubuildandruntheapponyouremulatoryoushouldseeyouriconinsteadofthestandardAndroidicon.

It is worth mentioning a problem that I faced initially and had me stumped. I would make some changes and get the error “R cannot be resolved to a variable”.

AftertryingtounsuccessfullycleanandrebuildtheprojectseveraltimesItriedtodiginmore.MysearchwithGoogleprovedfutilewithsomepostscomplainingthatEclipsewasclobberingfiles.TheissueusuallyhappenswhentheR.javafilecannotbegeneratedwhenyoubuildtheproject.Thisusuallyhappenswhenthereissomeissueinyour /resdirectory.Checkifthereareanyredmarksinyourlayout,strings.xmlorAndroidManifest.xmletcfile, fixthem, rebuild and theproblemshouldgoaway.

Finally I added an initial splash screen. For this I took the code from O’Reilly’s cook book “Splash screens in Android”. A splash *.jpg or *.png has to be added to the res/drawable folders

Remember to change the AndroidManifest.xml to have the app open up with the splash screen and then switch the MainActivity.java.

A snippet is shown below

<activity

android:name=“com.tvganesh.unity.SplashScreen”

android:noHistory=“true”

android:label=“@string/app_name” >

<intent-filter>

<action android:name=“android.intent.action.MAIN” />

<category android:name=“android.intent.category.LAUNCHER” />

</intent-filter>

</activity>

<activity

android:name=“com.tvganesh.unity.MainActivity”

android:label=“@string/app_name” >

</activity>

<activity

android:name=“com.tvganesh.unity.massActivity”

android:label=“@string/app_name” >

</activity>

….

With this app is also set to rock ‘n roll. I also managed to submit the app to Google Play. To publish in Google Play you need to do the following

  1. Create a signed app package. For this right click the package, select Android Tools->Export Signed Application Package and follow the prompts. Upload the *.apk file in Google Play
  2. You will also need 2 screenshots of the app & a 512×512 icon.

And you should be through.

The Unity project can be cloned from Git Hub at Unity project or

The entire Unity – Unit converter app can be downloaded at Unity-Unit Converter

Find me on Google+

Unity – My first android app

Unity – A simple unit converter is my first android app. The app in itself is no great piece of software wizardry but I managed to play around some of the basic android concepts. Currently in its current version there are just 4 main types of units – length, mass,temperature and volume each with just 2 unit types. I am planning to implement a full-fledged android version with all types of units and unit conversions shortly. Watch this space for more.

For this simple version I have a textfield to take user input of the value to be converted. I also have 2 spinners with the list of units. The first spinner (fromUnit) has its content loaded in runtime from an ArrayAdapter. The contents of the 2nd spinner is based on the selection of the 1st spinner. So if the 1st spinner chooses a length unit the 2nd spinner will also be loaded with the length units and so on. There is also a Calculate button with a “convert” method for onClick to convert from the fromUnit to the toUnit.

The resource/activity_main.xml

<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=http://schemas.android.com/tools&#8221;
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“.MainActivity” >
<Button
android:id=“@+id/button1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_below=“@+id/spinner2”android:layout_centerHorizontal=“true”
android:layout_marginTop=“62dp”
android:onClick=“convert”
android:text=“Calculate” />
<EditText
android:id=“@+id/editText1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true”
android:layout_marginTop=“24dp”
android:ems=“10”
android:inputType=“numberDecimal” >

<requestFocus />
</EditText>
<Spinner
android:id=“@+id/spinner1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_below=“@+id/editText1”
android:layout_marginTop=“24dp” />
<Spinner
android:id=“@+id/spinner2”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_below=“@+id/spinner1”
android:layout_marginTop=“44dp” />
</RelativeLayout>
The fromUnit is based on the units array below
String[] units = {“kilogram”,“mile”,
“kilometer”,“pound”,“gallon”,“liter”,“centigrade”,“fahrenheit”,
};
In the onCreate() method I create an ArrayAdapter and set the spinner with this adapter as follows
final ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,units);
sp = (Spinner) findViewById(R.id.spinner1);
sp.setAdapter(adapter);
I also set the 2nd spinner (toUnit) based on the selected unit in spinner 1. Hence I conditionally set the 2nd spinner as follows
sp1 = (Spinner) findViewById(R.id.spinner2);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> argo0, View arg1,
int arg2, long arg3) {
int item = sp.getSelectedItemPosition();
fromUnit = units[item];
if( (fromUnit.equals(“kilometer”)) || (fromUnit.equals(“mile”))) {
sp1.setAdapter(lengthAdapter);
unitType=1;
}
else if ((fromUnit.equals(“kilogram”)) || (fromUnit.equals(“pound”))){
sp1.setAdapter(massAdapter);
unitType=2;
}
else if ((fromUnit.equals(“centigrade”)) || (fromUnit.equals(“fahrenheit”))) {
sp1.setAdapter(tempAdapter);
unitType=3;
}
else if((fromUnit.equals(“liter”)) ||(fromUnit.equals(“gallon”))){
sp1.setAdapter(volumeAdapter);
unitType=4;
}
else {
sp1.setAdapter(adapter);
unitType =5;
}
Toast.makeText(getBaseContext(),“You have selected: “ +
fromUnit, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> argo0, View arg1,
int arg2, long arg3) {
int item = sp1.getSelectedItemPosition();
if(unitType == 1) {
toUnit= lengthUnits[item];
}
else if(unitType == 2){
toUnit = massUnits[item];
}
else if(unitType == 3){
toUnit = tempUnits[item];
}
else if (unitType == 4) {
toUnit = volumeUnits[item];
}
else {
toUnit = units[item];
}
Toast.makeText(getBaseContext(),“SP2:You have
selected: “ +
toUnit, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Finally based on the fromUnit and the toUnit the appropriate method is called in the onClick method of the Calculate button.
if((fromUnit.equals(“kilometer”)) && (toUnit.equals(“mile”))){
text.setText(String.valueOf(convertkilometer2mile(inputValue)));
}

else if((fromUnit.equals(“mile”)) && (toUnit.equals(“kilometer”))) {
text.setText(String.valueOf(convertmile2kilometer(inputValue)));
}
and so on…
While this is an elementary app I intend to develop a more thorough version shortly with some of the good features of android.
The complete code can be downloaded from the link Unity.zip

Also see
1. Train Spotting android app – Nuts & bolts
2. The making of Dino Pong android game

Find me on Google+

Toying with Android apps

As the title suggests this is my first encounter with Android. This post is not meant for those who are intending to develop serious android apps. This article shows how to get started with Android App development. Recently I acquired my first Samsung smartphone and I can’t seem to get enough of it. I am now fully hooked on to Android and hope to play around with it in the days to come. Fortunately the initial encounter has been fairly pleasant.

To get started download the SDK from http://developer.android.com/sdk/index.html#ExistingIDE assuming you already have Eclipse like I did. Unpack and install the SDK at a suitable location for e.g. /android. You will also have to install the Eclipse plugin for Android from http://developer.android.com/sdk/installing/installing-adt.html. Alternatively you can directly download the comple ADT bundle which includes the SDK,Eclipse along with plugin etc.

Once you have Android installed on in the plugin start Eclipse. Select File->New->Project-> Android Application Project and click next. In the Application Name enter My Test and let eclipse fill the names for Project name and Package name. Click next. Allow default values in New Android Application and Configure Launcher icon screens. In the Create Activity choose Blank Activity and choose default values for New Blank Activity and finally choose Finish.

This will create the Android Project. The files and folders that are created
/src – Source folder. This contains the java source files
/res – Resource folder. This is the resource which specifies the Layout, UI and also has the Android Manifest File indicating permissions.

For the 1st Android app under res/layout open activity_main.xml. There are 2 tabs in the eclipse Window namely Graphical Layout and activity_main.xml. The Palette can be used to drag and drop widgets like textfield, buttons, radio buttons etc. For my example I placed a text field with a text “My first Android Hello World App”. You can modify the text after dragging from the palette by right clicking and entering the text string. Similarly I also dragged and dropped a button and named it “Submit”. Right click the button choose Other properties->Inherited from View and select onClick and enter “print” for New OnClickValue. Now the function print will be invoked when the Submit button is clicked.

The activity_main.xml will contain the following contents
<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=http://schemas.android.com/tools&#8221;
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“.MainActivity” >
<Button
android:id=“@+id/button1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/textView1”
android:layout_below=“@+id/textView1”
android:layout_marginTop=“32dp”
android:onClick=“print”
android:text=“Submit” />
<TextView
android:id=“@+id/textView1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true”
android:layout_marginTop=“22dp”
android:text=“My First Android Hello World App”
android:textAppearance=“?android:attr/textAppearanceMedium” />
</RelativeLayout>

Now under src open MainActivity.java and add the following code
public void print(View view) {
Toast.makeText(this, “Hello World, Hello Android!”,
Toast.LENGTH_LONG).show();
return;
}

Before you build your application click Windows->Android SDK Manager. Select Tools, Android 4.2 and the necessary Extras. This will update your SDK with the latest version of teh SDK and associated libraries. Now click Windows-> Android Virtual Device Manager. This is Android’s emulator and needs to be setup. The simplest way is to select the Device Definitions tab and choose one of the devices mentioned there as your AVD. Alternatively you can select New and create a custom AVD.

Now build the project by selecting Project->Build All. Once the build is successful run the project. This will bring the AVD you selected above.

This will take a few minutes. Finally the screen will appear with a lock. Drag the lock to unlock it. To see a list of apps click the rectange wih six squares inside it. You show now see this in the AVD.

Finally double click your My Test app. When you click the Submit button it show print “Hello world, Hello Android as show below.

The SDK also comes with several sample Android projects to play around with. To build a sample project click New->Project-Android Sample Project and choose any one among them. Play around with other AVDs.

I hope to do some more serious stuff with Android in the days to come. Watch this space

Find me on Google+