Anda di halaman 1dari 43

Gii thiu v SQLite trong android v cng c SQLite Manager (phn 1).

Gii thiu v SQLite trong android

Bt k mt ng dng no d ln hay nh chng ta hu nh u phi s dng c s


d liu. cc bi trc ti gii thiu cho cc bn cch lu tr gi liu bng
text, XML hay SharePreference. bi ny ti s gii thiu cho cc bn mt cch
lu tr d liu rt thng dng v tin li c android h tr sn l SQLite.
u im ca SQLite l c th lu tr mi d liu ln nh v d liu c th c
x l mt cch linh hot. Khi s dng SQLite cc bn c th to c s d liu trc
tip trong code nhng vic lm ny kh tn thi gian, hm nay ti s gii thiu cho
bn mt cng c h tr to c s d liu rt nhanh v d s dng l SQLite
Manager c tch hp trn trnh duyt.

Gii thiu cng c SQLite Manager

Vi cng c SQLite Manager, cc bn c th thit k c s d liu nh vic thit


k trn mysql. Sau y ti s hng dn cc bn tch hp SQLite Manager trn
firefox.

Bc 1: cc bn m trnh duyt firefox, sau m menu v chn tin ch.


Sqlite

Bc 2: Ca s tin ch hin ra, cc bn g vo tm kim SQLite Manager, chn


Tin ch c th ci thm ri tm kim. Cc bn chn SQLite Manager ri n ci t.
Sqlite

Bc 3: Sau khi ci xong cc bn chn khi ng li firefox cp nht tin ch.

Sqlite

Bc 4: Cc bn chn tin ch ca ti s thy SQLite Manager c ci t.


Bc 5: Cc bn m SQLite Manager bng cch kch vo thanh cng c trn thanh
menu ca trnh duyt v chn SQLite Manager.

Bc 6: Mn hnh lm vic ca SQLite Manager.


Sau y ti s hng dn cc bn to mt c s d liu n gin lu tr thng tin
sinh vin.

Bng SinhVien: Gm ID (t tng), h tn (TEXT), m sinh vin (TEXT), m lp


(TEXT), a ch (TEXT).

Bng LopHoc: Gm ID (t tng), tn lp (TEXT), m lp (TEXT), s s


(INTEGER).

Mt lp hc c th cha nhiu sinh vin v mt sinh vin c th trong nhiu lp.

Cc bn to mt c s d liu mi c tn quanlisinhvien.
Cc bn lu file database va to.

Sau khi to c s d liu, cc bn to cc bng SinhVien v LopHoc.


Nh vy l cc bn c mt c s d liu quanlisinhvien, cc bn c thm d
liu cho cc bng.
Sau khi c d liu ti s hng dn cc bn s dng d liu hin th trn
android.

Hng dn s dng c s d liu to t SQLite Manager trong android

Cc bn to mt project mi c tn l demoSQLite.

Cc bn to mt th mc Asset nh hng dn bn di cha file database


chng ta to bng SQLite Manager.
By gi cc bn to mt class SQLiteDataController kt ni ti database v truy
xut database. Cc bn ch phn namedatabase chnh l tn database ca mnh.

package com.example.devpro.d

import android.content.Context;
import android.database.SQLEx

1 package com.example.devpro.demosqlite;
2
3 import android.content.Context;
4 import android.database.SQLException;
5 import android.database.sqlite.SQLiteDatabase;
6 import android.database.sqlite.SQLiteOpenHelper;
7
8 import java.io.File;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13
14 /**
15 * DevPro Viet Nam
16 */
17 public class SQLiteDataController extends SQLiteOpenHelper {
18
19
20 public String DB_PATH = "//data//data//%s//databases//";
21 // ng dn ni cha database
22 private static String DB_NAME = "databasename";
23 public SQLiteDatabase database;
24 private final Context mContext;
25
26 public SQLiteDataController(Context con) {
27 super(con, DB_NAME, null, 1);
28 DB_PATH = String.format(DB_PATH, con.getPackageName());
29 this.mContext = con;
30 }
31
32 /**
33 * copy database from assets to the device if not existed
34 *
35 * @return true if not exist and create database success
36 * @throws IOException
37 */
38 public boolean isCreatedDatabase() throws IOException {
39 // Default l c DB
40 boolean result = true;
41 // Nu cha tn ti DB th copy t Asses vo Data
42 if (!checkExistDataBase()) {
43 this.getReadableDatabase();
44 try {
45 copyDataBase();
46 result = false;
47 } catch (Exception e) {
48 throw new Error("Error copying database");
49 }
50 }
51
52 return result;
53 }
54
55 /**
56 * check whether database exist on the device?
57 *
58 * @return true if existed
59 */
60 private boolean checkExistDataBase() {
61
62 try {
63 String myPath = DB_PATH + DB_NAME;
64 File fileDB = new File(myPath);
65
66 if (fileDB.exists()) {
67 return true;
68 } else
69 return false;
70 } catch (Exception e) {
71 return false;
72 }
73 }
74
75 /**
76 * copy database from assets folder to the device
77 *
78 * @throws IOException
79 */
80 private void copyDataBase() throws IOException {
81 InputStream myInput = mContext.getAssets().open(DB_NAME);
82 OutputStream myOutput = new FileOutputStream(DB_PATH +
83 DB_NAME);
84 byte[] buffer = new byte[1024];
85 int length;
86 while ((length = myInput.read(buffer)) > 0) {
87 myOutput.write(buffer, 0, length);
88 }
89
90 myOutput.flush();
91 myOutput.close();
92 myInput.close();
93 }
94
95 /**
96 * delete database file
97 *
98 * @return
99 */
100 public boolean deleteDatabase() {
101 File file = new File(DB_PATH + DB_NAME);
102 if (file != null && file.exists()) {
103 return file.delete();
104 }
105 return false;
106 }
107
108 /**
109 * open database
110 *
111 * @throws SQLException
112 */
113 public void openDataBase() throws SQLException {
114 database = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME,
115 null,
116 SQLiteDatabase.OPEN_READWRITE);
117 }
118
119 @Override
120 public synchronized void close() {
121 if (database != null)
122 database.close();
123 super.close();
124 }
125
126 @Override
127 public void onCreate(SQLiteDatabase db) {
128 // do nothing
129 }
130
131 @Override
132 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
133 {
134 // do nothing
135 }
136
137 public int deleteData_From_Table(String tbName) {
138
139 int result = 0;
140 try {
141 openDataBase();
142 database.beginTransaction();
143 result = database.delete(tbName, null, null);
144 if (result >= 0) {
145 database.setTransactionSuccessful();
146 }
147 } catch (Exception e) {
148 database.endTransaction();
149 close();
150 } finally {
151 database.endTransaction();
152 close();
153 }
154
155 return result;
156 }
157

}
By gi ti thit k mt layout n gin hin th d liu trong database ln: gm
2 button v 2 textview, khi click vo button th thng tin sinh vin hay lp hc
c hin th.

<?xml version="1.0" encoding="


<LinearLayout xmlns:android="h
xmlns:app="http://schemas.a
xmlns:tools="http://schemas.a

1 <?xml version="1.0" encoding="utf-8"?>


2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 xmlns:tools="http://schemas.android.com/tools"
5 android:layout_width="match_parent"
6 android:layout_height="match_parent"
7 android:orientation="vertical"
8 android:paddingBottom="@dimen/activity_vertical_margin"
9 android:paddingLeft="@dimen/activity_horizontal_margin"
10 android:paddingRight="@dimen/activity_horizontal_margin"
11 android:paddingTop="@dimen/activity_vertical_margin"
12 app:layout_behavior="@string/appbar_scrolling_view_behavior"
13 tools:context=".MainActivity"
14 tools:showIn="@layout/activity_main">
15
16 <Button
17 android:id="@+id/btnShowHS"
18 android:layout_width="wrap_content"
19 android:layout_height="wrap_content"
20 android:text="show" />
21
22 <TextView
23 android:id="@+id/txtShowHS"
24 android:layout_width="wrap_content"
25 android:layout_height="wrap_content"
26 android:layout_marginTop="20dp"
27 android:hint="Thng tin hc sinh" />
28
29 <Button
30 android:id="@+id/btnShowLH"
31 android:layout_width="wrap_content"
32 android:layout_height="wrap_content"
33 android:layout_marginTop="20dp"
34 android:text="show" />
35
36 <TextView
37 android:id="@+id/txtShowLH"
38 android:layout_width="wrap_content"
39 android:layout_height="wrap_content"
40 android:layout_marginTop="20dp"
41 android:hint="Thng tin lp hc" />
42
43
44 </LinearLayout>

Sau khi thit k layout cc bn to 2 class thc th l SinhVien v LopHoc cha


cc thuc tnh m bn database cc bn thit k.

package com.example.devpro.d

/**
* Created by Devpro on 2/22/20

1 package com.example.devpro.demosqlite;
2
3 /**
4 * Created by Devpro on 2/22/2016.
5 */
6 public class SinhVien {
7 private int ID;
8 private String hoTen;
9 private String maSv;
10 private String maLop;
11 private String diaChi;
12
13 public SinhVien() {
14 }
15
16 public SinhVien(int ID, String hoTen, String maSv, String maLop, String
17 diaChi) {
18
19 this.ID = ID;
20 this.hoTen = hoTen;
21 this.maSv = maSv;
22 this.maLop = maLop;
23 this.diaChi = diaChi;
24 }
25
26 public int getID() {
27
28 return ID;
29 }
30
31 public void setID(int ID) {
32 this.ID = ID;
33 }
34
35 public String getHoTen() {
36 return hoTen;
37 }
38
39 public void setHoTen(String hoTen) {
40 this.hoTen = hoTen;
41 }
42
43 public String getMaSv() {
44 return maSv;
45 }
46
47 public void setMaSv(String maSv) {
48 this.maSv = maSv;
49 }
50
51 public String getMaLop() {
52 return maLop;
53 }
54
55 public void setMaLop(String maLop) {
56 this.maLop = maLop;
57 }
58
59 public String getDiaChi() {
60 return diaChi;
61 }
62
63 public void setDiaChi(String diaChi) {
64 this.diaChi = diaChi;
65 }
}

package com.example.devpro.d

/**
* Created by Devpro on 2/22/20

1 package com.example.devpro.demosqlite;
2
3 /**
4 * Created by Devpro on 2/22/2016.
5 */
6 public class LopHoc {
7 private int ID;
8 private String maLop;
9 private String tenLop;
10 private int siSo;
11
12 public LopHoc() {
13 }
14
15 public LopHoc(int ID, String maLop, String tenLop, int siSo) {
16
17 this.ID = ID;
18 this.maLop = maLop;
19 this.tenLop = tenLop;
20 this.siSo = siSo;
21 }
22
23 public int getID() {
24
25 return ID;
26 }
27
28 public void setID(int ID) {
29 this.ID = ID;
30 }
31
32 public String getMaLop() {
33 return maLop;
34 }
35
36 public void setMaLop(String maLop) {
37 this.maLop = maLop;
38 }
39
40 public String getTenLop() {
41 return tenLop;
42 }
43
44 public void setTenLop(String tenLop) {
45 this.tenLop = tenLop;
46 }
47
48 public int getSiSo() {
49 return siSo;
50 }
51
52 public void setSiSo(int siSo) {
53 this.siSo = siSo;
54 }
55 }

By gi ti s vit hm ly d liu t database, cc bn to 2 class SQLiteLopHoc


v SQLiteSinhVien nh sau.

package com.example.devpro.d

import android.content.ContentV
import android.content.Context;
1 package com.example.devpro.demosqlite;
2
3 import android.content.ContentValues;
4 import android.content.Context;
5 import android.database.Cursor;
6 import android.database.SQLException;
7
8 import java.util.ArrayList;
9
10 /**
11 * Created by Devpro on 2/22/2016.
12 */
13 public class SQLiteLopHoc extends SQLiteDataController {
14 public SQLiteLopHoc(Context con) {
15 super(con);
16 }
17
18 public ArrayList<LopHoc> getListLopHoc() {
19 ArrayList<LopHoc> listLopHoc = new ArrayList<>();
20 // mo ket noi
21 try {
22 openDataBase();
23 Cursor cs = database.rawQuery("select id, malop,tenlop,siso from
24 lophoc", null);
25 LopHoc lopHoc;
26 while (cs.moveToNext()) {
27 lopHoc = new LopHoc(cs.getInt(0), cs.getString(1), cs.getString(2),
28 cs.getInt(3));
29 listLopHoc.add(lopHoc);
30 }
31 } catch (SQLException e) {
32 e.printStackTrace();
33 } finally {
34 close();
35 }
36
37 return listLopHoc;
38 }
39
40 public boolean insertLopHoc(LopHoc lopHoc) {
41 boolean result = false;
42 try {
43
44 openDataBase();
45 ContentValues values = new ContentValues();
46 values.put("malop", lopHoc.getMaLop());
47 values.put("tenlop", lopHoc.getTenLop());
48 values.put("siso", lopHoc.getSiSo());
49 long rs = database.insert("lophoc", null, values);
50 if (rs > 0) {
51 result = true;
52 }
53 } catch (SQLException e) {
54 e.printStackTrace();
55 } finally {
56 close();
57 }
58 return result;
59 }
60
61 public boolean updateLopHoc(LopHoc lopHoc) {
62 boolean result = false;
63 try {
64
65 openDataBase();
66 ContentValues values = new ContentValues();
67 values.put("malop", lopHoc.getMaLop());
68 values.put("tenlop", lopHoc.getTenLop());
69 values.put("siso", lopHoc.getSiSo());
70 int rs = database.update("lophoc", values, "id=" + lopHoc.getID(), null);
71 if (rs > 0) {
72 result = true;
73 }
74 } catch (SQLException e) {
75 e.printStackTrace();
76 } finally {
77 close();
78 }
79 return result;
80 }
81
82 public boolean deleteLopHoc(int id) {
83 boolean result = false;
84 try {
85
86 openDataBase();
87 //
88 int rs = database.delete("lophoc", "id=" + id, null);
89 if (rs > 0) {
90 result = true;
91 }
92 } catch (SQLException e) {
93 e.printStackTrace();
94 } finally {
95 close();
96 }
97 return result;
}
}

public boolean insertSinhVien(S


boolean result = false;
try {

1 public boolean insertSinhVien(SinhVien sinhVien) {


2 boolean result = false;
3 try {
4
5 openDataBase();
6 ContentValues values = new ContentValues();
7 values.put("hoten", sinhVien.getHoTen());
8 values.put("masv", sinhVien.getMaSv());
9 values.put("malop", sinhVien.getMaLop());
10 values.put("diachi", sinhVien.getDiaChi());
11 long rs = database.insert("sinhvien", null, values);
12 if (rs > 0) {
13 result = true;
14 }
15 } catch (SQLException e) {
16 e.printStackTrace();
17 } finally {
18 close();
19 }
20 return result;
21 }
22
23 public boolean updateSinhVien(SinhVien sinhVien) {
24 boolean result = false;
25 try {
26
27 openDataBase();
28 ContentValues values = new ContentValues();
29 values.put("hoten", sinhVien.getHoTen());
30 values.put("masv", sinhVien.getMaSv());
31 values.put("malop", sinhVien.getMaLop());
32 values.put("diachi", sinhVien.getDiaChi());
33 int rs = database.update("sinhvien", values, "id=" + sinhVien.getID(),
34 null);
35 if (rs > 0) {
36 result = true;
37 }
38 } catch (SQLException e) {
39 e.printStackTrace();
40 } finally {
41 close();
42 }
43 return result;
44 }
45
46 public boolean deleteSinhVien(int id) {
47 boolean result = false;
48 try {
49
50 openDataBase();
51 //
52 int rs = database.delete("sinhvien", "id=" + id, null);
53 if (rs > 0) {
54 result = true;
55 }
56 } catch (SQLException e) {
57 e.printStackTrace();
58 } finally {
59 close();
60 }
61 return result;
}

By gi chng ta tin hnh hin th d liu thng qua 2 hm va ri, cc bn cu


hnh mainActivity nh sau.

package com.example.devpro.d

import android.content.SharedP
import android.os.Bundle;

1 package com.example.devpro.demosqlite;
2
3 import android.content.SharedPreferences;
4 import android.os.Bundle;
5 import android.support.design.widget.FloatingActionButton;
6 import android.support.design.widget.Snackbar;
7 import android.support.v7.app.AppCompatActivity;
8 import android.support.v7.widget.Toolbar;
9 import android.view.View;
10 import android.view.Menu;
11 import android.view.MenuItem;
12 import android.widget.Button;
13 import android.widget.TextView;
14
15 import java.io.IOException;
16 import java.util.ArrayList;
17
18 public class MainActivity extends AppCompatActivity implements
19 View.OnClickListener {
20 Button btnShowHS, btnShowLH;
21 TextView txtShowHS, txtShowLH;
22 final int currentDBversion = 1;
23 final String BDVERSION = "DBVERSION_KEY";
24 private ArrayList<SinhVien> listSV;
25 private ArrayList<LopHoc> listLH;
26
27 @Override
28 protected void onCreate(Bundle savedInstanceState) {
29 super.onCreate(savedInstanceState);
30 setContentView(R.layout.activity_main);
31 createDB();
32 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
33 setSupportActionBar(toolbar);
34
35 FloatingActionButton fab = (FloatingActionButton)
36 findViewById(R.id.fab);
37 fab.setOnClickListener(new View.OnClickListener() {
38 @Override
39 public void onClick(View view) {
40 Snackbar.make(view, "Replace with your own action",
41 Snackbar.LENGTH_LONG)
42 .setAction("Action", null).show();
43 }
44 });
45 // khi to cc control
46 btnShowHS = (Button) findViewById(R.id.btnShowHS);
47 btnShowLH = (Button) findViewById(R.id.btnShowLH);
48 txtShowHS = (TextView) findViewById(R.id.txtShowHS);
49 txtShowLH = (TextView) findViewById(R.id.txtShowLH);
50 // set s kin click
51 btnShowHS.setOnClickListener(this);
52 btnShowLH.setOnClickListener(this);
53 }
54
55 private void createDB() {
56 // khi to database
57 SQLiteDataController sql = new SQLiteDataController(this);
58 try {
59 sql.isCreatedDatabase();
60 } catch (IOException e) {
61 e.printStackTrace();
62 }
63 }
64
65 private void getListSV() {
66 SQLiteSinhVien sinhVien = new
67 SQLiteSinhVien(getApplicationContext());
68 listSV = new ArrayList<>();
69 listSV = sinhVien.getListSinhVien();
70
71 }
72
73 private void getListLH() {
74 SQLiteLopHoc lopHoc = new SQLiteLopHoc(getApplicationContext());
75 listLH = new ArrayList<LopHoc>();
76 listLH = lopHoc.getListLopHoc();
77 }
78
79 @Override
80 public void onClick(View v) {
81 switch (v.getId()) {
82 case R.id.btnShowHS:
83 // get list sinh vien ri hin th gi tr u tin ln text view
84 getListSV();
85 txtShowHS.setText(listSV.get(0).getHoTen());
86 break;
87
88 case R.id.btnShowLH:
89 // get list lop hoc ri hin th gi tr u tin ln
90 getListLH();
91 txtShowLH.setText(listLH.get(0).getTenLop());
92 break;
93 }
94 }
95
96 @Override
97 public boolean onCreateOptionsMenu(Menu menu) {
98 // Inflate the menu; this adds items to the action bar if it is present.
99 getMenuInflater().inflate(R.menu.menu_main, menu);
100 return true;
101 }
102
103 @Override
104 public boolean onOptionsItemSelected(MenuItem item) {
105 // Handle action bar item clicks here. The action bar will
106 // automatically handle clicks on the Home/Up button, so long
107 // as you specify a parent activity in AndroidManifest.xml.
108 int id = item.getItemId();
109
110 //noinspection SimplifiableIfStatement
111 if (id == R.id.action_settings) {
112 return true;
113 }
114
115 return super.onOptionsItemSelected(item);
}

Cc bn c th chy ng dng v xem kt qu nh.


y mnh ch hin th n gin d liu thi, cc bn c th thm sa xa d liu
ty mnh cu hnh sn trong 2 class SQLiteSinhVien v SQLiteLopHoc ri,
cc bn t my m thm mt cht nh. Chc cc bn hc tp chm ch !!!
database trong android bng sqlite (phn 2)

phn 1 mnh hng dn v gii thiu cho cc bn thao tc vi sqlite v s


dng tool sqlite manager. Bi hm nay mnh s hng dn cc bn to v s dng
database bng sqlite trc tip trong code. Bi vit ny s gip cc bn hiu r hn
v sqlite trong android.

u tin cc bn to cho mnh mt project, sau khi to xong project cc bn to


cho mnh mt class DatabaseHandler extend SQLiteOpenHelper khi to
database v thao tc vi database. Chng ta khi to mt database c tn l
Manager v mt table SanPham c cc thuc tnh id, masp, tensp, dongia. Cc bn
c th tham kho code mnh vit, cc phn mnh ch thch li kh r rng.

public class DatabaseHandler e

// All Static variables


// Database Version

1 public class DatabaseHandler extends SQLiteOpenHelper {


2
3 // All Static variables
4 // Database Version
5 private static final int DATABASE_VERSION = 1;
6
7 // Database Name
8 private static final String DATABASE_NAME = "Manager";
9
10 // Contacts table name
11 private static final String TABLE_CONTACTS = "SanPham";
12
13 // Contacts Table Columns names
14 private static final String KEY_ID = "id";
15 private static final String KEY_Ma = "masp";
16 private static final String KEY_NAME = "tensp";
17 private static final String KEY_DONGIA = "dongia";
18
19 public DatabaseHandler(Context context) {
20 super(context, DATABASE_NAME, null, DATABASE_VERSION);
21 }
22
23 public DatabaseHandler(Context context, String name,
24 SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler
25 errorHandler) {
26 super(context, name, factory, version, errorHandler);
27 }
28
29 @Override
30 public void onCreate(SQLiteDatabase db) {
31 String CREATE_CONTACTS_TABLE = "CREATE TABLE " +
32 TABLE_CONTACTS + "("
33 + KEY_ID + " INTEGER PRIMARY KEY,"
34 + KEY_Ma + " TEXT,"
35 + KEY_NAME + " TEXT,"
36 + KEY_DONGIA + " TEXT" + ")";
37 db.execSQL(CREATE_CONTACTS_TABLE);
38
39 }
40
41 @Override
42 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
43 {
44 // Drop older table if existed
45 db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
46
47 // Create tables again
48 onCreate(db);
49 }
50 // Adding new contact
51 void addContact(SanPham contact) {
52 SQLiteDatabase db = this.getWritableDatabase();
53
54 ContentValues values = new ContentValues();
55 values.put(KEY_Ma,contact.masp);
56 values.put(KEY_NAME, contact.getTensp());
57 values.put(KEY_DONGIA, contact.getDongia());
58
59 // Inserting Row
60 db.insert(TABLE_CONTACTS, null, values);
61 db.close(); // Closing database connection
62 }
63 // Getting single contact
64 private SanPham getContact(int id) {
65 SQLiteDatabase db = this.getReadableDatabase();
66
67 Cursor cursor = db.query(TABLE_CONTACTS, new String[] {
68 KEY_ID,KEY_Ma,
69 KEY_NAME, KEY_DONGIA }, KEY_ID + "=?",
70 new String[] { String.valueOf(id) }, null, null, null, null);
71 if (cursor != null)
72 cursor.moveToFirst();
73
74 SanPham contact = new SanPham (Integer.parseInt(cursor.getString(0)),
75 cursor.getString(1), cursor.getString(2),cursor.getString(3));
76 // return contact
77 return contact;
78 }
79
80 // Getting All Contacts
81 public ArrayList<SanPham> getAllContacts() {
82 ArrayList<SanPham> contactList = new ArrayList<SanPham>();
83 // Select All Query
84 String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
85
86 SQLiteDatabase db = this.getWritableDatabase();
87 Cursor cursor = db.rawQuery(selectQuery, null);
88
89 // looping through all rows and adding to list
90 if (cursor.moveToFirst()) {
91 do {
92 SanPham contact = new SanPham();
93 contact.setId(Integer.parseInt(cursor.getString(0)));
94 contact.setMasp(cursor.getString(1));
95 contact.setTensp(cursor.getString(2));
96 contact.setDongia(cursor.getString(3));
97 // Adding contact to list
98 contactList.add(contact);
99 } while (cursor.moveToNext());
100 }
101
102 // return contact list
103 return contactList;
104 }
105
106 // Updating single contact
107 public int updateContact(SanPham contact) {
108 SQLiteDatabase db = this.getWritableDatabase();
109
110 ContentValues values = new ContentValues();
111 values.put(KEY_Ma, contact.getMasp());
112 values.put(KEY_NAME, contact.getTensp());
113 values.put(KEY_DONGIA, contact.getDongia());
114
115 // updating row
116 return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
117 new String[] { String.valueOf(contact.getId()) });
118 }
119
120 // Deleting single contact
121 public void deleteContact(SanPham contact) {
122 SQLiteDatabase db = this.getWritableDatabase();
123 db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
124 new String[]{String.valueOf(contact.getId())});
125 db.close();
126 }
127
128
129 // Getting contacts Count
130 public int getContactsCount() {
131 String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
132 SQLiteDatabase db = this.getReadableDatabase();
133 Cursor cursor = db.rawQuery(countQuery, null);
134 cursor.close();

// return count
return cursor.getCount();
}
}
Class ny tng ng vi class SQLiteDataController phn 1. Tip theo chng
ta sang class MainActivity gi v s dng database.

public class MainActivity extend


ListView lvData;
ArrayList<SanPham> list;
private ArrayList<SanPham>

1 public class MainActivity extends AppCompatActivity {


2 ListView lvData;
3 ArrayList<SanPham> list;
4 private ArrayList<SanPham> contacts;
5 private MyAdapter adapter;
6
7 @Override
8 protected void onCreate(Bundle savedInstanceState) {
9 super.onCreate(savedInstanceState);
10 setContentView(R.layout.activity_main);
11 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
12 setSupportActionBar(toolbar);
13
14 DatabaseHandler db = new DatabaseHandler(this);
15
16 /**
17 * CRUD Operations
18 * */
19 // Inserting Contacts
20 Log.d("Insert: ", "Inserting ..");
21 db.addContact(new SanPham(1,"SP_122", "Vertu Constellation",
22 "10000"));
23 db.addContact(new SanPham(2,"SP-123", "Vertu ", "10000"));
24 db.addContact(new SanPham(3,"SP-124", "Constellation", "10000"));
25 db.addContact(new SanPham("SP-125", "Vertu Cons", "10000"));
26
27 // Reading all contacts
28 Log.d("Reading: ", "Reading all contacts..");
29 contacts = db.getAllContacts();
30
31 for (SanPham cn : contacts) {
32 String log = "id: " + cn.getId() + " ,masp: " + cn.getMasp() + " ,tensp: "
33 + cn.getTensp() + " ,dongia: " + cn.getDongia();
34 // Writing Contacts to log
35 Log.d("Name: ", log);
36 }
37 lvData = (ListView) findViewById(R.id.lvData);
38 adapter = new MyAdapter(this, contacts);
39 lvData.setAdapter(adapter);
40 // adapter.notifyDataSetChanged();
41
42 }
43
44 @Override
45 public boolean onCreateOptionsMenu(Menu menu) {
46 // Inflate the menu; this adds items to the action bar if it is present.
47 getMenuInflater().inflate(R.menu.menu_main, menu);
48 return true;
49 }
50
51 @Override
52 public boolean onOptionsItemSelected(MenuItem item) {
53 // Handle action bar item clicks here. The action bar will
54 // automatically handle clicks on the Home/Up button, so long
55 // as you specify a parent activity in AndroidManifest.xml.
56 int id = item.getItemId();
57
58 //noinspection SimplifiableIfStatement
59 if (id == R.id.action_settings) {
60 return true;
61 }
62
63 return super.onOptionsItemSelected(item);
}
}

y mnh s dng mt listview hin th database ln. Cc bn cu hnh bn


layout
android:layout_w idth="fill_
android:layout_height="fill_
</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>


1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"
8 android:paddingTop="@dimen/activity_vertical_margin"
9 android:paddingBottom="@dimen/activity_vertical_margin"
10 app:layout_behavior="@string/appbar_scrolling_view_behavior"
11 tools:showIn="@layout/activity_main" tools:context=".MainActivity">
12
13 <ListView
14 android:id="@+id/lvData"
15 android:layout_width="fill_parent"
16 android:layout_height="fill_parent"></ListView>
</RelativeLayout>

Listview ny hin th d liu t database ln, chng ta i custom n. Trc tin


chng ta to mt class thc th cha cc thng tin ca mt sn phm.

this.dongia = dongia;
}
}

1 public class SanPham {


2 int id;
3 String masp;
4 String tensp;
5 String dongia;
6
7 public SanPham() {
8 }
9
10 public SanPham(String tensp, String dongia) {
11 this.tensp = tensp;
12 this.dongia = dongia;
13 }
14
15 public SanPham(String masp, String tensp, String dongia) {
16 this.masp = masp;
17 this.tensp = tensp;
18 this.dongia = dongia;
19 }
20
21 public SanPham(int id, String masp, String tensp, String dongia) {
22 this.id = id;
23 this.masp = masp;
24 this.tensp = tensp;
25 this.dongia = dongia;
26 }
27
28 public int getId() {
29 return id;
30 }
31
32 public void setId(int id) {
33 this.id = id;
34 }
35
36 public String getMasp() {
37 return masp;
38 }
39
40 public void setMasp(String masp) {
41 this.masp = masp;
42 }
43
44 public String getTensp() {
45 return tensp;
46 }
47
48 public void setTensp(String tensp) {
49 this.tensp = tensp;
50 }
51
52 public String getDongia() {
53 return dongia;
54 }
55
56 public void setDongia(String dongia) {
57 this.dongia = dongia;
58 }
59 }

Tip theo chng ta i custom Adapter cho listview. Cc k thut ny mnh


hng dn bi custom listview, cc bn c th xem li.

public class MyAdapter extends


ArrayList<SanPham> listData
LayoutInflater inflater;
Context context;

1 public class MyAdapter extends BaseAdapter {


2 ArrayList<SanPham> listData;
3 LayoutInflater inflater;
4 Context context;
5
6 // Hm to ca custom
7 public MyAdapter(Context context, ArrayList<SanPham> listData) {
8 this.inflater = (LayoutInflater)
9 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
10 this.listData = listData;
11 this.context = context;
12 }
13
14 // Tr v s lng phn t c hin th trong listview
15 @Override
16 public int getCount() {
17 return listData.size();
18 }
19
20 // Tr v i tng c ly theo v tr
21 @Override
22 public Object getItem(int position) {
23 return listData.get(position);
24 }
25
26 @Override
27 public long getItemId(int position) {
28 return 0;
29 }
30
31 // Hm quan trng nht, hin th giao din ca listview
32 @Override
33 public View getView(int position, View convertView, ViewGroup parent) {
34 // Ly ra i tng cn hin th v tr th position
35 SanPham item = listData.get(position);
36 // Khai bo cc component
37 TextView txtId, txtMaSP, txtTenSP, txtDongGia;
38 // Khi to view.
39 if (convertView == null) {
40 convertView = inflater.inflate(R.layout.item_listview, parent, false);
41 }
42
43 txtId = (TextView) convertView.findViewById(R.id.txtID);
44 txtMaSP = (TextView) convertView.findViewById(R.id.txtMaSP);
45 txtTenSP = (TextView) convertView.findViewById(R.id.txtTenSP);
46 txtDongGia = (TextView) convertView.findViewById(R.id.txtDongGia);
47 // Set d liu vo item ca list view
48 txtId.setText(item.getId()+"");
49 txtMaSP.setText(item.getMasp());
50 txtTenSP.setText(item.getTensp());
51 txtDongGia.setText(item.getDongia());
52 return convertView;
53 }
}

Vy l chng ta hon thnh vic ly d liu t database v a ln listview.


Chng ta hy xem thnh qu nh.
Cc bn c th kim tra database trn my tht nu my c root cn trn my
o, y mnh dng genymotion cc bn c th lm nh sau.
Sau y mnh s hng dn cc bn ly data ra v xem trn Sqlite Manager.
Nh vy l chng ta hon ton c th lm vic vi sqlite theo cch no m cc
bn thy n gin nht. Cc bn hay ch theo di nhng bi hng dn tip theo
nh. Chng cc bn hc tp tt nh!

Anda mungkin juga menyukai