Tạo ứng dụng Android thêm, sửa, xoá với CSDL SQLite

Nội dung

Giới thiệu

SQLite là một hệ quản trị cơ sở dữ liệu trên Android giúp các nhà phát triển ứng dụng lưu dữ liệu cục bộ trên bộ nhớ thiết bị ở dạng có cấu trúc, giúp dễ dàng đọc, cập nhật hoặc xóa dữ liệu được lưu ở nhiều định dạng khác nhau.

Android SQLite là cách tốt nhất để lưu dữ liệu cục bộ trên chính thiết bị.

SQLite hoạt động như một database cục bộ cho các ứng dụng lưu dữ liệu theo cấu trúc hàng cột truyền thống. Nó phù hợp khi dữ liệu lưu trữ theo dạng bảng, chẳng hạn như dữ liệu người dùng, dữ liệu sách, dữ liệu nhân viên, v.v.

Chúng ta sẽ triển khai phát triển ứng dụng với SQLite bắt đầu bằng việc sử dụng API của gói android.database.sqlite .

Bạn có thể xem thêm những giới hạn của SQLite tại đây
Xem thêm Khoá học lập trình với Android.

Trong bài này, tôi sẽ tạo một ứng dụng mẫu, sẽ diễn giải một số chức năng cơ bản để thao tác với các bảng trong Database như Insert, Delete Update, Remove All Table, Get Rows Count Get All Rows được lưu trong Table.

Trước khi bắt đầu, chúng ta cùng xem một số hình ảnh demo của ứng dụng chúng ta sẽ phát triển.

 

Chương trình quản lý UserYêu cầu

Tạo một cơ sở dữ liệu trong SQLite, trong đó có bảng:
USERS(ID integer primary key autoincrement,user_name text,user_phone text,user_email text)

Viết ứng dụng trong Android thực hiện các công việc:

  • Thêm mới người sử dụng
  • Sửa người sử dụng đã chọn
  • Xoá người sử dụng được chọn
  • Đếm số lượng người sử dụng
  • Xoá toàn bộ người sử dụng

Bước 1) Mở Android Studio và tạo một project mới, chọn loại project là Empty Activity

Tạo mới dự án Android.

Bước 2) Tạo một lớp UserModel để getset các dữ liệu cho bảng User.

UserModel.java


public class UserModel {

    String ID,username,phone,email;

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
        public String getUserphone() {
            return phone;
        }

        public void setUserphone(String phone) {
            this.phone = phone;
        }
        public String getUseremail() {
            return email;
        }

        public void setUseremail(String email) {
            this.email = email;
        }

    }

Bước 3) Viết lớp Utils để hiển thị thông báo


public class Utils {
    public static void showToast(Context context, String msg)
    {
        Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        toast.show();
    }
}

Bước 4) Tạo lớp  UsersDatabaseAdapter thực thi các phương thức thao tác với Database như Insert, Update, Delete, v.v.


public class UsersDatabaseAdapter {
    static ArrayList<UserModel> users=new ArrayList<>();
    static final String DATABASE_NAME = "UsersDatabase.db";
    static final String TABLE_NAME = "USERS";
    static final int DATABASE_VERSION = 1;
    // Câu lệnh SQL tạo mới cơ sở dữ liệu.
    static final String DATABASE_CREATE = "create table "+TABLE_NAME+"( ID integer primary key autoincrement,user_name  text,user_phone  text,user_email text); ";
    private static final String TAG = "UsersDatabaseAdapter";

    // Khai báo biên db kiểm SQLiteDatabase để thực thi các phương thức với cơ sở dữ liệu
    public static SQLiteDatabase db;
    // Khai báo đối tượng kiểu Context của ứng dụng sử dụng cơ sở dữ liệu này.
    private final Context context;
    // Database open/upgrade helper
    private static DataBaseHelper dbHelper;
    public  UsersDatabaseAdapter(Context _context)
    {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Phương thức mở Database
    public  UsersDatabaseAdapter open() throws SQLException
    {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    // Phương thức đóng Database
    public void close()
    {
        db.close();
    }

    // Phương thức trả về instance của Database
    public  SQLiteDatabase getDatabaseInstance()
    {
        return db;
    }

    // Phương thức insert bản ghi vào Table
    public String insertEntry(String user_name, String user_phone, String user_email)
    {

        try {


            ContentValues newValues = new ContentValues();
            // Gán dữ liệu cho mỗi cột.
            newValues.put("user_name", user_name);
            newValues.put("user_phone", user_phone);
            newValues.put("user_email", user_email);

            // Insert hàng dữ liệu vào table
            db = dbHelper.getWritableDatabase();
            long result=db.insert(TABLE_NAME, null, newValues);
            Log.i("Row Insert Result ", String.valueOf(result));
            Utils.showToast(this.context.getApplicationContext(), "User Info Saved! Total Row Count is "+getRowCount());
            db.close();

        }catch(Exception ex) {
        }
        return "ok";
    }

    // Phương thức lấy tất cả các hàng được lưu trong Table
    public static ArrayList<UserModel> getRows() throws JSONException {

        users.clear();
        UserModel user;
        db=dbHelper.getReadableDatabase();
        Cursor projCursor = db.query(TABLE_NAME, null, null,null, null, null, null,null);
        while (projCursor.moveToNext()) {

            user=new UserModel();
            user.setID(projCursor.getString(projCursor.getColumnIndex("ID")));
            user.setUsername(projCursor.getString(projCursor.getColumnIndex("user_name")));
            user.setUserphone(projCursor.getString(projCursor.getColumnIndex("user_phone")));
            user.setUseremail(projCursor.getString(projCursor.getColumnIndex("user_email")));
            users.add(user);
        }
        projCursor.close();
        return users;
    }

    // phương thức xoá bản ghi trong Table sủw dụng khoá chính là ID
    public int deleteEntry(String ID)
    {
        String where="ID=?";
        int numberOFEntriesDeleted= db.delete(TABLE_NAME, where, new String[]{ID}) ;
        Toast.makeText(this.context.getApplicationContext(),"Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_SHORT).show();
        return numberOFEntriesDeleted;
    }

    // Phương thức đếm tổng số bản ghi trong Table
    public int getRowCount()
    {
        db=dbHelper.getReadableDatabase();
        Cursor cursor=db.query(TABLE_NAME, null, null, null, null, null, null);
        Toast.makeText(this.context.getApplicationContext(),"Row Count is "+cursor.getCount(),Toast.LENGTH_LONG).show();
        db.close();
        return cursor.getCount();
    }

    // Phương thức xoá tất cả các bản ghi trong bảng Table
    public void truncateTable()
    {
        db=dbHelper.getReadableDatabase();
        db.delete(TABLE_NAME, "1", null);
        db.close();
        Toast.makeText(context.getApplicationContext(),"Table Data Truncated!",Toast.LENGTH_LONG).show();
    }

    // Phương thức Update các bản ghi trong Table
    public void  updateEntry(String ID,String Username, String Userphone, String Useremail)
    {
        ContentValues updatedValues = new ContentValues();
        updatedValues.put("user_name", Username);
        updatedValues.put("user_phone", Userphone);
        updatedValues.put("user_email", Useremail);
        String where="ID = ?";
        db=dbHelper.getReadableDatabase();
        db.update(TABLE_NAME,updatedValues, where, new String[]{ID});
        db.close();
        Toast.makeText(context.getApplicationContext(),"Row Updated!",Toast.LENGTH_LONG).show();
    }
}

Bước 5) Kế tiếp tạo một lớp DataBaseHelper được kế thừa từ lớp SQLiteOpenHelper, đây là lớp helper quản lý tạo database và quản lý phiên bản.


package timoday.edu.vn.quanlyuser;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import static timoday.edu.vn.manageuser.UsersDatabaseAdapter.TABLE_NAME;

public class DataBaseHelper extends SQLiteOpenHelper {
    public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        try {
            _db.execSQL(UsersDatabaseAdapter.DATABASE_CREATE);
        }catch(Exception er){
            Log.e("Error","exceptioin");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
    {
        _db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        _db.execSQL("DROP TABLE IF EXISTS " + "SEMESTER1");
        // Tạo một database mới.
        onCreate(_db);
    }
}

Bước  6) Viết code cho MainActivity, tạo một đối tượng kiểu UsersDatabaseAdapter để tạo DATABASE và TABLE.

Bước 6.1) Giao diện activity_main.xml sau khi thêm các button


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    tools:context=".MainActivity">

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal">


        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@drawable/freakyjollylogo"
                tools:layout_editor_absoluteX="8dp"
                android:onClick="goToUrl"/>
        </TableRow>


        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/insertRow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:onClick="insertRowActivity"
                android:text="Insert User" />
        </TableRow>


        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <Button
                android:id="@+id/updateRowView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:onClick="updateRowView"
                android:text="Update User" />

        </TableRow>
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/deleteRow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:onClick="deleteRowActivity"
                android:text="Delete User" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <Button
                android:id="@+id/rowCount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:onClick="rowCount"
                android:text="Count User" />

        </TableRow>


        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/truncateTable"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:onClick="truncateTable"
                android:text="Remove All User" />
        </TableRow>

    </TableLayout>

</android.support.constraint.ConstraintLayout>

Chương trình quản lý User

Bước 6.2) Code MainActitity.java

Khai báo một đối tượng usersDatabaseAdapter bên ngoài phương thức onCreate

UsersDatabaseAdapter usersDatabaseAdapter;

Sau đó hoàn thiện code như bên dưới:

public class MainActivity extends AppCompatActivity {
    UsersDatabaseAdapter usersDatabaseAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // create the instance of Databse
        usersDatabaseAdapter=new UsersDatabaseAdapter(getApplicationContext());
    }

    //open activity to Insert new rows in table
    public void insertRowActivity(View view) {
        Intent myIntent = new Intent(MainActivity.this, InsertRowActivity.class);
        MainActivity.this.startActivity(myIntent);
    }

    //Open activity to update rows
    public void updateRowView(View view) {
        Intent myIntent = new Intent(MainActivity.this, UpdateRowsActivity.class);
        MainActivity.this.startActivity(myIntent);
    }

    //call method to show rows count in Toast
    public void rowCount(View view) {
        usersDatabaseAdapter.getRowCount();
    }

    //Open activity to delete rows
    public void deleteRowActivity(View view) {
        Intent myIntent = new Intent(MainActivity.this, DeleteRowsActivity.class);
        MainActivity.this.startActivity(myIntent);
    }

    //Button method to truncate table rows
    public void truncateTable(View view) {
        usersDatabaseAdapter.truncateTable();
    }

    //Open URL in browser
    public void goToUrl (View view) {
        String url = "https://timoday.edu.vn";
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }
}

 

Bước 7) Tạo các Activity  và code cho thêm, sửa, xoá và hai ListView

Các Activitie bao gồm:

  1. activity_insert_row.xml
  2. activity_update_rows.xml
  3. activity_delete_rows.xml

Cách đề hêm một Activity mới: Kích chuột phải trên main package > New > Activity > Empty Activity

Chúng ta sẽ thêm phần giao diện sau đó sẽ viết phần code Activity.

Bước 7.1) Tạo giao diện activity_insert_row.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    tools:context=".InsertRowActivity">



    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/userNameTxt"
                android:layout_width="293dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:hint="User Name"
                android:inputType="textPersonName" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/userPhoneTxt"
                android:layout_width="289dp"
                android:layout_height="53dp"
                android:layout_marginBottom="10dp"
                android:hint="User Phone"
                android:inputType="phone" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText
                android:id="@+id/userEmailTxt"
                android:layout_width="291dp"
                android:layout_height="59dp"
                android:layout_marginBottom="10dp"
                android:hint="User Email"
                android:inputType="textEmailAddress" />
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <Button
                android:id="@+id/insertRowFrom"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="insertRow"
                android:text="Insert User" />
        </TableRow>
    </TableLayout>
</android.support.constraint.ConstraintLayout>

Giao diện thêm mới User

 

Bước 7.2) Code InsertRowActivity.java


public class InsertRowActivity extends AppCompatActivity {
    private TextView mUserName;
    private TextView mUserPhone;
    private TextView mUserEmail;
    private Button insertRowFrom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_row);

        insertRowFrom = (Button) findViewById(R.id.insertRowFrom);
        mUserName = (TextView) findViewById(R.id.userNameTxt);
        mUserPhone = (TextView) findViewById(R.id.userPhoneTxt);
        mUserEmail = (TextView) findViewById(R.id.userEmailTxt);


        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("Inser New User");
        }
    }
    public void insertRow(View view) {

        TextView userNameTxtView = findViewById(R.id.userNameTxt);
        TextView userPhoneTxtView = findViewById(R.id.userPhoneTxt);
        TextView userEmailTxtView = findViewById(R.id.userEmailTxt);

        if(userNameTxtView.getText().toString().trim().equals("")
                || userPhoneTxtView.getText().toString().trim().equals("")
                || userEmailTxtView.getText().toString().trim().equals("")){
            Utils.showToast(InsertRowActivity.this, "Please Fill All Fields ");
        }else{
            UsersDatabaseAdapter usersDB = new UsersDatabaseAdapter(getApplicationContext());
            usersDB.insertEntry(userNameTxtView.getText().toString().trim(),userPhoneTxtView.getText().toString(),userEmailTxtView.getText().toString());
            Intent myIntent = new Intent(InsertRowActivity.this, MainActivity.class);
            InsertRowActivity.this.startActivity(myIntent);
        }

    }

    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
}

Trong InsertRowActivity chúng ta sẽ hiển thị một form với ba trường EditText và nút Submit để lưu các giá trị tới bảng sử dụng phương thức insertEntry của đối tượng UsersDatabaseAdapter

Bước 7.3) Giao diện activity_update_rows.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".UpdateRowsActivity">


    <ListView
        android:id="@+id/listupdateviewID"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_margin="10dp"
        android:padding="10dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />

</android.support.constraint.ConstraintLayout>

Giao diện Update User

 

Bước 7.4) Code UpdateRowsActivity.java


public class UpdateRowsActivity extends AppCompatActivity {
    static ListView listView ;
    ArrayList<UserModel> users=new ArrayList<>();
    static CustomListAdapterUpdateRows updateAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_rows);

        try {
            UsersDatabaseAdapter usersDB = new UsersDatabaseAdapter(getApplicationContext());
            users = usersDB.getRows();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        updateAdapter = new CustomListAdapterUpdateRows(this, users);
        listView = (ListView) findViewById(R.id.listupdateviewID);
        listView.setAdapter(updateAdapter);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("Update User");
        }
    }
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
}

UpdateRowsActivity sẽ có ListView để hiển thị dữ liệu theo hàng và mỗi hàng sẽ có một nút Update để cập nhật dữ liệu trực tiếp theo từng hàng.

Bước 7.5) Giao diện activity_delete_rows.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".deleteRowsActivity">


    <ListView
        android:id="@+id/listviewdeleteID"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_margin="10dp"
        android:padding="10dp"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />
</android.support.constraint.ConstraintLayout>

 

 

Giao diện xoá UserBước 7.6) DeleteRowsActivity.java


public class DeleteRowsActivity extends AppCompatActivity {
    ListView listView ;
    ArrayList<UserModel> users=new ArrayList<>();
    static CustomListAdapterDeleteRows deleteAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delete_rows);
        try {
            users = UsersDatabaseAdapter.getRows();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        deleteAdapter = new CustomListAdapterDeleteRows(this, users);
        listView = (ListView) findViewById(R.id.listviewdeleteID);
        listView.setAdapter(deleteAdapter);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("Delete Row from SQLite");
        }
    }

    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
}

Bây giờ chúng ta sẽ thêm hai layout chứa ListView

Cách để thêm danh sách Layout: Kích chuột phải vào thư mục layout trong res > New > Layout resource file

Tạo Layout trong Android

 

Bước 7.7) Giao diện listviewupdate_row.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="96dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="64dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="50dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="" />

    <Button
        android:id="@+id/updateBtn"
        android:layout_width="41dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:onClick="deleteListRow"
        android:text="Update"
        android:textSize="10sp" />

</LinearLayout>

Đây là ListLayout cho activity Update theo hàng.

Bước 7.8) Giao diện listviewdelete_row.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="95dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="83dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="82dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Del"
        android:onClick="deleteListRow"/>

</LinearLayout>

Đây là layout cho Acivity Update

Bước 8) Code class CustomListAdapterUpdateRows CustomListAdapterDeleteRows hiển thị danh sách user trong ListViews cho UpdateDelete.

Bước 8.1) Code CustomListAdapterUpdateRows.java


public class CustomListAdapterUpdateRows extends BaseAdapter {
    Context c;
    ArrayList<UserModel> users;

    public CustomListAdapterUpdateRows(Context c, ArrayList<UserModel> users) {
        this.c = c;
        this.users = users;
    }

    @Override
    public int getCount() {
        return users.size();
    }

    @Override
    public Object getItem(int i) {
        return users.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view= LayoutInflater.from(c).inflate(R.layout.listviewupdate_row,viewGroup,false);
        }

        final EditText meditText1 = (EditText) view.findViewById(R.id.editText1);
        final EditText meditText2 = (EditText) view.findViewById(R.id.editText2);
        final EditText meditText3 = (EditText) view.findViewById(R.id.editText3);
        Button updateBtn = (Button) view.findViewById(R.id.updateBtn);

        final UserModel user= (UserModel) this.getItem(i);
        meditText1.setText(user.getUsername());
        meditText2.setText(user.getUserphone());
        meditText3.setText(user.getUseremail());

        updateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String col1value = meditText1.getText().toString();
                String col2value = meditText2.getText().toString();
                String col3value = meditText3.getText().toString();
                UsersDatabaseAdapter usersDB = new UsersDatabaseAdapter(c);
                usersDB.updateEntry(user.getID(),col1value,col2value,col3value);
            }
        });

        return view;
    }
}

Bước 8.2) Code CustomListAdapterDeleteRows.java


public class CustomListAdapterDeleteRows extends BaseAdapter {
    Context c;
    ArrayList<UserModel> users;

    public CustomListAdapterDeleteRows(Context c, ArrayList<UserModel> users) {
        this.c = c;
        this.users = users;
    }

    @Override
    public int getCount() {
        return users.size();
    }

    @Override
    public Object getItem(int i) {
        return users.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view=LayoutInflater.from(c).inflate(R.layout.listviewdelete_row,viewGroup,false);
        }

        TextView mtextView1 = (TextView) view.findViewById(R.id.textView1);
        TextView mtextView2 = (TextView) view.findViewById(R.id.textView2);
        TextView mtextView3 = (TextView) view.findViewById(R.id.textView3);
        Button deleteBtn = (Button) view.findViewById(R.id.button1);

        final UserModel user= (UserModel) this.getItem(i);
        mtextView1.setText(user.getUsername());
        mtextView2.setText(user.getUserphone());
        mtextView3.setText(user.getUseremail());

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                UsersDatabaseAdapter usersDB = new UsersDatabaseAdapter(c);
                usersDB.deleteEntry(user.getID());
                users.remove(i);
                notifyDataSetChanged();
            }
        });

        return view;
    }
}

Kết luận

Như vậy chúng ta đã hoàn thành toàn bộ các phần code giao diện và phần code lập trình cần thiết để ứng dụng quản lý người sử dụng có thể thực hiện. Bạn có thể xem thêm các dòng comment để hiểu thêm về các đoạn code.

Chúc các bạn thành công!

Có thể bạn sẽ thích…

Trả lời

EnglishVietnamese