Sqlite
Cc bn to mt c s d liu mi c tn quanlisinhvien.
Cc bn lu file database va to.
Cc bn to mt project mi c tn l demoSQLite.
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.
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 }
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;
}
}
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);
}
// 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.
this.dongia = dongia;
}
}