Network Access in Android Applications

In all the earlier posts throughout this tutorial section, we’ve been dealing with standalone applications i.e. ones that require no network access. But with the ever growing Android market and competitive applications on the play store, there will be times when you will want to introduce some type of network functionality in your application.

In this post, I’m going to help you create an application that will have a very basic network access. We’ll be providing the application a website and we’ll be displaying the source code of that webpage. Of course, we’ll need internet access on the device we run this application on. As far as emulators are concerned, they derive their network access from your system’s internet connection. So fire up an activity and start coding. Complete Source Code is at the bottom.

  • The first thing we need to do is add a permission in the manifest file for internet access. It tells the Android system that the application requires an active internet connection and it will access the connection as and when required.
  • So open up the Manifest file and switch to the permissions tab. Add in the Android.permission.INTERNET permission from the drop down menu.
  • Next we need to setup the layout. We’re going to have a minimal layout consisting of an EditText, a TextView and a Button. We’ll be entering the website name in the EditText and the TextView will display the source when the button is clicked. We’ll span the TextView over the entire area left after placing the other elements.
  • Switch over to the MainActivity.java file and declare the elements appropriately. Remember to make them final variables.
  • We’ll now set up the onClickListener() method of the button. Inside the onClick() method, write the following lines.
    [java]
    try{
    URL url = null;
    url = new URL(et.getText().toString());
    URLConnection conn = url.openConnection();
    BufferedReader x= new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    while((line=x.readLine())!=null){
    tv.append(line);
    }
    }catch(Exception e){
    e.printStackTrace();
    }
    [/java]
  • Save the activity and launch it in an emulator or a device. Here’s what it looks like on my Gingerbread emulator.

networkinit network

Understanding the Code

  • A closer look at the code clearly shows that we are not using any new concepts but basic Java.
  • We create an object of the URL class of Java and pass it the string value from the EditText.
  • We then set up a URL Connection. The openConnection() method helps us in doing so.
  • We are also using the basic BufferedReader class that we use in basic java programs. This is to read the source code of the website and accept it as input.
  • The whole section has been enclosed in a try catch block because we are dealing with networking here and there are many things that can go wrong like link failure, unrecognized connection etc. We do not want our application to crash but to properly handle these exceptions.
  • Also remember that we are doing exactly what a web browser does while rendering a webpage. Then the question arises why are we only seeing the source code instead of the webpage as in a web browser. This is because web browsers are programmed to understand and render hypertext while out simple TextView is not. Thus we are only able to see the raw source code.

COMPLETE SOURCE CODE

activity_main.xml

MainActivity.java

[java]
package com.nero.myfirstapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et = (EditText) findViewById(R.id.editText1);
final Button b = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);

b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
try{
URL url = null;
url = new URL(et.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader x= new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=x.readLine())!=null){
tv.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
});
}

}

[/java]

Introducing Android Debug Bridge – Part II

In the part I of this post, I gave you a brief explanation of what ADB is and what is it used for. Although, ADB is a very effective tool and is used in numerous fields of Android Development, we are going to focus on only one which is, using ADB to query our Databases.
It is most likely that you have the previous application on your disk where we had created a database. If not, follow this post, and create one.

Now, to start off follow the steps:

  • Launch Command Prompt and navigate to the platform-tools directory inside your SDK directory. This is where adb.exe is located
  • Launch the ADB shell by typing:
    adb shell
  • Each line should now start with a “#”.
  • If you can recall, I have told you in my earlier posts that all databases of an application is located in
    data -> data -> <your application name> -> databases -> <databasename>.db
  • Navigate to the above location using the following command. Remember that we are not going inside the .db file now:
    cd data/data/<your application name>/databases
  • Now, in order to query the database, we need to execute SQLite queries. To do this, we need to start off the SQLite3 module of the ADB. Execute the following command:
    sqlite3 <databasename>.db
  • If your command is syntactically correct you should see something like this
    SQLite version 3.5.0
    Enter “.help” for instructions
  • Each line should now start with “sqlite>”.
  • List tables : In order to list all the tables present in the database, use the following command
    .table
  • Now, you can execute raw SQLite queries just like you would in an SQLite RDBMS, in order to verify what data the tables in your database hold.
  • Try the below query by substituting NeroTable with the name of your table.
    select * from NeroTable
  • The above query should present you with all the rows and columns present in the table in a formatted fashion.

This post assumes that you have a fair knowledge of SQLite queries and hence I suggest you try some of those out so that you  can have a hands on practice of working with command line tools. It is quite apparent that this gives us a direct access to our databases and we do not have to resort to logs in order to view the data inside the tables as we were doing earlier. Also it prevents writing extra lines of code in our activity.
While developing complex applications containing multiple tables, ADB serves our purposes beautifully and is hence preferred.

Introducing Android Debug Bridge – Part I

Any development work invariably involves the use of terminals. There are many who find the terminal much more fascinating than the GUI. This post is mainly targeted towards those. However, those who are not so much into command user interface, also need to take a look.

ADB exapanded as Android Debug Bridge is a versatile command line tool. It lets your system interact directly with an Emulator instance’s or a tethered Android device’s file system. Remember that this can be done on the device or the emulator itself using a terminal emulator, but writing and executing commands on the device becomes quite a task.
ADB comes with the Android SDK and no separate installation is required. It is located in <your android sdk> -> platform-tools -> adb.exe.

To get started with ADB we need to launch it first. Below instructions are for Windows Users.

  • Open up Run on Windows by pressing Windows+R.
  • Type in cmd to launch the Command Prompt.
  • Now navigate to your Android SDK directory using the cd command. For instance, my SDK is located in G:\Android Development\
    So I type in:

    G:
    cd Android Development
  • Furthermore, in order to navigate to platform-tools I type in:
    cd sdk/platform-tools
  • Type in the below command:
    adb
  • The above command gives a detailed summary of the components present in the ADB. It’s quite a read so you can spare some time to have a look.
  • Now type in the following command:
    adb shell
  • You are now inside the ADB shell. Here you can type and execute ADB commands. Start an emulator and after it has successfully started, execute the below command:
    adb devices
  • This shows the list of all running emulators and tethered Android devices. Remember that in some cases you might need to turn on USB Debugging in your Android device for it to be recognized by the ADB.
  • You can practically control your device from this terminal.

Now that you have a fair idea of what ADB is and what it is used for, it is time you try out some commands on your own. You can start off by reading the official Android Documentation for ADB here.

The post should act as a precursor to what we are going to do next, which is to use ADB shell for SQLite queries on our Application databases. In the part II of this post I will show you how we can stop relying on logs to see the data in our application’s database and make use of ADB shell instead, to do this in a simpler and effective manner.

Path Finding

Given an undirected,unweighted graph and two vertices u and v,the task is to find the path between these two vertices.u can be considered as the source vertex and v as the destination vertex.

Example-

Number of vertices-5
Number of edges-4
Given vertices are 2 and 4.
Edges-
1 2
1 3
3 4
4 5
The path between 2 and 4 is 2->1->3->4.

Algorithm-

1.DFS is called on vertex u.
2.A stack S is kept to keep track of the path between the source vertex and the current vertex.
3.As soon as destination vertex v is encountered,we return the path as the contents of the stack.

Code-

[cpp]

#include<stdio.h>
#include<vector>
#include<stack>
using namespace std;

vector<int>arr[10005];
int n,a,b,j=0,m;
int color[100005];
int u,v;
stack<int> path;

void dfs(int node)
{

//printing the vertices of the path
printf("%d->",node+1);

//until final vertex is reached
if(node!=v-1)
{

color[node]=2;//marking the visited nodes

for(int i=0;i<arr[node].size();++i)
{

if(color[arr[node][i]]==0)
{
dfs(arr[node][i]);
}
}
}
}

int main()
{
int t,p;
int i;
p=1;
j=0;

// n is the number of vertices
// m is the number of edges

scanf("%d %d",&n,&m);

// u is the source vertex
// v is the destination vertex

scanf("%d %d",&u,&v);

//clearing the arrays and vectors

for(i=0;i<n;i++)
arr[i].clear();

for(i=0;i<n;++i){
color[i]=0;
}

while(j<m)
{

//a and b denote the starting and ending points of the edge

scanf("%d %d",&a,&b);

//maintaining the adjacency lists

arr[a-1].push_back(b-1);
arr[b-1].push_back(a-1);
j++;

}

//calling dfs on source vertex

dfs(u-1);

return 0;
}

[/cpp]

Databases in Android using SQLite – Part III

Till now, we have restricted ourselves to very simple databases and hence we declare and define the database inside the Main Activity itself. However, this is mostly not the case. Often times in your application you would want to keep your Database and related functions separately from you activity. This is a much better idea because then your activity will consist of all related components and your database class will have all the methods related to creation, access or updation of the database.

In this post I will show you how to keep two classes, one for the Activity and another for your Database related operations. So create a project and follow along. Complete Source code is at the bottom.

  • Create a new Java Class, the super class of which is SQLiteOpenHelper. Name this DatabaseHelper.java
  • Once this is created, you can see that there are two methods that are already present, onCreate() and onUpgrade().
  • Create a class variable named DatabaseName of the type String and assign it a value “NeroDB or anything you like. This will be the name of your Database.
  • We will need to create a constructor for this Class, so write down the following lines just before onCreate() method
    [java]
    public DatabaseHelper(Context context) {
    super(context, DatabaseName, null, 1);
    }
    [/java]
  • Here we are calling the constructor of the Super Class and passing to it the Context, name of the database, CursorFactory(which is null here) and the version of our Database.
  • Now write the following lines in the onCreate(SQLiteDatabase db) method
    [java]
    db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
    [/java]
  • Again, write the following line in the onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) method
    [java]
    db.execSQL("DROP TABLE NeroTable;");
    db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
    [/java]
  • We have just told Android that when the database is created, create a table named NeroTable with the specified columns and if there is an upgrade in the version of the Database, drop the table and create it again leading to deletion of all data.
  • Now to insert values in the table, write the following method after the onUpgrade()

    [java]
    public void InsertValues()
    {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast1’, ‘NeroFirst1’, 20);");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast2’, ‘NeroFirst2’, 21);");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast3’, ‘NeroFirst3’, 22);");
    db.close();
    }
    [/java]
  • Now that we are done with the DatabaseHelper class, switch over to the Main activity and create an object of the DatabaseHelper class. Remember to declare it outside all methods and inside the class.
    [java]
    DatabaseHelper db;
    [/java]
  • Define this inside the onCreate() method of the Main activity.
    [java]
    db = new DatabaseHelper(this);
    [/java]
  • By creating the object and defining it, the constructor of the DatabaseHelper class has been called and hence the Database and the table has been created.
  • Now to insert the values,
    [java]
    db.InsertValues();
    [/java]
  • Remember that we are only using the basic OOP Concepts here of calling a class’s constructor and using the object of that class to call it’s methods.
  • Save your work and execute it on the emulator.

Understanding the Code

  • The onCreate() and the onUpgrade() methods are quite clear.
  • The constructor of the Super method passes the Database Version too. If this Database version is to be changed, the onUpgrade() method comes into play and the table is deleted and recreated. You can try it out by changing the value to a different number.

COMPLETE SOURCE CODE

DatabaseHelper.java

[java]
package com.nero.myfirstapp;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

static String DatabaseName="NeroDB";

public DatabaseHelper(Context context) {
super(context, DatabaseName, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE NeroTable;");
db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
}

public void InsertValues()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast1’, ‘NeroFirst1’, 20);");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast2’, ‘NeroFirst2’, 21);");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast3’, ‘NeroFirst3’, 22);");
db.close();
}
}

[/java]

Main.java

[java]
package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
db.InsertValues();
db.close();
}
}

[/java]

Longest path in a tree

Given an unweighted and undirected tree,the task is to find the length of the longest path (from one node to another) in that tree.The length of a path in this case is number of edges we traverse from source to destination.

Example-

Number of nodes=3
Number of edges=2
Edges-
1 2
2 3

Output-
2
(1->2->3 is the longest path in the given tree which has a length of 2 units).

Algorithm-

1.Loop through the vertices, starting a new depth first search whenever the loop reaches a vertex that has not already been included in previous DFS calls.
2.A dist[] array is constructed to record the distances of all the vertices from the starting vertex ie. vertex on which DFS is called.
3.Maximum of all the values of the dist[] array is found and the respective vertex number is found.Let it be v.
4.Now,DFS is called on v and dist[] array records the distances of all the vertices from the vertex v.
5.Maximum of all the values of the dist[] array is the final answer that is it is the length of the longest path in the tree.

Code-

[cpp]

#include<stdio.h>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;

vector<int>arr[10005];

int n,a,b,j=0,m;

int color[10005],dist[10005];

//d denotes the distance of the node on which DFS is called from the starting vertex.
void dfs(int node,int d)
{
color[node]=2;
//marking the visited vertices

dist[node]=d;

for(int i=0;i<arr[node].size();++i)
{

if(color[arr[node][i]]==0)
{
dfs(arr[node][i],d+1);
}
}
}

int main()
{
int p;

int i1;
p=1;j=0;

//n is the number of vertices
scanf("%d",&n);

for(i=0;i<n;i++)
arr[i].clear();
for(i=0;i<n;++i)
{
color[i]=0;dist[i]=0;
}

//tree has n-1 edges

while(j<n-1)
{
scanf("%d %d",&a,&b);
//a and b denote the starting and ending vertices of an edge

arr[a-1].push_back(b-1);
arr[b-1].push_back(a-1);
j++;
}
for(i=0;i<n;++i)
{
if(color[i]==0)
dfs(i,0);
}

int max=0;

// p denotes the vertex with maximum distance

for(i=0;i<n;i++)
{
if(dist[i]>=max)

{ max=dist[i];
p=i;
}
}
//resetting the arrays to call DFS again

for(i=0;i<n;++i)
{
color[i]=0;dist[i]=0;
}

//calling dfs on vertex which has max distance

dfs(p,0);
max=0;
for(i=0;i<n;i++)
{
if(dist[i]>=max)

{ max=dist[i];
p=i;
}
}

cout<<max<<endl;

return 0;

}

[/cpp]

Applications of DFS

One of the applications of DFS is to find the number of connected components in a graph.In graph theory, a connected component of an undirected graph is a sub-graph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the super-graph.

Algorithm-

A depth first search that begins at some particular vertex v will find the entire connected component containing v (and no more) before returning.To find all the connected components of a graph, loop through its vertices, starting a new depth first search whenever the loop reaches a vertex that has not already been included in a previously found connected component.

Another application is to find if the given graph is a tree or not.A tree is an undirected graph which is connected and does not have cycles.

Properties of a tree-

1.The tree should have only one connected component ie. it is not a disconnected graph.
2.If the graph has N vertices and N-1 edges,then it is a tree.This condition ensures that no cycles are formed.

Algorithm-

For a graph to be a tree,both the above conditions must be satisfied.Number of components is found using the above algorithm and it should be 1.Then,the second relation must be verified.

Code-

[cpp]

#include<stdio.h>
#include<vector>
using namespace std;

vector<int>arr[10005];
int n,a,b,j=0,m;
int color[100005];

//counter counts the number of components

int counter;

void dfs(int node)
{
color[node]=2;//marking the visited nodes

for(int i=0;i<arr[node].size();++i)
{

if(color[arr[node][i]]==0)
{
dfs(arr[node][i]);
}
}
}

int main()
{
int t,p;
int i;
counter=0;
p=1;
j=0;

// n is the number of vertices
// m is the number of edges

scanf("%d %d",&n,&m);

//clearing the arrays and vectors

for(i=0;i<n;i++)
arr[i].clear();

for(i=0;i<n;++i){
color[i]=0;
}

while(j<m){

//a and b denote the starting and ending points of the edge

scanf("%d %d",&a,&b);

//maintaining the adjacency lists

arr[a-1].push_back(b-1);
arr[b-1].push_back(a-1);
j++;

}
//looping through the vertices

for(i=0;i<n;++i)
{
if(color[i]==0)
{
dfs(i);
counter++;
}
}

printf("Number of components is %d\n",counter);

if((m==n-1)&&(counter==1))printf("IT IS A TREE\n");

else printf("NOT A TREE\n");

return 0;
}
[/cpp]

Databases in Android using SQLite – Part II

In the last post I showed you how to create a database. We created a table inside it and inserted values. Although we could make sure that our database was successfully created, we had no way to confirm the same about our tables. In this post I’ll show you how to access the data from a database.

So create an activity and follow along. Complete Source Code is at the bottom

  • Set the Content View of the activity. Do not put any elements in the layout.
  • Switch over to the java file and write the below lines after the setContentView() method.
    [java]
    SQLiteDatabase db = openOrCreateDatabase("NeroDB", MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast1’, ‘NeroFirst1’, 20);");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast2’, ‘NeroFirst2’, 21);");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast3’, ‘NeroFirst3’, 22);");
    [/java]
  • Since, this post assumes that you have a fair idea of SQLite, you can change the name of the Database, table and the values inside the table to whatever you wish.
  • Now, we will access the data from our database. Notice that we have not yet closed the database, this being the reason.
  • Write the code below. I strongly recommend not to paste these lines, but to write them using the Auto-Complete feature of Eclipse editor. That way, in the suggestion, you can see the method signatures and it will help you understand what we are doing and also change a few values to your liking.
    [java]
    Cursor c = db.rawQuery("SELECT * FROM NeroTable;", null);
    while(c.moveToNext()){
    Log.v("NeroLog", c.getString(c.getColumnIndex("FirstName")));
    }
    [/java]
  • Now, we will drop the Table and delete the database. We are doing this because if we do not, every time we run the application, the three rows will be inserted into the table. You can choose to let it be and not drop the table and the database. In case you do want to, write the below lines.
    [java]
    db.execSQL("DROP TABLE NeroTable;");
    this.deleteDatabase("NeroDB.db");
    [/java]
  • Remember to close the database irrespective of whether or not you did the above step.
    [java]
    db.close();
    [/java]
  • Now execute the application in an emulator.
  • Once it runs successfully, switch over to the DDMS section. If you wrote the exact lines as I have you will find Logs with the tag NeroLog and the values as the first name column values in the database. This is how you make sure that your table has been created and the values have been inserted.

Db2

Understanding the Code

  • Cursor :- Cursor is analogous to a pointer in most programming languages, It points to the beginning of the set of rows returned from a query.
  • rawQuery(String SQL, String [] SelectionArgs) :- This method returns a Cursor and is similar to execSQL(). It provides a way to provide selection arguments to an SQL query. I will talk about selection arguments in a later post.
  • moveToNext() :- Since a cursor points to the beginning of rows, this function provides a way to sequentially access each row.
  • Log.v :- Verbose Log. Creates a Log with the provided tag and message in the DDMS LogCat.
  • getColumnIndex :- This is a way to access the column by name of the row currently pointed to by Cursor.
  • deleteDatabase() :- This method is used to delete the database.

COMPLETE SOURCE CODE

[java]
package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

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

SQLiteDatabase db = openOrCreateDatabase("NeroDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast1’, ‘NeroFirst1’, 20);");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast2’, ‘NeroFirst2’, 21);");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast3’, ‘NeroFirst3’, 22);");
Cursor c = db.rawQuery("SELECT * FROM NeroTable;", null);
while(c.moveToNext()){
Log.v("NeroLog", c.getString(c.getColumnIndex("FirstName")));
}
db.execSQL("DROP TABLE NeroTable;");
this.deleteDatabase("NeroDB.db");
db.close();
}
}
[/java]

Databases in Android using SQLite – Part I

In this post I will show you how to integrate SQLite and Java in your Android Application. If you do not have a fair idea of SQLite, I would suggest you to take a look at my previous post and follow the instructions.

Create an Activity and start programming. Complete Source Code is at the bottom.

  • Set the Content View of the activity. Do not put any elements in the layout.
  • Switch over to the java file and write the below lines after the setContentView() method.
    [java]
    SQLiteDatabase db = openOrCreateDatabase("NeroDB", MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast1’, ‘NeroFirst1’, 20);");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast2’, ‘NeroFirst2’, 21);");
    db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast3’, ‘NeroFirst3’, 22);");
    db.close();
    [/java]
  • Since, this post assumes that you have a fair idea of SQLite, you can change the name of the Database, table and the values inside the table to whatever you wish.
  • Save your activity and execute it on the emulator.
  • It is apparent that you have no way of knowing whether the database and the table were successfully created and whether the values were inserted into it.
  • This is where DDMS comes into play. Switch over to the DDMS section and you should see the File Explorer section just above the LogCat and Console. This is an explorer for the files in the SD card of the emulator. Remember that the emulator must be running in order for you to browse the files.
  • Navigate to data/data/<yourapplicationname>/databases. Here you should see a database file with the name of the database. If it is there, your database was successfully created. If not, something went wrong and you should check your code.

Db1

  • Remember that your application may encounter exceptions that require you to Force Close you application. In such cases refer to the LogCat in the DDMS and it should point you exactly to what exception was encountered. Also, you should know that since the exception may be encountered in on of the SQL queries, your Database and the table might have been successfully created and the exception occured thereafter.

Understanding the Code

  • SQLite Database db :- This is an instance of SQLite Database that we are creating.
  • openOrCreateDatabase(String Name, int mode, CursorFactory Factory) :- This functions opens the database if there exists a database by the name provided. If not, it creates one and opens it. Mode is provided in order to let the system know the accessibility of the database. By MODE_PRIVATE, we tell the system that this database is private to our application. CursorFactory is beyond the scope of this post. We do not need to use it and hence it is provided a value of null.
  • execSQL() :- This function allows us to write the SQL query as a string and execute it. Remember that there are other ways to write queries in which pure SQL will not be used.
  • close() :- This function closes the database. Recall that we had used the openOrCreateDatabase to open the database. Closing the database is essential to prevent leak.

COMPLETE SOURCE CODE

Main.java

[java]
package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

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

SQLiteDatabase db = openOrCreateDatabase("NeroDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS NeroTable(LastName VARCHAR, FirstName VARCHAR, Age INT(3));");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast1’, ‘NeroFirst1’, 20);");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast2’, ‘NeroFirst2’, 21);");
db.execSQL("INSERT INTO NeroTable VALUES(‘NeroLast3’, ‘NeroFirst3’, 22);");
db.close();
}
}

[/java]

Android development: Introducing SQLite

As you start to develop complex applications containing multiple activities and providing multiple functionality, often times you would want to store structured data in your application. Android provides a mechanism to do this using Databases.
The SQL that is used with Android system is SQLite. Just like MySQL is used with PHP and Microsoft SQL Server with ASP.NET, SQLite is used with Android System.

  • SQLite is an open source database that supports standard relational database features like SQL syntax and transactions.
  • SQLite supports a variety of data types like Text, Integer, Real etc. Text is similar to Strings in most Programming Languages.
  • SQLite is embedded in every Android device eliminating the need for any setup procedure.
  • All one needs to do in order to work with SQLite databse is to write SQL queries to create and update the database.
  • All the Databases contained within your application will be saved in the directory DATA/data/<yourappname>/databases/filename.

This tutorial series is concerned with Android Application Development and although databases are a major sections  I will not be concentrating on SQLite but on integrating SQLite with Android. Nevertheless, there are some very good tutorials on the internet that can come in handy while learning SQLite. Below are a few :-

For the scope of this tutorial series, a fair knowledge of SQLite should be enough. Further posts will assume the following :-

  • You have a fair idea of SQLite and it’s working.
  • You can write well formed SQL queries.
  • You have a fair idea of the how the values are returned for the queries.

In the next post I’ll show you how to integrate SQLite and Java for the purpose of Android Development.
Happy learning SQLite.