Friday, 16 March 2018

Sort HTML Table using JavaScript

Here is how you can sort your HTML data using a simple Javascript function WITHOUT using any external library.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sort Table using Javascript</title>

<script type="text/javascript">

/*
* These variables as name suggests store the column index based on
* which the table wil be sorted and also the sorting order
*/
var sortOrder;
var sortColumn;

function sortTable(column) {

/*
* First we will determine if the user has clicked the table for first
* time indicating that the table should be sorted in Ascending order. If
* user has clicked on it second time, then table will be sorted in
* descending order.
*/
if (sortColumn != column) {
sortColumn = column;
sortOrder = "asc";
} else if (sortColumn == column && sortOrder == "asc") {
sortOrder = "desc";
} else if (sortColumn == column && sortOrder == "desc") {
sortOrder = "asc";
}

var tableData = document.getElementById("myTable");
//This variable stores the complete Table Data
var tableRows = tableData.rows;

// Here we will convert the table data into an array for easy processing
var sortDataArray = [];
for (index = 1; index < tableRows.length; index++) {
sortDataArray.push(tableRows[index]);
}

/*
* Here we will pass the data array along with the column index, and
* sorting order to the data sorting algorithm. Here Merge Sort algorithm
* is being used to sort data.
*/
mergeSort(sortDataArray, 0, sortDataArray.length - 1, sortColumn,
sortOrder);

/*
* And Voila, sorting algorithm has sorted the data and returned data in a sorted array.
* Now all that's left is to set the sorted table data back into the html table.
*/
var sortedTableBody = "";
for (rowIndex = 0; rowIndex < sortDataArray.length; rowIndex++) {
sortedTableBody += "<tr>";
var rowCells = sortDataArray[rowIndex].cells;
for (columnIndex = 0; columnIndex < rowCells.length; columnIndex++) {
sortedTableBody += "<td>" + rowCells[columnIndex].innerHTML
+ "</td>";
}
sortedTableBody += "</tr>";

}

document.getElementById("myTableBody").innerHTML = sortedTableBody;
}

function mergeSort(arr, l, r, sortColumn, sortOrder) {

if (l < r) {
var m = Math.floor(l + (r - l) / 2);

mergeSort(arr, l, m, sortColumn, sortOrder);
mergeSort(arr, m + 1, r, sortColumn, sortOrder);

merge(arr, l, m, r, sortColumn, sortOrder);
}

}

function merge(arr, l, m, r, sortColumn, sortOrder) {

var i;
var j;
var k;
var n1 = m - l + 1;
var n2 = r - m;

var L = [];
var R = [];

for (i = 0; i < n1; i++) {
L[i] = arr[l + i];
}

for (j = 0; j < n2; j++) {
R[j] = arr[m + 1 + j];
}

i = 0;
j = 0;
k = l;
if (sortOrder == "asc") {
while (i < n1 && j < n2) {
if (L[i].cells[sortColumn].innerHTML <= R[j].cells[sortColumn].innerHTML) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
} else if (sortOrder == "desc") {
while (i < n1 && j < n2) {
if (L[i].cells[sortColumn].innerHTML >= R[j].cells[sortColumn].innerHTML) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
}

while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
</script>

</head>
<body>
<!-- Dummy Table to perform Sort Operation on Columns -->
<table id="myTable" border="1">
<thead>
<tr>
<th onclick="sortTable(0)">Alphabetical Data</th>
<th onclick="sortTable(1)">Numerical Data</th>
<th onclick="sortTable(2)">Alphanumerical Data</th>
</tr>
</thead>
<tbody id="myTableBody">
<tr>
<td>Hello</td>
<td>132</td>
<td>CR7</td>
</tr>
<tr>
<td>Alphabet</td>
<td>798</td>
<td>LM10</td>
</tr>
<tr>
<td>Coding</td>
<td>498</td>
<td>07CL</td>
</tr>
<tr>
<td>Redefined</td>
<td>369</td>
<td>18WC</td>
</tr>
</tbody>
</table>
</body>
</html>

Sunday, 26 July 2015

Android Check Network Connection

You may be building an application which requires an Internet connection. It is very important to detect the internet connection before the application starts working so that to prevent the application from raising exceptions. Here I am explaining how to achieve the goal.

First you need to include the permissions in the Manifest file after the <application> tag.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


After including the permissions, just add a few lines of code where you want to detect the internet connection.

ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] arrar_ni = cm.getAllNetworkInfo();
        for (NetworkInfo ni : arrar_ni)
        {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            {
                if (ni.isConnected())
                {
                    Toast.makeText(this, "WiFi Available", Toast.LENGTH_LONG).show();
                } else
                {
                    Toast.makeText(this, "WiFi Not Available", Toast.LENGTH_LONG).show();
                }
            }
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            {
                if (ni.isConnected())
                {
                    Toast.makeText(this, "Mobile Available", Toast.LENGTH_LONG).show();
                } else
                {
                    Toast.makeText(this, "Mobile Not Available", Toast.LENGTH_LONG).show();
                }
            }
        }



The above code will generate Toast displaying the availability and type of internet connection. You can replace the Toast statements with your code according to the requirement of your application.

Sunday, 15 March 2015

Android Date Picker

So here we are with an example to demonstrate how to implement Date Picker in your Android application.

First we need to create a TextBox to display the date and a button to trigger the Date Picker Dialog Box.

<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="com.codingredefined.datepicker.MainActivity" >

    <TextView
        android:id="@+id/displayDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:id="@+id/pickDate"
        android:layout_below="@+id/displayDate"
        android:paddingTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pick Date" />

</RelativeLayout>



After creating the layout for our application we need to add following code in our MainActivity class.

package com.codingredefined.datepicker;

import java.util.Calendar;

import android.support.v7.app.ActionBarActivity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity
{

private TextView displayDate;
private int mday, mmonth, myear;
static final int DATE_DIALOG_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        displayDate = (TextView)findViewById(R.id.displayDate);
        Button pickDate = (Button)findViewById(R.id.pickDate);
       
        pickDate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

showDialog(DATE_DIALOG_ID);

}
});
   
        final Calendar c = Calendar.getInstance();
        myear = c.get(Calendar.YEAR);
        mmonth = c.get(Calendar.MONTH);
        mday = c.get(Calendar.DAY_OF_MONTH);
        updateDisplay();
       
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
    switch(id)
    {
    case DATE_DIALOG_ID:
    return new DatePickerDialog(this, dateSetListener, myear, mmonth, mday);
    }
    return null;
    }
   
    protected void onPrepareDialog(int id, Dialog dialog)
    {
    switch(id)
    {
    case DATE_DIALOG_ID:
    ((DatePickerDialog)dialog).updateDate(myear, mmonth, mday);
    break;
    }
    }
   
    private void updateDisplay()
    {
    displayDate.setText(new StringBuilder().append(mmonth +1).append("-").append(mday).append("-").append(myear).append(" "));
    }
   
    private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub

myear = year;
mmonth = monthOfYear;
mday = dayOfMonth;
updateDisplay();

}
};
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}







Save the code and run.