meljun cortes android sql lite example#2
TRANSCRIPT
Android SQLite Example by Nikos Maravitsas on May 25th, 2013 | Filed in: SQLiteDatabase
In this example we are going to see how yo interact with an SQLite database with your Android
Application. SQLite is an Open Source Database for structued data in relational databases. It is
embeded in Android, to you don’t have to do anything special to set up or administer an SQLite
server (e.g like in a Linux box). Android offers a really fast and conviniet API to work with SQLite
databases from applications. It uses a wrapper class, SQLiteOpenHelper which offers three basic
API methods to interact with the database:
onCreate(SQLiteDatabase db), called when the database is created for the first time.
onOpen(SQLiteDatabase db), called when the database has been opened.
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion), called when the
database needs to be upgraded.
to name a few.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
JDK 1.7
Eclipse 4.2 Juno
Android SKD 4.2
1. 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/android"
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 <requestFocus />
15 </EditText>
16
17 <Button
18 android:id="@+id/addBtn"
19 android:layout_width="wrap_content"
20 android:layout_height="wrap_content"
21 android:layout_below="@+id/editText1"
22 android:onClick="addUser"
23 android:text="Add New" />
24
25 <Button
26 android:id="@+id/deleteBtn"
27 android:layout_width="wrap_content"
28 android:layout_height="wrap_content"
29 android:layout_toRightOf="@+id/addBtn"
30 android:layout_below="@+id/editText1"
31 android:onClick="deleteFirstUser"
32 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
18 + "(" + STUDENT_ID + " integer primary key autoincrement, "
19 + STUDENT_NAME + " text not null);";
20
21 public DataBaseWrapper(Context context) {
22 super(context, DATABASE_NAME, null, DATABASE_VERSION);
23 }
24
25 @Override
26 public void onCreate(SQLiteDatabase db) {
27 db.execSQL(DATABASE_CREATE);
28
29 }
30
31 @Override
32 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
33 // you should do some logging in here
34 // ..
35
36 db.execSQL("DROP TABLE IF EXISTS " + STUDENTS);
37 onCreate(db);
38 }
39
40 }
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 return id;
10 }
11
12 public void setId(int id) {
13 this.id = id;
14 }
15
16 public String getName() {
17 return this.name;
18 }
19
20 public void setName(String name) {
21 this.name = name;
22 }
23
24 @Override
25 public String toString() {
26 return name;
27 }
28 }
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 private String[] STUDENT_TABLE_COLUMNS = { DataBaseWrapper.STUDENT_ID, DataBaseWrapper.STUDENT_NAME };
17 private SQLiteDatabase database;
18
19 public StudentOperations(Context context) {
20 dbHelper = new DataBaseWrapper(context);
21 }
22
23 public void open() throws SQLException {
24 database = dbHelper.getWritableDatabase();
25 }
26
27 public void close() {
28 dbHelper.close();
29 }
30
31 public Student addStudent(String name) {
32
33 ContentValues values = new ContentValues();
34
35 values.put(DataBaseWrapper.STUDENT_NAME, name);
36
37 long studId = database.insert(DataBaseWrapper.STUDENTS, null, values);
38
39 // now that the student is created return it ...
40 Cursor cursor = database.query(DataBaseWrapper.STUDENTS,
41 STUDENT_TABLE_COLUMNS, DataBaseWrapper.STUDENT_ID + " = "
42 + studId, null, null, null, null);
43
44 cursor.moveToFirst();
45
46 Student newComment = parseStudent(cursor);
47 cursor.close();
48 return newComment;
49 }
50
51 public void deleteStudent(Student comment) {
52 long id = comment.getId();
53 System.out.println("Comment deleted with id: " + id);
54 database.delete(DataBaseWrapper.STUDENTS,
DataBaseWrapper.STUDENT_ID
55 + " = " + id, null);
56 }
57
58 public List getAllStudents() {
59 List students = new ArrayList();
60
61 Cursor cursor = database.query(DataBaseWrapper.STUDENTS,
62 STUDENT_TABLE_COLUMNS, null, null, null, null, null);
63
64 cursor.moveToFirst();
65 while (!cursor.isAfterLast()) {
66 Student student = parseStudent(cursor);
67 students.add(student);
68 cursor.moveToNext();
69 }
70
71 cursor.close();
72 return students;
73 }
74
75 private Student parseStudent(Cursor cursor) {
76 Student student = new Student();
77 student.setId((cursor.getInt(0)));
78 student.setName(cursor.getString(1));
79 return student;
80 }
81 }
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 private StudentOperations studentDBoperation;
14
15 @Override
16 public void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.main);
19
20 studentDBoperation = new StudentOperations(this);
21 studentDBoperation.open();
22
23 List values = studentDBoperation.getAllStudents();
24
25 // Use the SimpleCursorAdapter to show the
26 // elements in a ListView
27 ArrayAdapter adapter = new ArrayAdapter(this,
28 android.R.layout.simple_list_item_1, values);
29 setListAdapter(adapter);
30 }
31
32 public void addUser(View view) {
33
34 ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
35
36 EditText text = (EditText) findViewById(R.id.editText1);
37 Student stud =
studentDBoperation.addStudent(text.getText().toString());
38
39 adapter.add(stud);
40
41 }
42
43 public void deleteFirstUser(View view) {
44
45 ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
46 Student stud = null;
47
48 if (getListAdapter().getCount() > 0) {
49 stud = (Student) getListAdapter().getItem(0);
50 studentDBoperation.deleteStudent(stud);
51 adapter.remove(stud);
52 }
53
54 }
55
56 @Override
57 protected void onResume() {
58 studentDBoperation.open();
59 super.onResume();
60 }
61
62 @Override
63 protected void onPause() {
64 studentDBoperation.close();
65 super.onPause();
66 }
67
68 }
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: