heading

heading

Saturday, 17 May 2014

Set Up Your Personal SVN Repository Server For Free

Did you know you can have a private repository server to host your projects without any cost?  Ohh Yes. You can!! For this tutorial we shall use BitBucket to host a private SVN repository.  Other free host include beanstalkapp and Spring Loops, both of which give you at least one repository, maybe 100mb of space and a few user accounts to play with.  This is great for one project, but when you start another one or if you run out of space, you have to create a new account with a different email address (or different urls, etc..)
Fortunately we have BitBucket where we can host our code online in as many public and private repositories as we want and that for 5 users. Isn't that great!!!
So, firstly sign up on BitBucket (which is free and very easy to do). Once signed in, create a new repository (you can choose from either making the repository private or public).  For the repository type, select 'Mercurial'.  I have made a screenshot to help you with the process.


The next step will be to download the TortoiseHg which is very similar to TortoiseSVN, except that its for Mercurial revision control systems.  So download it and install it on your machine.  Please note after successful installation, it is recommended to restart your machine.

To confirm that TortoiseHg is properly installed on your machine, open command prompt on Windows and type the following command: " C:\> hg".  If you get all the basic command displayed on the command prompt screen, then you are on the right track.

Now here comes probably the harder part. Create a new folder in your Local Disk C directory and name it repository1.  Now on the command prompt, go that newly created directory and type in the commands "C:\repository1>  hg clone https://bitbucketusername@bitbucket.org/bitbucketusername/repositor1".  This url is already provided to you by bitbucket.


Now its time for us to create our first file. So go to your repository1 folder on your local machine and create a new html file. You can call it whatever name your want, for example home.html.  To synchronize the new file with your repository on bitbucket, right click on the file -> TortoiseHg -> Add File. After doing this step, right click again on the folder and click on Hg Commit.



Finally after adding all your required files and after doing all necessary changes, you need to push all the changes to your repository on BitBucket. To do that, just right click anywhere in the repository1 folder and click on Hg Workbench.  Click on the button indicated on the screenshot above to push all the changes to your remote repository.  Congrats!!! You now have a private & personal SVN server without spending a single penny. Good luck with BitBucket and TortoiseHg.

Note: You can view the step-by-step guide for TortoiseHg here.

Monday, 27 January 2014

Android AsyncTask: When, Why and How to Use?

This post provides an overview of the Android AsyncTask class.  As always, I'll try my best to make things appear as simple as possible.  Without losing any further seconds, lets start!

AsyncTask, short form for Asynchronous Task is an abstract class that allows to perform background operations and publish the result on the UI thread without having the need to manipulate threads or handlers.  In simple words:

 AsyncTask enables proper and easy use of the UI thread.


When and Why to use AsyncTask?
Android implements a single thread model.  Whenever an Android application is launched, the system creates a "main" thread of execution for the application.  The main thread is also sometimes called the UI thread.  It is to be noted that the system does not create a separate thread for each instance of a component.

Consider the following situation. After entering his login details, a user clicks on the "Sign In" button. On button click, a request is sent to the server for authentication.  While awaiting for a response from the server, the screen will be non-responsive since Android is based on a single thread model.   These kind of situations is less likely desirable by a user.  Therefore we should avoid performing long running operations on the UI thread.

One solution to this issue might be to create a new thread and implement the famous run() method to perform this network call while keeping UI responsive.  However, if there is the need to make some changes on the UI based on the result of the operation performed. other issues may pop up.  To conclude:

 For file and network access operations, it is recommended to use the AsyncTask


How to use?
An asynchronous task is defined by 3 generic types:

AsyncTask<Params, Progress, Result>


AsyncTask has four steps:
  • onPreExecute() 
Invoked on the UI thread before the task is executed.  This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  • do InBackground(Params...)
Invoked on the background thread immediately after onPreExecute() finishes executing.  This step is used to perform background computation that can take a long time.
  • onProgressUpdate(Progress...)
This method is used to display any form of progress in the user interface while the background computation is still executing.
  • onPostExecute(Result)
Invoke on the UI thread after the background computation finishes.  The result of the background computation is passed to this step as a parameter.

Below is an example that I retrieved from the official Android Developer's site.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
Once created, a task is executed very simply.

new DownloadFilesTask().execute(url1, url2, url3);

A working example of the AsyncTask can be found here.

Saturday, 25 January 2014

Android Login Application Using AsyncTask and HttpClient



In this tutorial, we are going to develop a simple app which will accept a username and a password from the user and send to the localhost server for authentication.  If the login information entered is correct, the user will be navigated to the main menu, otherwise an error message will be displayed.  This application will make use of the HttpClient class and also the AsyncTask class.

This tutorial will be divided into:
  • Server Side: The sever side will be a PHP(check.php) file hosted on a localhost server.
  • Client Side:  The client side represents our android application.

Structure of the Android Project:
  • Classes: 
    • LoginActivity.java
    • MainMenuActivity.java
    • CustomHttpClient.java
  • XML file:
    • activity_login.xml
    • activity_mainmenu.xml
Codes:
  • AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.logintutorial"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.logintutorial.LoginActivity"
            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.example.logintutorial.MainMenuActivity"
            android:label="@string/app_name" >
        </activity>
    </application>
</manifest>
  • res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">logintutorial</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="heading1">Welcome. Login to continue.</string>
    <string name="heading2">Login Success! You are on the main menu.</string>
    <string name="hint_user">enter your username</string>
    <string name="hint_pwd">enter your password</string>
    <string name="login_button">LOGIN</string>
</resources>
  • res/layout/activity_login.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LoginActivity" >

     <TextView
        android:id="@+id/txtheading1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtError"
        android:layout_alignParentTop="true"
        android:layout_marginTop="57dp"
        android:gravity="center"
        android:text="@string/heading1"
        android:textColor="#00F"
        android:textSize="40sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/txtUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtheading1"
        android:layout_below="@+id/txtheading1"
        android:layout_marginTop="105dp"
        android:ems="10"
        android:hint="@string/hint_user"
        android:textSize="25sp" />
     
    <EditText
       android:id="@+id/txtPassword"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/txtUsername"
       android:layout_below="@+id/txtUsername"
       android:layout_marginTop="40dp"
       android:ems="10"
       android:hint="@string/hint_pwd"
       android:textSize="25sp" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/txtPassword"
        android:layout_below="@+id/txtPassword"
        android:layout_marginTop="28dp"
        android:text="@string/login_button"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/txtError"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="" />

</RelativeLayout>

  • res/layout/activity_mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

     <TextView
         android:id="@+id/txtheading1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:layout_marginTop="131dp"
         android:gravity="center"
         android:text="@string/heading2"
         android:textColor="#00F"
         android:textSize="40sp"
         android:textStyle="bold" />

</RelativeLayout>
  • src/com.example.logintutorial/LoginActivity.java
package com.example.logintutorial;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

//define controls
EditText  txt_uname, txt_pwd;
TextView  txt_Error;
Button btnLogin;
String response = null;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        //initalise controls
        txt_uname=(EditText)findViewById(R.id.txtUsername);
        txt_pwd=(EditText)findViewById(R.id.txtPassword);
        btnLogin =(Button)findViewById(R.id.btnLogin);
        txt_Error =(TextView)findViewById(R.id.txtError);
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String uname = txt_uname.getText().toString();
String pwd = txt_pwd.getText().toString();
validateUserTask task = new validateUserTask();
task.execute(new String[]{uname, pwd});
}
        }); //close on listener
    }// close onCreate
    
    private class validateUserTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
                postParameters.add(new BasicNameValuePair("username", params[0] ));
                postParameters.add(new BasicNameValuePair("password", params[1] ));
                String res = null;
        try {
           response = CustomHttpClient.executeHttpPost("http://akinads.0fees.net/check.php", postParameters);
           res=response.toString();
           res= res.replaceAll("\\s+","");                        
       
        catch (Exception e) {
        txt_Error.setText(e.toString());
        }
return res;
}//close doInBackground
@Override
protected void onPostExecute(String result) {
if(result.equals("1")){
//navigate to Main Menu
Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
startActivity(i);
}
else{
txt_Error.setText("Sorry!! Incorrect Username or Password"); 
}  
}//close onPostExecute
    }// close validateUserTask 
}//close LoginActivity
  • src/com.example.logintutorial/MainMenuActivity.java
package com.example.logintutorial;
import android.app.Activity;
import android.os.Bundle;

public class MainMenuActivity extends Activity{
@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_mainmenu);
   }
}//close MainMenuActivity
  • src/com.example.logintutorial/MainMenuActivity.java
package com.example.logintutorial;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
/** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }
    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

As mentioned previously, the server side will be a PHP file hosted on a domain or on a localhost server.  In this example, the PHP file consist of a static 'if..else' function.  However, you can customize the PHP file to link it to your database. 
  • check.php
<?php
//you can include here: Database connection & SQL query
    try{
         $uname = $_POST['username'];
         $pw = $_POST['password'];
         //valid login
         echo "1";
    }
    catch(PDOException $e)    {
        echo $e->getMessage();
    }
?>

Friday, 24 January 2014

Android Development Tips and Resources



Get Started with Android Application Development


This post is for novices interested in starting Android Application Development.  More people are now relying on smartphones and tablets to stay connected and Android is the current leading mobile platform.  Therefore the opportunities for Android app developers are enormous.

To start developing Android apps, lets see what are the tools that we require:
1.  Android requires the Java Development kit (JDK) version 5 or higher.  This can be downloaded here.
2. Next we have to download the ADT Bundle.  This can be downloaded here.

The ADT Bundle includes:
1. Eclipse IDE:  Eclipse is the recommended integrated development environment (IDE) for developing Android apps.
2. Android SDK: The Android Software Development Kit (SDK) provides the tools that we need to develop, test and debug Android apps.
3. ADT Plugin:  The Android Development Tools (ADT) Plugin for Eclipse allows us to use the Android SDK tools to develop Android apps in the Eclipse IDE.
4. Android Emulator:  The Android Emulator is helpful if ever we don't have any Android smartphone/tablet.  The emulator allows us to run Android apps in a simulated environment on our machine rather than on an actual Android device.

Extract the Zip file and install the required software.  The next step will be to create our Android Virtual Device (AVD).  Basically this will be the simulated version of the physical device on which we want to test our app.  A tutorial for doing this is available here.