Thursday, 2 January 2020

Java Exception Handling


Error is a serious problem caused during the runtime execution of a program. It cannot be handled and recovered. Errors cause the program to terminate. For example, System Crash or Out of Memory.

Exception is an error which can disrupt the normal execution flow of a program and may cause termination of the program.

During the normal execution of a program, whenever an error is occurred, an exception object is created at runtime, the execution of the normal flow is stopped, and JRE(Java Runtime Environment) finds a suitable handler for that exception. The exception object contains information like Type of Exception, Line number of statement along with Method call hierarchy, etc. The process of creating an exception object and passing it to the suitable handler is called throwing the exception.

Since the exception is an object in Java, it has a Parent Class as well i.e. Throwable. Throwable further has 2 child classes i.e. Error, and Exception.
Error is a scenario which cannot be handled and results in the prompt termination of the program. Whereas, an Exception is a scenario which only halts the normal execution flow and terminates the program only if the scenario is not handled.

Exception further be classified into Checked and Runtime Exception.
Checked Exception - These are the type of exception which are anticipated during the time of writing the code. Adding informative log messages can help in debugging this type of exception. These are also called Compile Time Exception. Before compilation, compiler verifies whether the exception has been handled or not. If not, then compilation error is thrown.
Runtime Exception - This type of exception cannot be anticipated. Checking the data before processing can avoid this type of exception. These are also called Unchecked Exception.


Keywords:

  • throws
    • When we are explicitly throwing an exception in a method and not handling it, we use "throws" keyword to let the calling method know that there might be an exception which needs to be handled. In this case, the caller method can also use throws keyword and not handle the exception and let its caller method know about the exception.
  • throw
    • When we want to explicitly throw an exception, "throw" keyword is used.
  • try - catch
    • try- catch is basically a block of code used to handle exception. The statements which are prone to exception are placed inside a try block and a handler for those exception(s) is written inside the catch block. The catch block expects an parameter, i.e. the Type of Exception. We can have a try-catch block inside another try-catch block and we can also have multiple catch blocks for a single try block to catch different exceptions.
  • finally
    • There is an optional block of code used with try-catch block in Java Exception Handling called the "finally" block. Since exceptions halt the normal flow of execution, there might be some code which needs to be executed e.g. closing the files or database connections, if opened, etc. Those blocks of code are written in finally block. This block of code gets executed irrespective of the occurrence of the exception.

Points to remember:
  • Catch and Finally blocks cannot be used without using Try block.
  • Try block must have a supporting Catch and/or Finally block.
  • Only one Finally block can be used with a Try-Catch block.
  • When using multiple catch blocks with a single try block, the exceptions must be ordered on the basis of most specific to general.
  • Finally block is not executed only if the program terminates abruptly(due to death of thread) or the program is explicitly terminated or there has been an exception in finally block as well.
  • In case of nested try-catch blocks, if the catch block does not handle the exception, then the catch block of the parent try block is inspected for that exception, and if a match is found then that catch block is executed. But in case the parent try block also does not handle the exception, then a system generated exception is shown same as what we see when we do not handle the exception.
  • Statements present in finally block execute even if control transfer statements like return, continue, and break are used in the try block.
  • Error and RuntimeException are collectively known as Unchecked Exception.

In addition to using the Java built-in classes, we can create your own exception(both Checked Exception and Runtime Exception) according to the needs of your project. We can create a user defined checked exception by extending Exception class and we can extend RuntimeException class to create a user defined Runtime Exception.

Wednesday, 1 January 2020

Java Interview Questions

  1. Run time and Compile time Polymorphism
  2. Overload Main Method
  3. Program Without Main Method
  4. Override Static Method
  5. Object Oriented Programming over Procedural Programming
  6. Abstract Classes VS Interfaces
  7. Clubbing Exceptions in Catch Block
  8. Try with Resources, Suppressed Exception, and Retrieving Suppressed Exception
  9. Possibility when Finally Block is Not Executed
  10. Exception Handling with Method Overriding
  11. Explain Struts framework
  12. Difference between request.getParameter() and request.getAttribute()
  13. Difference between REST and SOAP web service
  14. Difference between jsp:include and jsp:forward
  15. How to create a Servlet
  16. Brief about Collections hierarchy
  17. Difference between different collection classes
  18. Working of HashMap
  19. Difference between Git Rebase and Git Reset
  20. Brief about @Qualifier annotation in Spring
  21. Explain different REST methods
  22. Difference between Spring and SpringBoot
  23. Explain Spring framework workflow
  24. Explain SpringBoot framework workflow
  25. Brief about contract between equals() and hashCode()
  26. Useful methods in Java classes like Character, Arrays, String, Collections, Object
  27. Difference between Comparator and Comparable
  28. Difference between sleep, yield and wait methods
  29. Can we create volatile array
  30. Explain Cyclic Barrier in Multithreading
  31. Difference between Association, Composition and Aggregation
  32. What are different Application Context classes in Spring
  33. Which classes are available in Spring for Handshake
  34. Difference between Procedure and Function in PLSQL
  35. Can we implement an interface without using implements
  36. Brief about JSP and Servlet lifecycle
  37. Explain CSRF, XSS, Brute Force, Denial of Service and CORS
  38. Deep Copy vs Shallow Copy
  39. Brief about Exception handling and Runtime, and Compile time exception (Read here)
  40. Difference between webserver and appserver.

Sunday, 25 March 2018

OOPs Concepts

Although its actually OOP concepts, but the most widely used term is OOPs Concepts. Though OOP stands for Object Oriented Programming, but what what does "s" stands for? System. "s" in OOPs stands for Object Oriented Programming System.

Lets talk about OOP concepts, the basics of all Programming Languages available today.
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritence

Abstraction
Abstraction is the concept of hiding the internal processing from outside world. We can implement abstraction using encapsulation and inheritance.

Encapsulation
Encapsulation is a means to achieve Abstraction. it is used to restrict the scope and usage of class members and methods. Access modifiers such as public, private and protected are used to restrict access.

Polymorphism
Polymorphism is a concept in which an object can behave differently based on different situations.
Polymorphism can further be classified into 2 categories, i.e. Run time Polymorphism, and Compile time polymorphism.

Inheritance
Inheritance is a means to achieve code reusability. It allows the properties of another class to be used in another class in a Parent-Child model. The class using the properties of another class is called the Derived class and the class whose properties are used by another class are called Base Class or Parent Class. Inheritance in Java is achieved using keyword "extends".
Types of Inheritance(in Java): Single Inheritance, Multilevel Inheritance, and Hybrid Inheritance

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.




Friday, 6 February 2015

Android Broadcast Receiver

Hey, in this tutorial we will learn to implement Broadcast Receiver in your Android app. Broadcast Receivers are implemented to respond to the messages broadcasted by the system or by other applications.

First create a button which will trigger a broadcast from our application.

<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.broadcastreceiver.MainActivity" >

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Broadcast Intent"
        android:onClick="broadcastIntent"
        />

</RelativeLayout>



After creating the button make changes in the MainActivity.java file.

package com.codingredefined.broadcastreceiver;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @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);
    }
    
    //broadcast a custom intent
    public void broadcastIntent(View view)
    {
    Intent intent= new Intent();
    intent.setAction("com.codingredefined.CUSTOM_INTENT");
    sendBroadcast(intent);
    }
}



Following the changes done in the MainActivity file, then we need to create a new file MyReceiver.java which will respond to the broadcast messages.

package com.codingredefined.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Broadcast Received", Toast.LENGTH_LONG).show();
}

}


Now finally we need to register our broadcast receiver in the manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codingredefined.broadcastreceiver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="MyReceiver">
            <intent-filter>
                <action android:name="com.codingredefined.CUSTOM_INTENT"></action>
            </intent-filter>
        </receiver>
    </application>

</manifest>



Now the application is ready to run.


Tuesday, 3 February 2015

Android Background Service

Hey, in this tutorial I will demonstrate how to enable your application to continue working in the background without requiring any user interaction.

To start with, first of all create 2 buttons to start and stop the background service.

<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.codingreedefined.backgroundservice.MainActivity" >

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:onClick="startService"
    />
    
    <Button
        android:id="@+id/btnStopService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnStartService"
        android:text="Stop Service"
        android:onClick="stopService"
    />

</RelativeLayout>


After creating the buttons write functions to start and stop the background service in MainActivity file.

package com.codingreedefined.backgroundservice;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @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);
    }
    
    //Method to start the service
    public void startService(View view)
    {
    startService(new Intent(getBaseContext(), MyService.class));
    }
    
    //Method to start the service
    public void stopService(View view)
    {
    stopService(new Intent(getBaseContext(), MyService.class));
    }
    
}




Now create a new Java class named MyService and extend Service. Finally write the following code.

package com.codingreedefined.backgroundservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service 
{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//let it continue running until it is stopped
Toast.makeText(this, "Service Started!!!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped!!!", Toast.LENGTH_SHORT).show();
}
}


Finally add <service /> tag in the manifest file and run the application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.codingreedefined.backgroundservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />
    </application>
</manifest>


The following output shall be obtained.







Wednesday, 7 May 2014

Hide Source Code of Web Pages

<!DOCTYPE html>
<html>
<head>
<!-- Code to prevent use of Ctrl+U -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).on('keydown',function(e)
{
    var key = e.charCode || e.keyCode;
    if(key == 17 || key == 85)
        {
e.preventDefault();
}
});
</script>
</head>
<!-- Use oncontextmenu="return false" to disable right-click -->
<body oncontextmenu="return false">
<h2>Coding Redefined</h2>
</body>
</html>

Sunday, 5 January 2014

Android SQL Lite

Learn to use pre-installed SQL Lite in your Android phone.

Create the following layout to proceed with the example.

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

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Text" />

    <EditText 
        android:id="@+id/et"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:layout_below="@+id/tv1"
        android:hint="Enter Here"
        />
    
    <Button 
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/select"
        android:text="DELETE"
        />

    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/delete"
        android:layout_alignBottom="@+id/delete"
        android:layout_alignLeft="@+id/insert"
        android:text="UPDATE" />

    <Button
        android:id="@+id/select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="SELECT" />

    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/select"
        android:layout_toRightOf="@+id/select"
        android:text="INSERT" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/et" />
    
</RelativeLayout>




Now make changes in the activity file.

package com.codingredefined.androidsqlite;

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
EditText et;
TextView tv1,tv2;
Button select,insert,update,delete;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.et);
tv1=(TextView)findViewById(R.id.tv1);
tv2=(TextView)findViewById(R.id.tv2);
select=(Button)findViewById(R.id.select);
insert=(Button)findViewById(R.id.insert);
update=(Button)findViewById(R.id.update);
delete=(Button)findViewById(R.id.delete);
//Create DB
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
//Create Table(s)
final String create="CREATE TABLE TEST(daat TEXT);";
db.execSQL(create);
Toast.makeText(this,"Table Created Successfully",Toast.LENGTH_SHORT).show();
select.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
select(v);
}
});
insert.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
insert(v);
}
});
delete.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
delete(v);
}
});
update.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
update(v);
}
});
}

//function to display data
public void up()
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
tv2.setText("");
Cursor cr=db.query("TEST",null,null,null,null,null,null,null);
cr.moveToFirst();
while(cr.isAfterLast()==false)
{
tv2.append("\n"+cr.getString(0));
cr.moveToNext();
}
cr.close();
db.close();
}

public void select(View v)
{
up();
}

//function to insert
public void insert(View v)
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
ContentValues cv=new ContentValues();
cv.put("daat",et.getText().toString());
long a=db.insert("TEST",null,cv);
db.close();
if(a!=0)
{
Toast.makeText(this,"Insert",Toast.LENGTH_SHORT).show();
up();
}
else
{
Toast.makeText(this,"ERROR",Toast.LENGTH_SHORT).show();
}
}

//function to delete
public void delete(View v)
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.delete("TEST","daat=?",new String[]{et.getText().toString()});
db.close();
up();
}

//function to update
public void update(View v)
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
ContentValues cv=new ContentValues();
cv.put("daat",et.getText().toString());
db.update("TEST",cv,"daat=?",new String[]{et.getText().toString()});
db.close();
up();
}

@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;
}

}





The output will be




Video Tutorial