Monday, 31 December 2012

Build an Android app using JQuery and HTML

In this post, I am going to explain how to create a simple android application using Html and javascript as grphical interface. Basic concept is loading html file in Webview object using Web Client in Android.

Assuming Eclipse environment for developing Android applications is ready.

What we are going to do sample?
Create a html file which contains few hard coded contacts list items and two buttons (Exit & About) on the top in Main page. On About click, About us page will be shown. Back button in About Us page returns to Main page.

Create new Android project by clicking File>New>Android Application Project and name it as 'MyContacts'.

First we design a simple HTML file to host it on mobile.
Contact.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <style type="text/css">
        body
        {
            background: Black;
            color: White;
            font-size: small;
        }
        .Header
        {
            border: 1px solid #AAA;
            width: 100%;
        }
        
        .Button
        {
            text-align: center;
            border: 1px solid #333;
            background: #AAA;
            width: 50px;
            font-weight: bold;
            padding: 5px;
            float: left;
            color: #000;
            margin: 1px;
            cursor:pointer;
        }
        .Left
        {
            float: left;
        }
        .Right
        {
            float: Right;
        }
        .Content
        {
         Float:Left;
            width: 100%;
            background: #AAA;
            border: 1px solid #AAA;
            height: auto;
            margin: 1px;
        }
        
        .AboutUs
        {
         Float:Left;
            width: 100%;
            background: #AAA;
            border: 1px solid #AAA;
            height: auto;
            margin: 1px;
            padding:10px;
        }
        
        .ContentHeader
        {
            border: 1px solid #333;
            padding: 2px;
            font-weight: bold;
            color: #000;
        }
        .ContentItem
        {
            border: 1px solid #333;
            padding: 2px;
            margin: 1px;
            color: #333;
        }
    </style>
   <script type="text/javascript">
   $(document).ready(function(){
    $("#About").click(function(){
     $(".Content").hide(); 
     $(".AboutUs").show(); 
     });
    $("#Back").click(function(){
     $(".Content").show(); 
     $(".AboutUs").hide(); 
     });
   });
    </script>
</head>
<body>
    <div class="Header">
        <div class="Button Left">
            Exit</div>
        <div id="About" class="Button Right">
            About</div>
    </div>
    <div class="Content">
        <div class="ContentHeader">
            Contacts</div>
        <div class="ContentItem">
            Andrew</div>
        <div class="ContentItem">
            Chris</div>
        <div class="ContentItem">
            David</div>
        <div class="ContentItem">
            Mickel</div>
        <div class="ContentItem">
            Mahesh</div>
    </div>
    <div class="AboutUs" style="display:none;">
    Developed By : tekpot.blogspot.com<br/>
    Thank You! <br/>
    Happy Coding!
    <div id="Back" class="Button Right">
            Back</div>
    </div>
    
</body>
</html>

Preview will be as

In the above html file I have included JQuery plugin google reference. Instead download JQuery and include local reference to html file.
Copy paste Contact.html and Jquery.min.js files in Project folders as mentioned path bellow.
MyContacts/assets/www/contact.html
Create a Webview object and load our Contact.html page in MyContacts activity class.
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ContactActivity extends Activity {
    /** Called when the activity is first created. */
 WebView mWebView;  

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webview); 
        mWebView.getSettings().setJavaScriptEnabled(true);  
        mWebView.getSettings().setDomStorageEnabled(true);  
        mWebView.loadUrl("file:///android_asset/www/Contact.html");
    }
}
In the above code WebView mWebView; webview object is declared.

        mWebView.getSettings().setJavaScriptEnabled(true);  
        mWebView.getSettings().setDomStorageEnabled(true);  

above statements enable Javascript and DOM object in Android Webview.

        mWebView.loadUrl("file:///android_asset/www/Contact.html");

LoadUrl loads html file mentioned in the path. Http url can be given in LoadUrl method.
Example

        mWebView.loadUrl("Http://google.com");

Compile and run the application in simulator.
Main Page


About Us page


Thats it we have developed a simple Android application using Javascript and html with out using much Java code.

Wait for next post to load data from server and display on html and javascript.

Happy Coding! :-)

Tuesday, 11 September 2012

Javascript Pivot Library

Arikai - Javascript Pivot Library - Niral Aakkam

A new version of Arikai - a simple javascript pivot library is released. Easy, simple, client side pivot table report generator using Jquery. Arikai supports SUM, AVG, MIN, MAX and COUNT aggregate functions. 

Arikai online demo - Niral Aakkam
Arikai online demo - Niral Aakkam

Edit Layout button offers user to change the report dynamically. New fields can be added  in to / swapped Column Area / Row Area by drag n drop. Few steps of javascript code generates the Pivot Table.

Check Arikai online demo here.

Javascript file and stylesheet file are available for downloaded at Niral Aakkam. or GitHub

Sample website in C# is available at Niral Aakkam dowload page. or GitHub
 

For more information visit Niral Aakkam web site.

Friday, 7 September 2012

Location using GPS in Android programming

GPS Location in Android

Find current latitude and longitude location by using GPS

No need GPRS or Internet connection

We need to add permission for accessing GPS. So put following tag in Android manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>  
Import the necessary libraries
 import android.location.Location;  
 import android.location.LocationListener;  
 import android.location.LocationManager;  
Create a Listener class for loaction
 /* Class My Location Listener */  
 public class MyLocationListener implements LocationListener {  
   @Override  
   public void onLocationChanged(Location loc) {  
     loc.getLatitude();  
     loc.getLongitude();  
     String Text = "My current location is: " + "Latitude = "  
         + loc.getLatitude() + "Longitude = " + loc.getLongitude();  
     Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT)  
         .show();  
     Log.d("TAG", "Starting..");  
   }  
   @Override  
   public void onProviderDisabled(String provider) {  
     Toast.makeText(getApplicationContext(), "Gps Disabled",  
         Toast.LENGTH_SHORT).show();  
   }  
   @Override  
   public void onProviderEnabled(String provider) {  
     Toast.makeText(getApplicationContext(), "Gps Enabled",  
         Toast.LENGTH_SHORT).show();  
   }  
   @Override  
   public void onStatusChanged(String provider, int status, Bundle extras) {  
   }  
 }/* End of Class MyLocationListener */  
Declare LocationManager object in Activity
  LocationManager locationManager; 
  private String provider;
Override onCreate method of Activity
@Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);   
     LocationListener mlocListener = new MyLocationListener();  
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);     
      Criteria criteria = new Criteria();  
       criteria.setAccuracy(Criteria.ACCURACY_COARSE);  
       criteria.setAccuracy(Criteria.ACCURACY_FINE);  
       provider = locationManager.getBestProvider(criteria, true);  
       locationManager.requestLocationUpdates(provider, 61000, 250,  
         mlocListener);  
   }
Happy coding...

Saturday, 11 August 2012

Android AutoCompleteTextView data binding based on another AutoCompleteTextView selection

Android - Bind data to an AutoCompleteTextView based on another AutoCompleteTextView selection

Hi friends, here I am going to explain how to load an AutoCompleteTextView based on the selection of another AutoCompleteTextView in Android.

Create screen layout xml file

Add following in layout xml file as station_input.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/ station_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp" >

        <AutoCompleteTextView
            android:id="@+id/fromStation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:imeOptions="actionNext"
            android:inputType="text"
            android:singleLine="true"
            android:text="@string/From" >
            <requestFocus />
        </AutoCompleteTextView>

         <AutoCompleteTextView
             android:id="@+id/toStation"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:ems="10"
             android:imeOptions="actionDone"
            android:inputType="text"
            android:singleLine="true"
             android:text="@string/To" >
            <requestFocus />
        </AutoCompleteTextView>
    </LinearLayout>

Add list_station.xml to the project layout folder

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="14sp"
    android:textColor="#000">
</TextView>

Bind data to first AutoCompleteTextView

 // Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id. station_input);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View layout = layoutInflater.inflate(R.layout. station_input, viewGroup);

    
    // bind all stations to station auto complete
  AutoCompleteTextView fromStation = (AutoCompleteTextView) layout.findViewById(R.id.fromStation) ;
                   // Helper class for getting Stations list from Databse. 
  DatabaseHelper helper = new  DatabaseHelper();
  List<String> stationsList =helper.GetStations(context); 
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.list_station, stationsList);
  fromStation.setAdapter(adapter);
  fromStation.setText("");

  
  
  
  toStation = (AutoCompleteTextView) layout.findViewById(R.id.toStation) ;
  toStation.setText("");

setOnItemClickListener for first AutoCompleteTextView

//  add item click listener for fromStation AutocompleteTextView 
  fromStation.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3){
                                // get the clicked item in fromStation
String fromStationSelected = arg0.getItemAtPosition(arg2).toString().split("-")[1];

                                 // Helper class for getting Stations list from Databse.
DatabaseHelper  helper = new  DatabaseHelper();
  List<String> stationsList = helper.GetToStation(context,  fromStationSelected ); 
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.layout.list_station, stationsList);
  toStation.setAdapter(adapter);
  toStation.setText("");
 
}
});
    
  toStation.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3){
  
  // to do what ever you want in item click of second AutoCompleteTextView (toStation)
          
}
});



If any better way, please feel free to comment.

Enjoy Coding. 

Friday, 3 August 2012

Build an Android app using existing SQLite database

Step by step guide to use existing sqlite database file in Android application.



Step 1.
Prepare the SqLite database file

Step 2.
Create a table android_metadata in the database,
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
Insert a record as follows
INSERT INTO "android_metadata" VALUES ('en_US')
Step 3.
Rename primary Id fields of existing tables as _Id. So that Android will know where to bind the id field of your tables.

Now the database is ready.

Step 4.
Simply copy and paste the database.db file to 'assets' folder of the android project.

Step 5.
Create a class MyDatabaseAdapter to access the our own database through project.
It will extend from SQLiteOpenHelper class, which is in android.database.sqlite namespace.
MyDatabaseAdapter class look like this.

public class MyDatabaseAdapter extends SQLiteOpenHelper {

    private Context mycontext;

    private String DB_PATH = "data/data/texkpot.package.app/databases/";
//dont forget to change your namespace.package.app
    private static String DB_NAME = "database.db";
    // the extension may be .sqlite or db
    public SQLiteDatabase myDataBase;

    public DatabaseAdapter(Context context) {
        super(context, DB_NAME, null, 1);
        this.mycontext = context;
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            System.out.println("Database doesn't exist");
            try {
                createdatabase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void createdatabase() throws IOException {
        boolean dbexist = checkdatabase();
        if (dbexist) {
        } else {
            this.getReadableDatabase();
            try {
                copydatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkdatabase() {
        boolean checkdb = false;
        try {
            String myPath = DB_PATH + DB_NAME;
            File dbfile = new File(myPath);
            checkdb = dbfile.exists();
        } catch (SQLiteException e) {
            System.out.println("Database doesn't exist");
        }

        return checkdb;
    }

    private void copydatabase() throws IOException {

        // Open your local db as the input stream
        InputStream myinput = mycontext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        @SuppressWarnings("unused")
        String outfilename = DB_PATH + DB_NAME;

        // Open the empty db as the output stream
        OutputStream myoutput = new FileOutputStream(
                "data/data/test.test.test/databases/test");

        // transfer byte to inputfile to outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myinput.read(buffer)) > 0) {
            myoutput.write(buffer, 0, length);
        }

        // Close the streams
        myoutput.flush();
        myoutput.close();
        myinput.close();

    }

    public void open() {
        // Open the database
        String mypath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(mypath, null,
                SQLiteDatabase.OPEN_READWRITE);

    }

    public synchronized void close() {
        myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}

thats it.

Step 6. 
Now we can create the instance of the MyDatabaseAdapter class to create and open the database.
The code will look like this


        DataBaseHelper myDbHelper = new DataBaseHelper();
        myDbHelper = new DataBaseHelper(this);
        try {
         myDbHelper.createDataBase();
  } catch (IOException ioe) {
  throw new Error("Unable to create database");
  }

  try {
  myDbHelper.openDataBase();
  }catch(SQLException ex){
  throw ex;
  }