You are on page 1of 15

.

Create a new Android Project


Open Eclipse IDE and go to File -> New -> Project -> Android -> Android
Application Project. You have to specify the Application Name, the Project
Name and the Package name in the appropriate text fields and then click
Next.

In the next window make sure the Create activity option is selected in
order to create a new activity for your project, and click Next. This is
optional as you can create a new activity after creating the project, but
you can do it all in one step.

Select BlankActivity and click Next.

You will be asked to specify some information about the new activity. In
the Layout Name text field you have to specify the name of the file that
will contain the layout description of your app. In our case the
file res/layout/main.xml will be created. Then, click Finish.

2. Create the main layout of the Application


Open

res/layout/main.xml

file :

And paste the following code :


main.xml:
01 <?xml version="1.0" encoding="utf-8"?>
02 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/an
droid"
03
android:layout_width="match_parent"
04
android:layout_height="match_parent"
05
android:orientation="vertical" >
06
<EditText
07
android:id="@+id/editText1"
08
android:layout_width="wrap_content"
09
android:layout_height="wrap_content"
10
android:layout_alignParentLeft="true"
11
android:layout_alignParentTop="true"
12
android:ems="10" >
13
14
15
16
17
18

<requestFocus />
</EditText>
<Button
android:id="@+id/addBtn"

19
20
21
22
23
24
25
26
27
28
29
30
31
32

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:onClick="addUser"
android:text="Add New" />
<Button
android:id="@+id/deleteBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/addBtn"
android:layout_below="@+id/editText1"
android:onClick="deleteFirstUser"
android:text="Delete First" />

33
34
<ListView
35
android:id="@android:id/list"
36
android:layout_width="match_parent"
37
android:layout_height="wrap_content"
38
android:layout_alignParentLeft="true"
39
android:layout_below="@+id/deleteBtn" >
40
</ListView>
41
42 </RelativeLayout>

3. Create a custom

SQLiteOpenHelper

Now we have to write the code of the application. First we have to create
a custom SQLiteOpenHelper. We have to create a new class for that. Use the
Package Explorer to navigate to the Package of the source files:

Right click on the package

com.javacodegeeks.android.androidsqliteexample

and go

to New -> Class, fill out the form as in the picture below and press Finish:

Open the source file and paste the following code:


DataBaseWrapper.java:
01 package com.javacodegeeks.android.example.androidsqliteexample;
02
03 import android.content.Context;
04 import android.database.sqlite.SQLiteDatabase;
05 import android.database.sqlite.SQLiteOpenHelper;
06
07 public class DataBaseWrapper extends SQLiteOpenHelper {
08
09

public static final String STUDENTS = "Students";

10

public static final String STUDENT_ID = "_id";

11

public static final String STUDENT_NAME = "_name";

12
13

private static final String DATABASE_NAME = "Students.db";

14

private static final int DATABASE_VERSION = 1;

15
16

// creation SQLite statement

17

private static final String DATABASE_CREATE = "create table " +


STUDENTS

+ "(" + STUDENT_ID + " integer primary key


autoincrement, "
19
+ STUDENT_NAME + " text not null);";
20
18

21
22
23
24
25
26
27
28
29
30
31

public DataBaseWrapper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override

public void onUpgrade(SQLiteDatabase


db, int oldVersion, int newVersion) {
33
// you should do some logging in here
34
// ..
35
32

36
37
38
39
40 }

db.execSQL("DROP TABLE IF EXISTS " + STUDENTS);


onCreate(db);
}

4. Create a Student class.


So this class will represent a Student stored in a database:
Student.java
01 package com.javacodegeeks.android.example.androidsqliteexample;
02
03 public class Student {
04
05

private int id;

06

private String name;

07
08

public long getId() {

09
10
11

12
13
14

public void setId(int id) {


this.id = id;
}

return id;

15
16

public String getName() {

17
18
19

return this.name;

20
21
22
23
24
25

public void setName(String name) {


this.name = name;
}
@Override
public String toString() {

26
27
28 }

return name;
}

5. Create a

StudentOperations

class.

Basically this wrapper will describe and implement the specific database
operations (e.g. add, delete) on a Student object.
StudentOperations.java:
01 package com.javacodegeeks.android.example.androidsqliteexample;
02
03 import java.util.ArrayList;
04 import java.util.List;
05
06 import android.content.ContentValues;
07 import android.content.Context;
08 import android.database.Cursor;
09 import android.database.SQLException;
10 import android.database.sqlite.SQLiteDatabase;
11
12 public class StudentOperations {
13
14
// Database fields
15
private DataBaseWrapper dbHelper;
16
17

private String[] STUDENT_TABLE_COLUMNS =


{ DataBaseWrapper.STUDENT_ID, DataBaseWrapper.STUDENT_NAME };
private SQLiteDatabase database;

18
19

public StudentOperations(Context context) {

20
21
22

dbHelper = new DataBaseWrapper(context);

23
24
25
26

public void open() throws SQLException {


database = dbHelper.getWritableDatabase();
}

27

public void close() {

28
29
30

dbHelper.close();

31

public Student addStudent(String name) {

32
33

ContentValues values = new ContentValues();

34
35
36

values.put(DataBaseWrapper.STUDENT_NAME, name);

37

long studId =
database.insert(DataBaseWrapper.STUDENTS, null, values);

38
39
40
41

+ " = "

42
43
44
45
46
47
48
49
50

// now that the student is created return it ...


Cursor cursor = database.query(DataBaseWrapper.STUDENTS,
STUDENT_TABLE_COLUMNS, DataBaseWrapper.STUDENT_ID
+ studId, null, null, null, null);
cursor.moveToFirst();
Student newComment = parseStudent(cursor);
cursor.close();
return newComment;

51

public void deleteStudent(Student comment) {

52

long id = comment.getId();

53

System.out.println("Comment deleted with id: " + id);


database.delete(DataBaseWrapper.STUDENTS,
54
DataBaseWrapper.STUDENT_ID
55
+ " = " + id, null);
56
}
57
58

public List getAllStudents() {

59

List students = new ArrayList();

60
61
62
63
64
65
66
67
68
69
70
71
72
73

Cursor cursor = database.query(DataBaseWrapper.STUDENTS,


STUDENT_TABLE_COLUMNS, null, null, null, null, null)
;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Student student = parseStudent(cursor);
students.add(student);
cursor.moveToNext();
}
cursor.close();
return students;
}

74
75
76
77
78
79
80
81 }

private Student parseStudent(Cursor cursor) {


Student student = new Student();
student.setId((cursor.getInt(0)));
student.setName(cursor.getString(1));
return student;
}

6. Code the MainActivity


Open the source file of the main Activity and paste the following code:
MainActivity.java:
01 package com.javacodegeeks.android.example.androidsqliteexample;
02
03 import java.util.List;
04
05 import android.app.ListActivity;
06 import android.os.Bundle;
07 import android.view.View;
08 import android.widget.ArrayAdapter;
09 import android.widget.EditText;
10
11 public class MainActivity extends ListActivity {
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

private StudentOperations studentDBoperation;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
studentDBoperation = new StudentOperations(this);
studentDBoperation.open();
List values = studentDBoperation.getAllStudents();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
public void addUser(View view) {
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();

35
36

EditText text = (EditText) findViewById(R.id.editText1);


Student stud =
37
studentDBoperation.addStudent(text.getText().toString());
38
39
adapter.add(stud);
40
41
}
42
43

public void deleteFirstUser(View view) {

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 }

ArrayAdapter adapter = (ArrayAdapter) getListAdapter();


Student stud = null;
if (getListAdapter().getCount() > 0) {
stud = (Student) getListAdapter().getItem(0);
studentDBoperation.deleteStudent(stud);
adapter.remove(stud);
}
}
@Override
protected void onResume() {
studentDBoperation.open();
super.onResume();
}
@Override
protected void onPause() {
studentDBoperation.close();
super.onPause();
}

7. Run the Application


This is the main screen of our Application:

Now, when you want to add some Students:

And if you click Delete First:

Download Eclipse Project


This was an Android ExpandableListview Example. Download the Eclipse
Project of this tutorial: AndroidExpandableListeView.zip