Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Sqlite+RecyclerView+Dialog to add, delete, modify and check data

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

Editor to share with you how to use Sqlite+RecyclerView+Dialog to add, delete, modify and check the data. I hope you will get something after reading this article. Let's discuss it together.

The original title requires:

(1) through the "add contact" button, jump to the Dialog of the "add" information to enter the user name, contact number and address to select the gender, and then display it in the contact list.

(2) Click the item in the contact to pop up Dialog, modify the contact information or delete the contact.

(3) the contact information can be found by entering the name, and the information is given.

Description

1. This blog post is the code part. There are some details about the implementation. Interested students can take a look at this blog post.

two。 It is recommended to read the authoritative Guide to Android programming 3, in which the format of Sqlite code is worth learning, or the code style of the whole book is worth learning.

3. I will keep updating my homework and keep an eye on not getting lost.

Effect picture

Code

Directory structure

This is my directory structure, the adapter under the adapter package, the interface and implementation methods to access the database under the dao package, some classes about the database under the database package, the custom dialog box under the dialog package, and the data model under the model package.

Add dependency

Because RecyclerView is used, you have to add dependencies

Implementation 'com.android.support:recyclerview-v7:28.0.0'

one

Specific code

1.User.java

Public class User {

Private UUID id

Private String name

Private String phone

Private String address

Private int sex

Public User () {

}

Public UUID getId () {

Return id

}

Public void setId (UUID id) {

This.id = id

}

Public String getName () {

Return name

}

Public void setName (String name) {

This.name = name

}

Public String getPhone () {

Return phone

}

Public void setPhone (String phone) {

This.phone = phone

}

Public String getAddress () {

Return address

}

Public void setAddress (String address) {

This.address = address

}

Public int getSex () {

Return sex

}

Public void setSex (int sex) {

This.sex = sex

}

Public User (UUID id, String name, String phone, String address, int sex) {

This.id = id

This.name = name

This.phone = phone

This.address = address

This.sex = sex

}

Public User (String name, String phone, String address, int sex) {

This.id = UUID.randomUUID ()

This.name = name

This.phone = phone

This.address = address

This.sex = sex

}

}

2.UserCursorWrapper.java

Public class UserCursorWrapper extends CursorWrapper {

/ * *

* Creates a cursor wrapper.

*

* @ param cursor The underlying cursor to wrap.

, /

Public UserCursorWrapper (Cursor cursor) {

Super (cursor)

}

Public User getUser () {

/ / get each row of data

String uuidString = getString (getColumnIndex (UserDbSchema.UserTable.Columns.UUID))

String name = getString (getColumnIndex (UserDbSchema.UserTable.Columns.NAME))

String phone = getString (getColumnIndex (UserDbSchema.UserTable.Columns.PHONE))

String address = getString (getColumnIndex (UserDbSchema.UserTable.Columns.ADDRESS))

Int sex = getInt (getColumnIndex (UserDbSchema.UserTable.Columns.SEX))

Return new User (UUID.fromString (uuidString), name,phone,address,sex)

}

}

3.UserDbSchema.java

Public class UserDbSchema {

/ / define user table structure using inner classes

Public static final class UserTable {

/ / define the table name

Public static final String TABLE_NAME = "user"

/ / define datasheet fields

Public static final class Columns {

Public static final String UUID = "uuid"

Public static final String NAME = "name"

Public static final String PHONE = "phone"

Public static final String ADDRESS = "address"

Public static final String SEX = "sex"

}

}

}

4.UserSqlHelper.java

Public class UserSqlHelper extends SQLiteOpenHelper {

Private static final int VERSION = 1 / definition version

Private static final String DATABASE_NAME = "course21DataBase"

Public UserSqlHelper (Context context) {

Super (context, DATABASE_NAME, null, VERSION)

}

@ Override

Public void onCreate (SQLiteDatabase db) {

/ * *

At this point, the database is not created or opened.

Until one of the getReadableDatabase,getWritableDatabase methods is called

, /

Db.execSQL ("create table" + UserDbSchema.UserTable.TABLE_NAME+

"(" + "_ id integer primary key autoincrement," +

UserDbSchema.UserTable.Columns.UUID+ "," +

UserDbSchema.UserTable.Columns.NAME+ "," +

UserDbSchema.UserTable.Columns.PHONE+ "," +

UserDbSchema.UserTable.Columns.ADDRESS+ "," +

UserDbSchema.UserTable.Columns.SEX+ ")"

);

}

@ Override

Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {

/ / do not update the database

}

}

5.IUserDao.java

Public interface IUserDao {

/ * *

* get all user information

* * /

ArrayList getAllUser ()

/ * *

* get the user information with the specified name. The default name is not duplicated.

* * /

User getUserByName (String name)

/ * *

* add user information

* * /

Void addUser (User user)

/ * *

* modify specified user information

* * /

Void updateUser (User user)

/ * *

* Delete specified user information

* * /

Void deleteUser (User user)

}

6.UserDao.java

Public class UserDao implements IUserDao {

Private static UserDao sUserDao

Private Context mContext

Private SQLiteDatabase mDatabase

Public UserDao (Context context) {

MContext = context.getApplicationContext ()

MDatabase = new UserSqlHelper (mContext) .getWritableDatabase (); / / the database is writable at this time

}

/ * *

* keep one userDao instance globally

* * /

Public static UserDao getUserDao (Context context) {

If (sUserDao = = null) {

SUserDao = new UserDao (context)

}

Return sUserDao

}

/ * *

* get all user information

, /

@ Override

Public ArrayList getAllUser () {

ArrayList users = new ArrayList ()

UserCursorWrapper cursorWrapper = queryUsers (null,null)

Try {

CursorWrapper.moveToFirst ()

While (! cursorWrapper.isAfterLast ()) {

Users.add (cursorWrapper.getUser ())

CursorWrapper.moveToNext ()

}

} finally {

CursorWrapper.close ()

}

Return users

}

/ * *

* get the user information with the specified name. The default name is not duplicated.

*

* @ param name

, /

@ Override

Public User getUserByName (String name) {

/ / define query conditions

String whereClause = UserDbSchema.UserTable.Columns.NAME + "=?"

String [] whereArgs = new String [] {name}

UserCursorWrapper cursorWrapper = queryUsers (whereClause,whereArgs)

Try {

/ / query failed

If (cursorWrapper.getCount () = = 0) {

Return null

}

CursorWrapper.moveToFirst ()

Return cursorWrapper.getUser ()

} finally {

/ / close

CursorWrapper.close ()

}

}

/ * *

* add user information

*

* @ param user

, /

@ Override

Public void addUser (User user) {

/ / prevent null values from being passed in

If (usernames are null) {

ContentValues values = getContentValues (user)

/ / insert data

MDatabase.insert (UserDbSchema.UserTable.TABLE_NAME,null,values)

}

}

/ * *

* modify specified user information

*

* @ param user

, /

@ Override

Public void updateUser (User user) {

String uuidString = user.getId () .toString ()

ContentValues values = getContentValues (user)

MDatabase.update (UserDbSchema.UserTable.TABLE_NAME

Values

UserDbSchema.UserTable.Columns.UUID+ "=?"

New String [] {uuidString})

}

/ * *

* Delete specified user information

*

* @ param user

, /

@ Override

Public void deleteUser (User user) {

String uuidString = user.getId () .toString ()

MDatabase.delete (UserDbSchema.UserTable.TABLE_NAME

UserDbSchema.UserTable.Columns.UUID+ "=?"

New String [] {uuidString})

}

/ / Private method, which returns a ContentValues object

Private ContentValues getContentValues (User user) {

ContentValues values = new ContentValues ()

/ / add key-value pairs

Values.put (UserDbSchema.UserTable.Columns.UUID,user.getId () .toString ())

Values.put (UserDbSchema.UserTable.Columns.NAME,user.getName ())

Values.put (UserDbSchema.UserTable.Columns.PHONE,user.getPhone ())

Values.put (UserDbSchema.UserTable.Columns.ADDRESS,user.getAddress ())

Values.put (UserDbSchema.UserTable.Columns.SEX,user.getSex ())

Return values

}

/ * *

* query the record and return a CursorWrapper object. You can call the getUser () method in it to get the user value.

*

* this method can be called regardless of whether the query is special or all

, /

Private UserCursorWrapper queryUsers (String whereClause,String [] whereArgs) {

Cursor cursor = mDatabase.query (

UserDbSchema.UserTable.TABLE_NAME

Null

WhereClause

WhereArgs

Null

Null

Null

);

Return new UserCursorWrapper (cursor)

}

}

7.UserAdapter.java

Public class UserAdapter extends RecyclerView.Adapter {

Private ArrayList mUsers

Private Context mContext;// context object

Private LayoutInflater mInflater

Private DialogListener mListener = new DialogListener () {

@ Override

Public void sendMessage () {

UpdateView ()

}

}

Public UserAdapter (Context context,ArrayList users) {

MUsers = users

MContext = context

MInflater = LayoutInflater.from (mContext)

}

@ NonNull

@ Override

Public ViewHolder onCreateViewHolder (@ NonNull ViewGroup parent, int viewType) {

View view = mInflater.inflate (R.layout.info_item, parent, false)

ViewHolder holder = new ViewHolder (view)

Return holder

}

@ Override

Public void onBindViewHolder (@ NonNull ViewHolder holder,int position) {

/ / mPosition = position

Final User user = mUsers.get (position)

/ / gender determination photos

Holder.mImageView.setImageResource (user.getSex () = = 1?R.drawable.boy:R.drawable.girl)

Holder.mTextViewPhone.setText (phone: + user.getPhone ())

Holder.mTextViewName.setText (user.getName ())

Holder.mTextViewAddress.setText (address: + user.getAddress ())

/ / A dialog box pops up after clicking

Holder.itemView.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

UpdateDialog dialog = new UpdateDialog (mContext,user,mListener)

Dialog.show ()

}

});

}

Public void updateView () {

MUsers = UserDao.getUserDao (mContext). GetAllUser ()

NotifyDataSetChanged ()

}

@ Override

Public int getItemCount () {

Return mUsers.size ()

}

Class ViewHolder extends RecyclerView.ViewHolder {

Public ImageView mImageView

Public TextView mTextViewName,mTextViewAddress,mTextViewPhone

Public ViewHolder (@ NonNull View itemView) {

Super (itemView)

MImageView = itemView.findViewById (R.id.info_image)

MTextViewName = itemView.findViewById (R.id.info_name)

MTextViewAddress = itemView.findViewById (R.id.info_address)

MTextViewPhone = itemView.findViewById (R.id.info_phone)

}

}

}

8.AddDialog.java

Public class AddDialog extends Dialog {

Private EditText mEditTextName,mEditTextAddress,mEditTextPhone

Private Button mButtonAdd,mButtonCancel

Private RadioGroup mRadioGroup

Private int sex = 1 / gender

Private Context mContext

Private DialogListener mListener

Public AddDialog (@ NonNull Context context, DialogListener listener) {

Super (context)

This.mContext = context

This.mListener = listener

}

@ Override

Protected void onCreate (Bundle savedInstanceState) {

Super.onCreate (savedInstanceState)

SetContentView (R.layout.add_dialog_layout)

InitView ()

MRadioGroup.setOnCheckedChangeListener (new RadioGroup.OnCheckedChangeListener () {

@ Override

Public void onCheckedChanged (RadioGroup group, int checkedId) {

Switch (checkedId) {

Case R.id.add_radio_sex_boy:

Sex = 1

Break

Case R.id.add_radio_sex_girl:

Sex = 0

Break

}

}

});

MButtonCancel.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

Dismiss ()

}

});

MButtonAdd.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

String name = mEditTextName.getText () .toString ()

String address = mEditTextAddress.getText () .toString ()

String phone = mEditTextPhone.getText () .toString ()

User user = new User (name,phone,address,sex)

UserDao.getUserDao (mContext) .addUser (user)

MListener.sendMessage ()

Dismiss ()

}

});

SetCanceledOnTouchOutside (false)

}

/ / initialization interface

Private void initView () {

MEditTextName = findViewById (R.id.edit_add_name)

MEditTextAddress = findViewById (R.id.edit_add_address)

MEditTextPhone = findViewById (R.id.edit_add_phone)

MButtonAdd = findViewById (R.id.button_add_add)

MButtonCancel = findViewById (R.id.button_add_cancel)

MRadioGroup = findViewById (R.id.add_radio_sex)

}

}

9.AddDialog corresponding layout add_dialog_layout.xml

10. UpdateDialog.java

Public class UpdateDialog extends Dialog {

The information to be displayed in the public User mUser;// pop-up box

Private EditText mEditTextName,mEditTextAddress,mEditTextPhone

Private Button mButtonUpdate,mButtonDelete,mButtonCancel

Private RadioGroup mRadioGroup

Private int sex

Private ImageView mImageView

Private DialogListener mListener

Private Context mContext

Public UpdateDialog (@ NonNull Context context,User user, DialogListener listener) {

Super (context)

This.mUser = user

This.mContext = context

This.mListener = listener

}

@ Override

Protected void onCreate (Bundle savedInstanceState) {

Super.onCreate (savedInstanceState)

SetContentView (R.layout.update_dialog_layout)

InitView ()

MRadioGroup.setOnCheckedChangeListener (new RadioGroup.OnCheckedChangeListener () {

@ Override

Public void onCheckedChanged (RadioGroup group, int checkedId) {

Switch (checkedId) {

Case R.id.update_radio_sex_boy:

Sex = 1

Break

Case R.id.update_radio_sex_girl:

Sex = 0

Break

}

}

});

/ / Delete button operation

MButtonDelete.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

UserDao.getUserDao (mContext) .delete user (mUser)

MListener.sendMessage ()

Dismiss ()

}

});

MButtonCancel.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

Dismiss ()

}

});

MButtonUpdate.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

/ / tag = 2

String name = mEditTextName.getText () .toString ()

String address = mEditTextAddress.getText () .toString ()

String phone = mEditTextPhone.getText () .toString ()

User user = new User (mUser.getId (), name,phone,address,sex)

UserDao.getUserDao (mContext) .updateUser (user)

MListener.sendMessage ()

Dismiss ()

}

});

SetCanceledOnTouchOutside (false)

}

/ / initialization interface

Private void initView () {

MEditTextName = findViewById (R.id.edit_update_name)

MEditTextAddress = findViewById (R.id.edit_update_address)

MEditTextPhone = findViewById (R.id.edit_update_phone)

MButtonUpdate = findViewById (R.id.button_update_update)

MButtonCancel = findViewById (R.id.button_update_cancel)

MButtonDelete = findViewById (R.id.button_update_delete)

MRadioGroup = findViewById (R.id.update_radio_sex)

MImageView = findViewById (R.id.image_update)

Sex = mUser.getSex ()

/ / initialize the content

MRadioGroup.check (mUser.getSex () = = 1?R.id.update_radio_sex_boy:R.id.update_radio_sex_girl)

MEditTextName.setText (mUser.getName ())

MEditTextPhone.setText (mUser.getPhone ())

MEditTextAddress.setText (mUser.getAddress ())

MImageView.setImageResource (mUser.getSex () = = 1?R.drawable.boy:R.drawable.girl)

}

}

11. UpdateDialog corresponding layout update_dialog_layout.xml

12 DialogListener.java

Public interface DialogListener {

Void sendMessage ()

}

one

two

three

13.MainActivity.java

Public class MainActivity extends AppCompatActivity {

Private Button mButtonAdd

Private RecyclerView mRecyclerView

Private UserAdapter mAdapter

Private ArrayList mUsers

Private ImageView mImageView

Private EditText mEditText

Private DialogListener mListener = new DialogListener () {

@ Override

Public void sendMessage () {

MAdapter.updateView ()

}

}

@ Override

Protected void onCreate (Bundle savedInstanceState) {

Super.onCreate (savedInstanceState)

SetContentView (R.layout.activity_main)

GetSupportActionBar () .hide ()

Init ()

InitData ()

MRecyclerView.setLayoutManager (new LinearLayoutManager (MainActivity.this))

MAdapter = new UserAdapter (MainActivity.this,mUsers)

MRecyclerView.setAdapter (mAdapter)

MButtonAdd.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

New AddDialog (MainActivity.this,mListener) .show ()

}

});

/ / Click to find

MImageView.setOnClickListener (new View.OnClickListener () {

@ Override

Public void onClick (View v) {

String name = mEditText.getText () .toString ()

If (name.equals ("")) {

Toast.makeText (MainActivity.this, query name is not allowed to be empty, Toast.LENGTH_SHORT) .show ()

} else {

User user = UserDao.getUserDao (MainActivity.this) .getUserByName (name)

UpdateDialog dialog = new UpdateDialog (MainActivity.this,user,mListener)

Dialog.show ()

}

}

});

}

Private void init () {

MButtonAdd = findViewById (R.id.main_button_add)

MRecyclerView = findViewById (R.id.main_recycler_view)

MEditText = findViewById (R.id.main_edit_name)

MImageView = findViewById (R.id.main_image_find)

}

Void initData () {

MUsers = UserDao.getUserDao (MainActivity.this). GetAllUser ()

}

}

14. Master layout file activity_main.xml

15. Sub-layout file info_item.xml

After reading this article, I believe you have a certain understanding of "how to use Sqlite+RecyclerView+Dialog to add, delete, modify and query data". If you want to know more about it, welcome to follow the industry information channel, thank you for your reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report