Search This Blog

Friday 7 December 2012

Help Me

I could use your help in a number of ways.  

Firstly my MathsTest app is now pretty much complete (Find it by searching 'Sundev Pabla' on Google Play), I know it could be more polished and there are a number of improvements that could be made - remember its a first app and the idea was to learn Android development.  I want to start on a new project now- something new that will help me learn new Android skills that I can share with you via this Blog.  So please let me have your ideas for Apps that you think would be useful or would allow me to learn new Android skills.

The other way in which I could use your help is suggestions on what the best laptop for me to buy is. My expertise lies in writing software, at work I don't need to worry about hardware, the company buys it and the IT department maintain it.  At home I am finding that my 6 year old DELL Inspiron 6400 is getting slow and struggles when running Eclipse and the Android Emulator.  So please advise me on what the best bit of hardware for me is.  My requirements and thoughts on what I need are as follows:
  1. Must be a laptop - so that I'm not tied do the desk and can work on the move
  2. As a desktop replacement I think it needs at least a 15'' screen
  3. I want to be able to write Android Apps and Java Applications using Eclipse and Windows Applications using Visual Studio.
  4. I want to be able to run a version control tool like GIT (This reminds me, I must write a post at some stage on version control tools like GIT and Subversion)
  5. In my view the hard drive does not need to be huge because I have a 2 Tb external hard drive and can also use Cloud storage
  6. I'm thinking of branching out into Windows Phone and Windows 8 apps as well as Android.  I was therefore considering getting a Touch Screen Laptop (If any of you have experience of using Window 8 or touch screen laptops then let me have your thoughts on whether this is a passing fad or the future of computing).
  7. I'm seriously considering the DELL Inspiron 15z, (The i7, 8Gb RAM variant).  What do people think - does anyone own one?
That all for today - Until next time Good Buy.

Tuesday 16 October 2012

Presenting data from a database to a user

We have spent the last few posts looking at the class which encapsulates all the database related activity.  In the case of my Maths Test App this class is the MathsTestDbAdapter class (By the way my Maths Test App can be downloaded by searching Google Play for 'Sundev Pabla').

Today we will look at how you would use this class in the main part of your app.  You would use this class to get data from the database and put data into the database.  In my Maths Test App I use a database to store top scores.  In order to present top scores to the user I need to read top score info from the database and present it to the user.

In the Maths Test App I have a separate activity which I use for displaying scores to the user.  In the OnCreate( ) function of this activity I instantiate an instance of the MathsTestDbAdapter class and then call the open function on the instance.


        mDbHelper = new MathsTestDbAdapter(this);
        mDbHelper.open();

I can now use the mDbHelper object to call the get data functions in the MathsTestDbAdapter class.  I do this in the fillData function of  my ViewScoreActivity class.  The code for the fill data function is shown below:


    private void fillData()
    {

    Cursor topScoreCursor = mDbHelper.fetchScoresBasedOnSpecifiedGameLevelAndType(this.getResources().getStringArray(R.array.gameLevelArray)[gameLevelSpinner2.getSelectedItemPosition()],this.getResources().getStringArray(R.array.gameTypeArray)[gameTypeSpinner2.getSelectedItemPosition()]);
   
    startManagingCursor(topScoreCursor);
       
    tvInitial1 = (TextView) findViewById(R.id.initials1);
    tvScore1 = (TextView) findViewById(R.id.score1);
    tvInitial2 = (TextView) findViewById(R.id.initials2);
    tvScore2 = (TextView) findViewById(R.id.score2);
    tvInitial3 = (TextView) findViewById(R.id.initials3);
    tvScore3 = (TextView) findViewById(R.id.score3);
    tvInitial4 = (TextView) findViewById(R.id.initials4);
    tvScore4 = (TextView) findViewById(R.id.score4);
    tvInitial5 = (TextView) findViewById(R.id.initials5);
    tvScore5 = (TextView) findViewById(R.id.score5);
   
    // Will use switch case without breaks to populate table
    topScoreCursor.moveToFirst();
    switch (topScoreCursor.getCount())
    {
    case 5:
    tvInitial5.setText(""+topScoreCursor.getString(1));
    tvScore5.setText(""+topScoreCursor.getDouble(2));
    topScoreCursor.moveToNext();
    case 4:
    tvInitial4.setText(""+topScoreCursor.getString(1));
    tvScore4.setText(""+topScoreCursor.getDouble(2));
    topScoreCursor.moveToNext();
    case 3:
    tvInitial3.setText(""+topScoreCursor.getString(1));
    tvScore3.setText(""+topScoreCursor.getDouble(2));
    topScoreCursor.moveToNext();
    case 2:
    tvInitial2.setText(""+topScoreCursor.getString(1));
    tvScore2.setText(""+topScoreCursor.getDouble(2));
    topScoreCursor.moveToNext();
    case 1:
    tvInitial1.setText(""+topScoreCursor.getString(1));
    tvScore1.setText(""+topScoreCursor.getDouble(2));
    topScoreCursor.moveToNext();
    break;
    }
    }

The first thing I do in the fillData( ) function is call the fetchScoresBasedOnSpecifiedGameLevelAndType( ) function.  This returns a Cursor object which contains the data extracted from the database.

I then call startManagingCursor( ) function and pass in the cursor object.  This means that Android will look after the Cursor life cycle for me and I don't need to worry about things like closing the cursor when the activity is destroyed.  The moveToFirst( ) function on the Cursor object is used to move to the first data record returned by performing the query on the database.  In the switch statement I then use the Cursor to populate TextViews with data from the database.  For each record the first column or array element is a unique id, the second column is the players initials and the third column is the score.  To move to the next record you call moveToNext( ) on the cursor object.

Hopefully you can follow the code in the fillData( ) function, this is easy for me to say because I wrote the code and it may not be as self explanatory as I thing - so if you have got any questions then please get in touch.  I will leave it here for today, all the best until next time.

Tuesday 2 October 2012

Reading and Deleting data from an Android SQL database

To date we have looked at setting up the SQL database and creating the schema and also how you go about adding data to the database.  Today we will look at reading data from the database.

Reading data from the database

In my Maths Test App (Download this by searching Google Play for 'Sundev Pabla'), I provide two functions in the MathsTestDbAdapter class which allow data to be read from the database.  The functions return a Cursor object which contains the data returned by performing an SQL query on the database.  The code for the two functions is shown below.  The first function returns all the top scores in the database, whereas the second function uses arguments passed in to the function to filter the data and return a subset of the top scores.

    public Cursor fetchAllScores()
    {
    // This function returns data for all scores in the database in ascending order
    return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID,KEY_USER_INITIALS,KEY_SCORE}, null, null, null, KEY_SCORE + " ASC", null);
    }


    public Cursor fetchScoresBasedOnSpecifiedGameLevelAndType(String level, String type)
    {
      return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID,KEY_USER_INITIALS,KEY_SCORE}, KEY_LEVEL + " = " + "'" + level + "'" + " and " + KEY_GAME_TYPE + " = " + "'" + type + "'" , null, null,null,KEY_SCORE + " ASC", null);
    }

We will look at the Cursor object in a subsequent post, possibly when we look at presenting data read from a database to the user (This will probably be the next post).  Today we will focus on the mDB.query function used to read data from the database in the above two functions.

The first argument to the mDb.query function tells the function which table you want to query, the second parameter is a list of columns you would like returned, the third parameter is a SQL WHERE clause (without the WHERE) specifying which data records you would like to get from the database - passing in null returns all the records.  The next three arguments I don't use and simply pass in null.  I will leave it as an exercise for yourselves to find out how setting these parameters would affect the data returned by the database.  The seventh argument allows you to specify how you would like the data ordered.  I am ordering the data in Ascending order of Score -  so the first record will be the lowest score and the last will be the highest.  The last argument which I do not use, would allow you to specify a limit on the amount of data returned.

Deleting data from the database

Deleting data from the database is relatively simple.  In my Maths Test App I provide a function for deleting data from the database.  This is needed because I only store the top 5 scores, so when a score falls out of the top 5 it is deleted.  The function takes a rowId for the row of data to be deleted.  So in the main part of my application code I would have to first read data from the database, determine which row I want to delete and then call the delete function below using the rowID as an argument to the function call.  In the delete function below, the first argument is the table from which I want to delete data. The second argument is an SQL WHERE clause without the WHERE, it is used to specify the data I wish to delete.  The third argument I do not use - again I will leave it as an exercise for you to find out what it does and how it might be used.


    public boolean deleteScore(long rowId)
    {
    return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
    
I think thats probably enough for today - so until next time good bye.

Friday 14 September 2012

General Comment

This is a general comment for any body who has stumbled on this Blog. This Blog is for people who wish to write their own Android Apps - the tools for doing this are free assuming you already own a PC or laptop.

Start with the first post in this Blog (A Welcome from yours truly) and work through the posts which effectively form a tutorial. Also download my Android App by searching Google Play for 'Sundev Pabla'. Having the App on your phone will be useful as you work through the posts in the blog. If you have any questions then please get in touch by using the comment feature of the blog.

Good luck

Adding data to an SQL database


In the last post we looked at setting up the schema for an SQL database and creating the database.  Today we will look at how data would be added to the database.

As usual we will be using my Maths Test App as the basis of examples, so if you have not downloaded it, do this now (This can be done by searching Google Play for 'Sundev Pabla').

Data is added to the SQL database by creating an instance of the ContentValues class and populating the class with the data you want to put in the database (the ContentValues class provides the 'put' method for this purpose).  Finally the insert method on the database is called and the name of the Database table and the instance of the ContentValues class are passed in as arguments of the insert function.

Below is the code I use to add a top score to the SQL database in my maths test app.  This addTopScore function is a method of the MathsTestDbAdapter Class we discussed in the previous post.  You should be able to see that I create an instance of the ContentValues class which is provided by the Android API (So you will need the following import statement at the top of file in which this method is implemented):

import android.content.ContentValues;

I then 'put' the data I want to store in the database into the object I instantiated from the ContentValues class.  Finally I call the insert method on the database object and pass in the name of the table where I want the data stored along with the data I want stored.  The insert function returns a long which is a unique identifier for the row just stored.

 public long addTopScore(String initials,Double score)
    {
    // This function adds a high score to the database
    // The initials and score of the high scorer are passed in, info
    // about the game level and type are obtained from the preset user
    // preferences
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_USER_INITIALS, initials);
    initialValues.put(KEY_SCORE, score);
    initialValues.put(KEY_LEVEL, cUserPreferences.gameLevel);
    initialValues.put(KEY_GAME_TYPE, cUserPreferences.gameType);
   
    return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

I  think that is enough for today, as usual if you have any questions please get in touch via the blog.

Friday 7 September 2012

Adding an SQL lite Database to Android Apps

Adding an SQL lite database to your applications is surprisingly easy.  I was able to reuse code from the standard notepad tutorial for Android developers.  The notepad tutorial can be found at the following url:

http://developer.android.com/training/notepad/index.html

In this tutorial all the database related tasks are encapsulated in a class called NotesDbAdapter, this class was fairly generic and it was easy to modify it to suit my own purposes.  I named my own class MathsTestDbAdapter.java (To make it easier to follow this blog, download my Android App - Maths Test, locate it by searching Google Play for 'Sundev Pabla').

The MathsTestDbAdapter class encapsulates all the database related activity such as defining the database schema (Schema refers to the definition of tables in the database and the columns making up the tables), creating the database and handling the database activities known as CRUD (Create, Read, Update and Delete).

We will look at each of the CRUD activities in subsequent posts.  Today we will have a quick look at defining the database schema and creating the database.  The database is created by executing an SQL command.  I store the SQL command in a String called DATABASE_CREATE.  The code for setting up my SQL command for creating the database is shown below:

// String variables to describe the schema of the database
private static final String DATABASE_NAME = "Maths_Test_Db";
private static final String DATABASE_TABLE = "Performace_Stats";
private static final int DATABASE_VERSION = 1;

private static final String TAG = "MathsTestDbAdapter";
public static final String KEY_ROWID = "_id";
public static final String KEY_USER_INITIALS = "initials";
public static final String KEY_SCORE = "score";
public static final String KEY_LEVEL = "level";
public static final String KEY_GAME_TYPE = "type";

// Store an SQL command for creating the database in a string variable called
// DATABASE_CREATE
    private static final String DATABASE_CREATE ="create table " + DATABASE_TABLE + " ("
    + KEY_ROWID + " integer primary key autoincrement, "
    + KEY_USER_INITIALS + " text not null, "
    + KEY_SCORE + " real not null, "
    + KEY_LEVEL + " text not null, "
    + KEY_GAME_TYPE + " text not null);";

From the code you should be able to determine the schema of my Database.  My Database has 1 table called Performance_Stats.  The table contains 5 columns.  The columns are a unique row id column, a column to hold the initials of a high scorer, a column for the high score, a column to store the game level which the high score relates to and finally a column to store the game type being played when the high score was obtained.

I think this is enough for today.  If I was you I would now download the NotePad tutorial from the link above and have a look at the schema for the database in the NotePad tutorial.  You could also have a look at the functions for performing the CRUD operations - this will make it easier to follow subsequent posts.  If you do download the NotePad tutorial then remember the source file you want to be looking at is called NotesDbAdapter.java.

All the best until next time, enjoy your android journey.



Friday 31 August 2012

Coming Soon...........

Its been a long time, but hopefully you are getting used to the format.  Yes there will be long periods without posts, however during these periods I am learning, doing Android development going on my Android journey so that I can share the details with you.

Todays post will be fairly short, I will just give you a taster for what will be coming in the following weeks.  I have added a new feature to my Maths Test App.  Go to Google Play and search for 'Sundev Pabla' and download the latest version of the app, then spend some time playing with it.

You should notice that the App now logs high scores.  This is because I have added an SQL lite database to the app, the display of high scores is also done in a new activity.  In forthcoming posts I will be telling you how to persist data in your own apps by adding an SQL lite database, I will tell you how to query, update, add and delete from the database - you will also learn how to launch new activities using intents.

We are coming to an exciting point in our Android journey, so be sure to join me.  For now go and get the latest version of the Maths Test App so that you can see what I am talking about in subsequent posts.  Also tell you friends and family to download the app, even if they are not interested in learning Android, the App provides a good work out for the brain and can help improve Mathematical attainment.

Saturday 21 July 2012

Custom Dialogs

Today we will look at creating custom dialogs.  When creating my own custom dialog for my Maths Test App,  I found the following website very useful (Although I did find an issue with the code which I had to correct for, more about that later):


A custom dialog is effectively a user interface, remember that user interfaces in android are called layouts and are defined in xml.  We have covered creating user interfaces and handling user inputs in previous posts, so I will not repeat myself here.  However step 1 in creating your custom dialog is creating a layout in xml.

Step 1 in creating custom dialog is to define a layout

The following layout is the one used in the example on the above website.  The layout contains an ImageView and a TextView.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />
</LinearLayout>
In the example on the website the following code is used to set the text for the TextView and the image for the ImageView.


Step 2 is to setup the layout in code
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");

TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
Everything covered so far should be familiar from previous posts.  The next bit is the key bit for displaying a custom dialog.  It is step 3 and is inflating the xml layout.

Step 3 is inflating the xml layout
AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
                               (ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
The line highlighted in yellow is the line I had to correct.  I had to replace


LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

with


LayoutInflater inflater = (LayoutInflater) myActivity.getSystemService(LAYOUT_INFLATER_SERVICE);


I will leave you to mull over the details of this post and see if you can create your own custom dialogs.  If you have any issues then please get in touch.



Friday 20 July 2012

Creating alerts

In this post we will learn how to create alerts.  You can see an example of an Alert Dialog in my Maths Test App (If you have not already downloaded it, then locate the Maths Test App by searching the Android Market / Google Play for "Sundev Pabla").

In the Maths Test App I use an alert to inform the user if they enter a game duration of less than 10s - originally all I wanted to do was handle the situation where the  user enters a null duration but then I decided to force the user to play for a minimum of 10s.  In order to set the Game Duration press the menu button before starting the game and select 'Set Game Preferences'.  The following code extract is taken from my Maths Test App:


            if (cUserPreferences.gameDuration < 10)
            {
            AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
            builder.setTitle("Warning")
            .setMessage("You entered a game duration of less than 10s. Your game duration has been defaulted to the minimum value of 10 seconds.")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {
                  cUserPreferences.gameDuration = 10;
                 }
              });
          AlertDialog alert =builder.create();
          alert.show();
         
            }

In the above extract I first check if the user has entered a game duration of less than 10 (If the user entered a null duration then I have already set the game duration to zero in order to force entry into the if block).  In the if block I create an instance of the AlertDialog.Builder class and use it to set the title of my alert dialog to "Warning", I then also use it to set the message I want displayed to the user.  The builder  is also used to create an ok button with a button click listener.  When the user clicks the "OK" button I set the game duration to 10s.  Finally I use the builder to create my alert dialog and then call show on the alert dialog.

I think this is enough for today, I will leave you to have a play with Alerts and next time we will look at displaying custom dialogs to the user (like  the one I use to get user preferences in the Maths Test App).

All the best until next time.

Saturday 14 July 2012

Disabling menu options when they are not applicable

In the last post we learned how to present the user with menu options when they press the menu button on their phone.  Today we will look at how to disable menu options when they are not applicable.  For example in my Maths Test App, I do not want the user to be able to change Game Preferences in the middle of a game, so I disable the Game Preferences option while a game is in progress (download the Maths Test App from the Android Market / Google Play by searching for Sundev Pabla).

In order to enable and disable menu options at runtime you must override the onPrepareOptionsMenu.  The following extract shows the overridden onPrepareOptionsMenu from my Maths Test App:


    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    super.onPrepareOptionsMenu(menu);
    // Don't display menu in the middle of a game
    if (!gameOver)
    {
    menu.getItem(0).setEnabled(false);
    }
    else
    {
    menu.getItem(0).setEnabled(true);
   
    }
    return true;    
    }
Essentially what this code is doing is getting the first menu option in my menu collection and either enabling or disabling the menu option depending on the state of the game (In the case of my Maths Test App, I only have one Menu Option so I know it will be the first one in the collection - 0 is used because the collection of menu items is zero based).

Its been a fairly small lesson today, but I believe in doing things in small bite size chunks.  Join me next time to learn how to present the user with custom dialogs and alerts (For example take a look at the dialog that is displayed when the user selects the 'Set Game Preferences' menu option on my Maths Test App).

Good bye for now.

Sunday 8 July 2012

Displaying menu options when the user presses the menu button on their phone

Today we will look at how to add menus to your Android App.  In the latest version of my Maths Test App (If you haven't already downloaded it, then download it now by searching for 'Sundev Pabla' on the Android Market) the user is presented with a "Set Game Preferences" menu option when they press the menu button on their phone.

Creating a menu using xml

Like user interfaces (layouts), menus are also defined in xml files.  The following xml defines the one menu option for my Maths Test App:


<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_setPreferences"
    android:icon="@android:drawable/ic_menu_preferences"
    android:title="Set Game Preferences"></item>  
</menu>

In the xml file I am giving the menu option an id, so that I can refer to it in code, I'm setting an icon for the menu option and I am setting the title displayed to the user for the menu option.

Loading the Menu by overriding the onCreateOptionsMenu function

To load your menu, you must override the onCreateOptionsMenu function in your code.  The following code extract is the onCreateOptionsMenu for my Maths Test App:



    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    super.onCreateOptionsMenu(menu);
    MenuInflater mi = getMenuInflater();
    mi.inflate(R.menu.main_menu, menu);
    return true;
    }

The MenuInflater is used to load the menu.  In my case the xml file is called main_menu.xml and is located in res/menu folder in the project and can be accessed from the R class as shown in the extract above.

Handling the selection of a menu option by overriding onMenuItemSelected function

In order to handle a user clicking on a menu option you must override the onMenuItemSelected function. This function is called when the user clicks on a menu option, an object of type MenuItem is passed into the function and can be interrogated to determine which menu option the user clicked on.  The following code extract is the onMenuItemSelected function for my Maths Test App:


    // Handle selection of menu item
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item)
    {
    switch(item.getItemId())
    {
    case R.id.menu_setPreferences:
    cUserPreferences.handlePreferenceSettings(this);

    }
    return super.onMenuItemSelected(featureId, item);
    }
In this function I check the id of the menu item/option clicked by the user and then use a case statement to handle the option clicked by the user (I only have the one menu option, so I didn't need to check the id or use a case statement, but this way I have future proofed my app in case I add in more menu options in the future.).  When the user clicks the menu option I call a function called handlePreferenceSettings - in this function I display a dialog to the user in which they can set their game preferences.    More on custom dialogs in a future posts - for now just have a play with creating menu options.  See if you can use what you have learnt above to present menu options to a user, maybe you could use Google to work out how to display a dialog to the user when they select a menu option. Good luck and all the best until next time.



Thursday 5 July 2012

Moving Forwards

As per last time apologies for the lack of posts.  What with the day job, family and having to actually do some Android Programming to write a blog about it - things can get a bit hectic.

In my last post the excuse for the lack of posts was that I had been increasing my presence on the Android Market.  I had done this by creating Addition, Subtraction, Multiplication and Division only variants of my Maths Test app which asks random Maths questions.  In addition to believing that it would be beneficial to increase my presence on the Android Market, I also believed there would be demand for these variants of the apps because you may want to start a child going with addition before moving on to subtraction, multiplication and division.  There was next to no new learning of Android concepts in creating these variants of the Maths Test app, thus the lack of posts because I had learnt nothing new to tell you about.

This time the excuse for lack of posts is that I have been learning new Android concepts.  I have done this by increasing the functionality of the original Maths Test app.  The functionality has actually been increased to a level where the four variants I had created are now obsolete and have been removed from the Android Market.  The latest version of Maths Test on the Android Market boasts the following functionality.

  • Duration of the game is now user specified (Guess what I used to get bored playing the game for 3 minutes as well).
  • The user can now choose from the following game types (Addition, Subtraction, Multiplication, Division and Random).  This is what has made the variants of Maths Test obsolete and prompted me to remove them from the Android Market.
  • The user can now choose from 5 different levels ranging from Very Easy to Very Hard.
  • A new scoring system has been introduced and user feedback has been improved.  The feedback now tells you how many questions you got correct, how many you got wrong and a score calculated using the following formula: 
(Correct Answers - Wrong Answers) * (60/Game Duration in Seconds)

In improving the functionality of the Android App I have learnt some new Android concepts and will be telling you about these in forthcoming posts.  The new concepts I have learned include the following:
  • Displaying menu options when the user presses the menu button on their phone
  • Disabling menu options when they are not applicable
  • Creating custom dialogs to get user input
  • Displaying dialogs and alerts to the user
For now go and search 'Sundev Pabla' on the Android Market.  Download the latest version of Maths Test and spend some time playing with the app.  This way you will have a better idea of what I am talking about in subsequent posts.  Enjoy playing Maths Test.  As always if you have any questions, advice or want a chat about Android then please get in touch.
 

Sunday 3 June 2012

More Apps

Sorry about the lack of posts lately.  I've been focusing on increasing my presence on the Android market.  I have added 4 more apps, check them out by searching the Android Market for 'Sundev Pabla'.

Sunday 13 May 2012

Making some money by adding adverts to your App

When your beginning with Android and still learning the trade like myself, you are unlikely to find anybody who is willing to pay for your apps.  By adding adverts to your app you can still make some money though.  A quick  Google search should reveal a number of companies which offer API's which allow you to monetize your app.  Most of these API's work on the principle of paying you every time somebody clicks on an advert.

I use the AdMob API in order to monetize my Maths Test App (Search Sundev Pabla on the Android market to locate it.).  AdMob is owned by Google.  The following links will take you through the process of adding AdMob Adds to your app (They will probably do it a lot better than I can).

https://developers.google.com/mobile-ads-sdk/docs/android/fundamentals

and

https://developers.google.com/mobile-ads-sdk/docs/android/banner_xml

These links will tell you that once you have set up an Admob acount then:


Incorporating Google AdMob Ads into your app is a three step process:
  1. Add the SDK JAR to your Eclipse project.
  2. Declare com.google.ads.AdActivity in AndroidManifest.xml.
  3. Set up required network permissions in the manifest.

I will leave you to set up an Admob account and to try and follow the above three steps for your self. If you get stuck, please feel free to post questions on the blog - Its reassuring to know that there are people out there who actually read it.  Good luck - I hope you make some money by monetizing your app.












Sunday 29 April 2012

Debugging and Testing the Application

I tested my app using the Android Emulator which is integrated with Eclipse (We previously discussed the Emulator in the post entitled "Writing your first Android program").

Having tested the app on the Emulator, I decided to test the app on my own phone.  I have found a quick and convenient way to get the app on to my phone using Dropbox.  I simply drop the app into the Dropbox folder on my PC, this is synchronised with the Dropbox app on my phone.  To learn more about Dropbox simply Google Dropbox.

Once I got the app onto my Phone, the first and most major bug I found was that my app worked fine provided the user did not rotate the phone from portrait to landscape.  You would be right in wondering why I did not spot this major flaw when testing with the emulator.  At the time I wrongly believed that the Emulator was limited on functionality, I now know that this is not the case.  You can rotate the Emulator screen by pressing Ctrl + F12.

So having found this major bug in my code, how did I fix it.  Well my good friend Google came to the rescue as usual.  A quick search of the internet revealed that unless you handle config changes then the Activity is restarted and the onCreate( ) function in the activity is called.

In order to handle config changes you need to tell the android system that you wish to handle configuration changes.  This is done in the manifest file.  I have used bold text in the extract below to show the change I had to make to the manifest file for my Maths Test App.


        <activity android:name=".TestActivity"
         android:configChanges="keyboardHidden|orientation"
                  android:label="@string/app_name">  
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

This change tells the android system that I will handle configuration changes in my code, so don't call onCreate( ) when the configuration changes, instead call

public void onConfigurationChanged(Configuration newConfig)

which I have implemented in my code.  In this function I load a different layout depending on the orientation of the phone and the size of the screen. I have obviously had to create multiple layouts (User Interfaces implemented using xml - see previous posts to learn more about layouts.).  The code extract below which I have simplified to make my point shows how to check the phone orientation and the size of the users screen.  Checking screen size requires you to do a Bitwise And - essentially I am checking to see if the small screen bit is set.

if((newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)&& ((newConfig.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) != Configuration.SCREENLAYOUT_SIZE_SMALL ))

        {
       
        setContentView(R.layout.main_smallscreen);
       
        }
        else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
        {
       
        setContentView(R.layout.main);    
        }

This has probably been fairly heavy going, so a quick summary of what has been learnt may well be useful.


  1. How to debug using the Emulator - Ctrl + F12 rotates the emulator screen
  2. How to get an app onto your phone using Dropbox
  3. How to handle configuration changes - so that your app does not restart when you rotate from portrait to landscape.
  4. How to handle different screen sizes.
I will leave you to digest the above, any questions please get in touch.







Sunday 15 April 2012

Handling User Input

In the Maths Test App, the user inputs the answer to mathematical questions by pressing buttons on the user interface.  Feedback is provided to the user via a text box or TextView in Android speak.

The following is an extract from my main.xml layout file.  Layout files were discussed in the previous post (layout files define the user interface).  This extract is for the "ENTER" button on my user interface.  The extract tells the android system that I want a button, the id that I will use to get access to the button from my code is "ButtonEnter", the text on the button should say "ENTER", the button should be aligned with the Button which has id "ButtonZero" and should be below the Button with id "ButtonNine", the button should also only be big enough in terms of height and width to display the text "ENTER".

<Button 
android:id="@+id/ButtonEnter" 
android:text="ENTER" 
android:layout_alignBaseline="@+id/ButtonZero" 
android:layout_below="@+id/ButtonNine" android:layout_toRightOf="@+id/ButtonZero" android:layout_width="wrap_content" android:layout_height="wrap_content">
</Button>

The following line declares a class variable of type Button.  The Button class inherits from the View class. (If you have learnt Java, then you should know what classes, variables and inheritance is.  If you are struggling with these concepts then you need to revise your Java).


Button ButtonEnter;

The following line is used in code to get hold of an instance of the "ENTER" button and assign the instance to the class variable created earlier.  What this line of code is doing is calling a function provided by the Android SDK called findViewById.  You pass this function an argument which is the id of the View object you want to get hold of (The id's of all Views on your user interface are stored in the R.id class).  We know that the View object returned by the function is a Button, so we specifically cast it to a button.

ButtonEnter = (Button) findViewById(R.id.ButtonEnter);

Once you have got hold of the Button object you can call functions on it.  The following function sets the OnClickListener( ).  Setting the OnClickListener( ) causes the onClick function to be called when the user presses the "ENTER" button.


ButtonEnter.setOnClickListener(this);


The this argument passed to the setOnClickListener is an instance of the current activity.  My application only has the one activity and it is the onCreate function in this class which is the first to be called.  The declaration of the Activity class is shown below, the implements OnClickListener says this class will implement an onClick( )  function.

public class TestActivity extends Activity implements OnClickListener 
{


}


The signature of the onClick function which the code must implement is shown below.  This function will be called when the Enter button is pressed.  The View passed into the function will be an instance of the button pressed.  If you have more than one View for which you have defined OnClickListeners( ) then you will have to perform a check in the onClick( ) function to determine which View was clicked (I have to do this in the Maths Test App).

public void onClick(View v) 
{


}


The following extract is again from my layout file and creates the TextView.

<TextView 
android:id="@+id/textViewQuestion" 
android:layout_width="wrap_content" 
android:text="Press any button to begin" 
android:layout_height="wrap_content" 
android:layout_below="@+id/textViewHeader" 
android:layout_alignLeft="@+id/ButtonTwo" 
android:layout_marginLeft="14dp" 
android:layout_marginTop="14dp">
</TextView>


The following three lines of code declare a variable of type TextView, get hold of the TextView and then write "Hello World" in the TextView.

TextView tvQuestionAnswerString;

tvQuestionAnswerString = (TextView) findViewById(R.id.textViewQuestion);
tvQuestionAnswerString.setText("Hello World");


Todays post has been fairly heavy on the code, so I will leave you to digest it.  Try and create a simple application which uses buttons to get user input and TextViews to provide feedback to the user. Good bye.



Saturday 7 April 2012

Creating User Interfaces

The first thing that I usually do when writing software is design the user interface.  I determine what inputs I require from the user and how I am going to get the user to provide them.  I also decide what the output of my program is going to be and how I am going to get the output to the user.  This post is going to be about creating user interfaces.

The Maths Test App is a variation on a program that I had previously written in both managed C++ using the Visual Studio IDE and also as an ASP.net application using C# and the Visual Web Developer IDE.  Express versions of both Visual Studio and Visual Web Developer are available for free from the Microsoft Website.  You may wonder why I am talking about  C# and Visual Studio on an Android Blog when we are using Eclipse and Java.  The reason is that I personally find creating user interfaces in Visual Studio much easier.  Those of you who are familiar with creating user interfaces in Visual Studio will soon realise that it is not as easy to create user interfaces for Android Apps in Eclipse.  If you have not used Visual Studio then it may be worth downloading the express version for C# and writing a few applications with GUI based user interfaces.  This will have a couple of benefits, it will give you experience of creating GUIs in what I view is a more user friendly tool. You will also gain familiarity with another IDE (Integrated Development Environment).  If you are thinking I have just learnt Java so that I can write Android Apps and even before I've got started I am being asked to learn C# then don't worry - Java and C# are almost identical.  Also to be a true Software Engineer you need to know multiple languages.  You can download Visual Studio Express for C# from the following location:

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express

Creating a user interface is so easy in Visual Studio that you can use it to quickly prototype a user interface and use that as the basis of discussions with potential users of your application.

Those of you who are already familiar with Visual Studio and want to get on with developing a user interface with Eclipse for an Android application - then the good news is that there is a visual tool for creating user interfaces in Eclipse.  As in Visual Studio you can drag and drop buttons, text boxes, labels and combo boxes on to your user interface.  Have a play with the tool for creating user interfaces by expanding the res folder, then the layout folder and then double clicking main.xml in an Android Project.  The screen shot below shows the user interface for the Maths Test Application in Eclipse.


User Interfaces in Android speak are known as layouts and are stored as xml files, have a look at the raw xml because you will need to understand it.  You will need to hand crank the xml at times, you will not be able to create the entire user interface by dragging and dropping components.

One of the very first lines of code in an Android Application usually loads the user interface.  An example of the line for loading a layout file called main.xml is shown below:

setContentView(R.layout.main);

That is all for today, go and practice creating GUI based user interfaces in either Visual Studio or Eclipse.  Until next time, good bye.


Friday 6 April 2012

My first real App

My first app is called Maths Test and is featured on the Android Market.  Being a first app it is limited on functionality, I intend to extend its functionality over time.  Its worth getting the app because I will refer to it on this Blog regularly and will be using it as the basis of tutorials (To locate the app, simply search Sundev Pabla on the Android market).  Overtime I will probably end up publishing the full source code for the app.

Maths Test is a game in which you must answer as many mathematical questions as you can in three minutes.  You will not be presented with a new question until you get the question correct. The questions are a random selection of addition, subtraction, division and multiplication.  At the end of the game the player is told how many answers he got correct.

In subsequent posts, I will  cover the following topics:

  • Creating the layout (This is the user interface, also known as a GUI)
  • How to respond to user input
  • Bugs and issues that I encountered (The first time I played the game, I felt very pleased with my self.  I then rotated my phone and found that although the game worked fine in portrait mode it restarted itself when you rotated to landscape.  Find out why this was the case and what I did about it).
  • Using the Emulator (I didn't need to install the app on my mobile to find out I had issues when I rotate the phone to landscape.  Its possible to rotate the emulator - my old friend Google told me how to do this)
  • How to add adverts to the app
  • Where next for the app, what functionality could be added.
That is all for today.  Join me again to learn how the Maths Test app was developed.

Sunday 1 April 2012

Writing your first Android program

Following tradition, I started learning Android by going to the Hello World tutorial and implementing it.  The Hello World tutorial for Android can be found at:


This tutorial covers a lot more than just how to write Hello World to the screen.  It covers:

  1. Installing a Platform using the Android SDK Manager - Installing the Android SDK does not install everything you need  (Neither would you want it to because you may not want to program for all versions of Android released to date or you may not have room to install them all).  I think I only installed the latest version as suggested in the tutorial.
  2. Creating an Android Virtual Device using the AVD Manager - The virtual device or emulator is used to test your Android program.  Yes you could test it out on your own device, however you probably have one may be two Android devices (Possibly a smart phone and a tablet) - using the AVD Manager you can emulate devices that you don't own.
  3. Creating your first Android Project - After creating the Android project, browse the folders so that you get a feel for what an Android project contains.  Have a look at the AndroidManifest.xml and the res/layout/main.xml - you will learn more about these later.
  4. Creating a User Interface using Code
  5. Running the Application
  6. Updating the User Interface to use an XML layout which the code loads in
Work through the tutorial, then have a play - try writing different things to the screen, remember you will never learn much just following steps in a tutorial.  You need to play, try things out and read around the subject.

I will be back with more later, when we start delving deeper into the world of Android.

Saturday 31 March 2012

Getting the tools specific to Android Programming

If you have been following my blog, then by now you have downloaded Eclipse and you have either learnt or already knew Java programming.

Despite me not telling you to (Sorry about that!), you will also have downloaded the JDK (Java Development Kit).  The JDK is different to the JRE (Java Runtime Environment), the JRE is sufficient if you only want to run Java programs - however if you want to develop  Java programs then you need the JDK.

In order to program for Android you need to download a couple more tools in addition to Eclipse.  You must download the Android SDK (Software Development Kit) and the ADT Plugin for eclipse.

The following website contains advice on installing and configuring the Android SDK and the ADT Plugin.

http://developer.android.com/sdk/installing.html

The Android Developer website the above link takes you to is well worth exploring.  For now go and get the necessary tools and explore the Android Developers website.  We will meet here again  to start doing some Android programming.

Wednesday 28 March 2012

Mastering the basics

I know that some of you more experienced programmers will be keen to get started with Android programming.  I will do one or two more posts for the complete beginners before sending them off to acquire the required java skills.  The rest of us can then continue on our Android journey and the beginners can catch up.

So you have now downloaded eclipse - what next.  In Eclipse you should find a hello world tutorial.  Try following this (It is traditional for the first program to be the hello world program).  Also spend a bit of time just playing with Eclipse and looking at some of the introductory sections of the help.

Then try searching the internet for 'java tutorials for beginners'.  Work through some or these tutorials.  So far you have not spent a penny.  At this stage you may want to invest in a java book for beginners, alternatively you could borrow one from the library.  I usually go for books like 'java for dummies' or 'learn java in 24 hours'.  I find that these books are an easy read and the chapters are in manageable chunks.  Take your time working through a beginners book, you will need a sound grasp of the basics before you start Android programming.

When working through a book it is a good idea to know what concepts you are trying to learn.  You need to develop an understanding of the following concepts:

If Statements
Loops (for, do, while)
Data types (Integers, doubles, strings)
Structures and Arrays
Writing functions

More advanced concepts that you will need to master include:

Classes
Objects
Inheritance, Encapsulation, Polymorphism.

This is not an exhaustive list of concepts.

Programming skills require practice.  In order to practice your newly acquired programming skills try and come up with a few projects for your self.  Use your book and the internet to complete your project.

The projects don't need to be complex.  For example to practice loops you could write a program which asks the user to enter a number.  The program could then loop that number of times, writing 'I love you' to the screen that many times (Just be careful about who you ask to test this program).  Another project to practice if statements may involve randomly generating a 3 digit number and then asking the user to guess it.  An if statement would be used to test if the user entered number is greater than or less than the generated number.  The program would loop providing appropriate feedback to the user until the number was guessed.

The basic concepts that you learn are common to all programming languages, only the syntax changes.

You will also need to learn how to debug programs.  This will involve understanding breakpoints, stepping through code and watching variables.  Play about with Eclipse to see if you can work out how to do this.

Now go and learn java.  Good luck, remember Google is your friend - however if you can't find the answer to your question via Google, then feel free to post it on this blog (You can use comments to post questions).  I will do my best to answer the question, if I can't answer it then I am sure somebody out there will be able to.  Also any general feedback that you want to give me will be greatly appreciated.

Enjoy learning java, until next time - Good bye

Saturday 24 March 2012

Knowledge and Tools of the trade

I want this blog to be all inclusive, which means catering for the complete beginner (I'm talking about complete beginners to programming and not just Android).

So what does a complete beginner need.  It goes without saying that you need access to a computer or laptop.

The next question to consider is which programming language to learn.  Take it from somebody that has worked with numerous programming languages over the years, once you know the basics of programming in one language then picking up a new language becomes relatively simple.

If you are a complete beginner then I would begin your programming career by learning java, because this is the language we will be using to write Android apps.

Different people learn in different ways.  The way I learn is by doing, so my advice to you is get the tools needed together and get programming.  You will not master programming by reading a java book from start to finish.  There is a place for books but that comes later.

So what tools do you need.  Download Eclipse once you have finished reading this post.  Eclipse is an Integrated Development Environment that you need in order to write code, it is free to download.  Eclipse is the main tool you need to write Java programs and Android applications.

Where do you download Eclipse from?  Remember Google is your friend.  I could tell you where to find Eclipse but you need to start using the internet to find solutions - you will never know all the answers your self.

Go get Eclipse now and then come back for the next installment for advice on how to progress.

Google is your friend

Google is your friend - This is a lesson that I have learned over the years.  When I don't know how to do something or can't remember how to do something whilst coding, a quick search of the internet usually gives me the answer.

The Google is your friend advice is also applicable to Android development in more ways than one.  For a long time I had an aspiration of developing educational software, being a Software Engineer though, I did not want to develop hardware on which to run my software.  What Google has done with Android is given me an interface to numerous different devices running Android.  These devices can host my applications.  Google has also provided me with a world wide market through the Android market.

My aspiration of developing educational software included the desire to make it available for free.  However I did want some compensation for my efforts, again Google comes to the rescue with Admobs and Adsense - These two methods allow me to add adverts to my apps and blogs respectively, which in time will hopefully generate me some revenue.

It's the weekend so I have more time, so the next installment will be soon.  It will cover how I got hold of the tools needed for Android development and how I got started with my first app.  In the mean time, if you want to check out my first app then search the Android market for Sundev Pabla.  I know the app is simple and limited on functionality - however I believe in getting a product to market quickly and then progressively increasing its functionality with upgrades.  Take care, I will be back soon.

Thursday 22 March 2012

Welcome

I believe that its important for you to know a little bit about me so that you can make an informed decision about whether or not you wish to follow me.  So here goes....

I graduated from Loughborough University in 2000 as an Engineer.  I then spent another year at Loughborough doing a P.G.C.E (Teacher training - by the end of the course the kids had persuaded me that teaching was not for me).

I  am now a Chartered Engineer with 10 years plus experience of working as a Systems / Software engineer.   I have worked right through the development life cycle from requirements analysis on major international bids, to design, development, integration and delivery of big software and systems projects for large multinational companies.

I have experience of programming in FORTRAN, matlab, c++,ADA, VB.net, C#, JAVA and probably other languages that I can't recall. 

I recently started developing Android apps and have published my first app on the Android market.  I am by no means an Android expert, but I want to share my experiences to date.  I also want you to join me on the next part of my Android journey.  I will try to blog as regularly as I can, sharing tips, giving advice, warning of pit falls.  I will also be wanting to learn from you, so please don't just read my blog, provide comments, ask questions, give me advice and if you think I have got it wrong then please shout.

That's all for now.  The aim of today was to introduce my self. In the next installment, I will discuss my Android experiences to date.  Take care until next time.