[Học lập trình Android] Bài tập: Làm việc với SQLite

ngày 23-08-2017

Bài tập được trích từ chương trình học Lập trình viên Android của Trung tâm Tin học Khoa học Tự nhiên.
Sau khi thực hiện bài lab này người học có khả năng:
Xây dựng ứng dụng lưu trữ dữ liệu với SQLite trong Android
Thực hiện được các truy vấn Insert, Update, Delete, Select trong Sqlite với Android
Xây dựng được 2 dạng menu Option Menu, Context Menu
 
Yêu cầu:
Xây dựng quản lý sinh viên với giao diện sau:
 
Làm việc với SQLite Làm việc với SQLite Làm việc với SQLite Làm việc với SQLiteLàm việc với SQLite
 
Một số nghiệp vụ như sau:
 
Ứng dụng hiển thị toàn bộ danh sách sinh viên tại màn hình 1
Thực hiện thêm sinh viên như màn hình 3
Thực hiện xoá hoặc cập nhật thông tin sinh viên như màn hình 4
 
Gợi ý thực hiện
 

Bước 1: Tạo project BT_LAB3

 

Bước 2: Xây dựng class DBHelper đê copy database và thực hiện kêt nối và class Student để quản lý sinh viên

 

Bươc 2.1: Class DBHelper

 

public class DBHelper {
    String DATABASE_NAME = "StudentesDB.sqlite";
    private static final String DB_PATH_SUFFIX = "/databases/";
    SQLiteDatabase db = null;

    Context context;

    public DBHelper(Context context) {
        this.context = context;

        processSQLite();
    }

    private void processSQLite() {
        File dbFile = context.getDatabasePath(DATABASE_NAME);
        if(!dbFile.exists()){
            try{
                CopyDatabaseFromAsset();
                Toast.makeText(context, "Copy successful !!!", Toast.LENGTH_SHORT).show();

            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    private void CopyDatabaseFromAsset() {
        try{
            InputStream databaseInputStream = context.getAssets().open(DATABASE_NAME);

            String outputStream = getPathDatabaseSystem();

            File file = new File(context.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
            if(!file.exists()){
                file.mkdir();
            }

            OutputStream databaseOutputStream = new FileOutputStream(outputStream);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = databaseInputStream.read(buffer)) > 0){
                databaseOutputStream.write(buffer,0,length);
            }


            databaseOutputStream.flush();
            databaseOutputStream.close();
            databaseInputStream.close();

        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    private String getPathDatabaseSystem() {
        return context.getApplicationInfo().dataDir + DB_PATH_SUFFIX + DATABASE_NAME;
    }

    public ArrayList<Student> getAllStudent(){
        ArrayList<Student> arrayList = new ArrayList<>();

        db = context.openOrCreateDatabase(DATABASE_NAME,context.MODE_PRIVATE,null);

        String sql = "SELECT * FROM Student";

        Cursor cursor  = db.rawQuery(sql ,null);
        while (cursor.moveToNext()){
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String address = cursor.getString(2);
            int gender = cursor.getInt(3);

            arrayList.add(new Student(id,name,address,gender));
        }
        return arrayList;
    }

    public void insertStudent(Student student){

        db = context.openOrCreateDatabase(DATABASE_NAME,context.MODE_PRIVATE,null);

        ContentValues contentValues = new ContentValues();
        contentValues.put("id",student.getId());
        contentValues.put("name",student.getName());
        contentValues.put("address",student.getAddress());
        contentValues.put("gender",student.getGender());

        if(db.insert("Student",null,contentValues) > 0){
            Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
        }
    }

    public void updateStudent(Student student){
        db = context.openOrCreateDatabase(DATABASE_NAME,context.MODE_PRIVATE,null);

        ContentValues contentValues = new ContentValues();
        contentValues.put("name",student.getName());
        contentValues.put("address",student.getAddress());
        contentValues.put("gender",student.getGender());

        if(db.update("Student",contentValues,"id =" + student.getId(),null) > 0){
            Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
        }
    }

    public void deleteStudent(Student student){
        db = context.openOrCreateDatabase(DATABASE_NAME,context.MODE_PRIVATE,null);

        if(db.delete("Student","id =" + student.getId(),null) > 0){
            Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
        }
    }
}

 

Bước 2.2: class Student

 

public class Student {
    int id;
    String name;
    String address;
    int gender;
 
    public Student() {
    }
 
    public Student(int id, String name, String address, int gender) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.gender = gender;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    public int getGender() {
        return gender;
    }
 
    public void setGender(int gender) {
        this.gender = gender;
    }
}
 
 

Bước 3: Tạo thư mục asset trong Android studio

 

Bước 3.1: Right chuột vô thư mục res → new → Folder → Asset Folder

 

Làm việc với SQLite
 

Bước 3.2 : chọn finish để hoàn thành

 

Bước 3.3: copy file database được cung cấp vào thư mục asset vừa tạo

 

Làm việc với SQLite
 
 

Bước 4: Xây dựng giao diện activity_main

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.vudinhai.bt_lab3.MainActivity">
 
  <ListView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/list"/>
</LinearLayout>

 

Bước 5: Xây dựng layout_row để hiển thị dữ liệu

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="100dp">
 
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/image"/>
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:padding="8dp">
 
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="Name"
                android:id="@+id/txtName"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="16sp"
                android:text="Name"
                android:id="@+id/txtAddress"/>
        </LinearLayout>
    </RelativeLayout>
 
 
</LinearLayout>

 

Bước 6: Xây dựng layout_input để tiến hành Insert và Update sinh viên

 

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1"
    android:padding="16dp">
 
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name:"
            android:textSize="18sp"/>
 
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edtName"
            android:textAlignment="center"
            android:layout_span="2"
            android:hint="name"/>
 
    </TableRow>
 
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Address:"
            android:textSize="18sp"/>
 
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edtAddress"
            android:textAlignment="center"
            android:layout_span="2"
            android:hint="address"/>
    </TableRow>
 
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_gravity="center|left"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender:"
            android:textSize="18sp"/>
 
        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:id="@+id/rdgGender">
 
            <RadioButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/rdbMale"
                android:text="Male"/>
            <RadioButton
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/rdbFemale"
                android:text="FeMale"/>
        </RadioGroup>
        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/image"
            android:src="@color/colorAccent" />
    </TableRow>
 
 
</TableLayout>
 

Bước 7: Tiến hành xây dựng menu 

 

Bước 7.1: menu option với tên main_menu

 

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
 
    <item android:title="Add"
        android:id="@+id/mnu_add"
        android:icon="@drawable/ic_add_black_24dp"
        app:showAsAction="always"/>
 
 
</menu>

 

Bước 7.2: menu context với tên context_menu

 

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
    <item android:title="Update"
        android:id="@+id/mnu_update" />
 
    <item android:title="Delete"
        android:id="@+id/mnu_delete" />
 
 
</menu>

 

Bước 8: Xây dựng lớp Adapter với tên Student Adapter

 

public class StudentAdapter extends ArrayAdapter<Student> {
 
    Context context;
    int layout;
    ArrayList<Student> arrayList;
 
    public StudentAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<Student> objects) {
        super(context, resource, objects);
        this.context = context;
        this.layout = resource;
        this.arrayList = objects;
 
    }
 
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater =LayoutInflater.from(context);
        convertView = inflater.inflate(layout,null);
 
        ImageView img =(ImageView)convertView.findViewById(R.id.image);
        TextView txt1 = (TextView)convertView.findViewById(R.id.txtName);
        TextView txt2 = (TextView)convertView.findViewById(R.id.txtAddress);
 
        if(arrayList.get(position).getGender() == 1) {
            img.setImageResource(R.drawable.male);
        }else {
            img.setImageResource(R.drawable.female);
        }
 
        txt1.setText(arrayList.get(position).getName());
        txt2.setText(arrayList.get(position).getAddress());
 
        return convertView;
    }
}

 

Bước 9: Thực hiện nghiệp vụ theo yêu cầu đề bài, thực hiện code cho MainActivity

 

public class MainActivity extends AppCompatActivity {
 
    ListView listView;
    ArrayList<Student> arrayList;
    StudentAdapter studentAdapter;
    DBHelper db;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //khoi tao doi tuong DBHelper
        db = new DBHelper(MainActivity.this);
        //mapping listview
        listView = (ListView)findViewById(R.id.list);
        //load danh sach sinh vien
        arrayList = db.getAllStudent();
        studentAdapter = new StudentAdapter(MainActivity.this,
                                            R.layout.layout_row,
                                            arrayList);
 
        listView.setAdapter(studentAdapter);
 
        //dang ky menu COntext cho listView
        registerForContextMenu(listView);
 
    }
    //them menu insert student
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu,menu);
 
        return super.onCreateOptionsMenu(menu);
    }
    //Xu ly menu insert student
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.mnu_add){
            final Student student = new Student();
 
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 
            builder.setTitle("Insert student");
            builder.setCancelable(false);
 
            LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
            View view = inflater.inflate(R.layout.layout_input,null);
 
            final EditText edtName = (EditText)view.findViewById(R.id.edtName);
            final EditText edtAddress = (EditText)view.findViewById(R.id.edtAddress);
            final RadioGroup rdg = (RadioGroup)view.findViewById(R.id.rdgGender);
            final ImageView img = (ImageView)view.findViewById(R.id.image);
 
            builder.setView(view);
 
            rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    switch (checkedId){
                        case R.id.rdbMale:
                            student.setGender(1);
                            img.setImageResource(R.drawable.male);
                            break;
                        case R.id.rdbFemale:
                            student.setGender(0);
                            img.setImageResource(R.drawable.female);
                            break;
                    }
                }
            });
 
 
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    student.setName(edtName.getText().toString());
                    student.setAddress(edtAddress.getText().toString());
 
                    db.insertStudent(student);
                    arrayList.add(student);
                    studentAdapter.notifyDataSetChanged();
                }
            });
 
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
 
 
 
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
        return super.onOptionsItemSelected(item);
    }
 
    //them menu Update va delete
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu,menu);
 
    }
 
    //xu ly menu Update va delete
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()){
            case R.id.mnu_update:
                final Student student = arrayList.get(info.position);
 
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
 
                builder.setTitle("Update student");
                builder.setCancelable(false);
 
                LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
                View view = inflater.inflate(R.layout.layout_input,null);
 
                final EditText edtName = (EditText)view.findViewById(R.id.edtName);
                final EditText edtAddress = (EditText)view.findViewById(R.id.edtAddress);
                final RadioGroup rdg = (RadioGroup)view.findViewById(R.id.rdgGender);
                final RadioButton rdbMale = (RadioButton)view.findViewById(R.id.rdbMale);
                final RadioButton rdbFemale = (RadioButton)view.findViewById(R.id.rdbFemale);
                final ImageView img = (ImageView)view.findViewById(R.id.image);
 
                edtName.setText(student.getName());
                edtAddress.setText(student.getAddress());
 
                if(student.getGender() == 1){
                    rdbMale.setChecked(true);
                    img.setImageResource(R.drawable.male);
                }else {
                    rdbFemale.setChecked(true);
                    img.setImageResource(R.drawable.female);
                }
 
 
                builder.setView(view);
 
                rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                        switch (checkedId){
                            case R.id.rdbMale:
                                student.setGender(1);
                                img.setImageResource(R.drawable.male);
                                break;
                            case R.id.rdbFemale:
                                student.setGender(0);
                                img.setImageResource(R.drawable.female);
                                break;
                        }
                    }
                });
 
 
 
 
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        student.setName(edtName.getText().toString());
                        student.setAddress(edtAddress.getText().toString());
 
                        db.updateStudent(student);
                        arrayList.set(info.position,student);
                        studentAdapter.notifyDataSetChanged();
                    }
                });
 
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
 
 
 
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                break;
            case R.id.mnu_delete:
                final Student student1 = arrayList.get(info.position);
 
                AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
 
                builder1.setTitle("Delete student");
                builder1.setCancelable(false);
                builder1.setMessage("Are you sure delete \" " + student1.getName() + "\"" );
 
                builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        db.deleteStudent(student1);
                        arrayList.remove(info.position);
                        studentAdapter.notifyDataSetChanged();
                    }
                });
 
                builder1.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
 
                AlertDialog alertDialog1 = builder1.create();
                alertDialog1.show();
 
 
                break;
 
        }
 
 
        return super.onContextItemSelected(item);
    }
}

 

Chúc các bạn học tốt!

Trung tâm Tin học ĐH Khoa học Tự nhiên