如何使用Sqlite+RecyclerView+Dialog进行数据的增删改查
原题要求:
(1)使用“添加联系人”按钮,跳转到“添加”信息对话框,输入用户名、联系电话、地址,选择性别,添加后显示在联系人列表中。
(2)点击联系人中的某一项,弹出对话框,可以修改联系人信息或删除联系人。
(3)您可以通过输入姓名并提供信息来搜索联系信息。
说明
1.这篇博文是代码部分,包含一些实现细节。有兴趣的同学可以阅读这篇博文
2.建议阅读《Android编程权威指南3》。里面的Sqlite代码的格式值得学习。也就是说,整本书的编码风格值得学习。
3.我想会继续更新作业,注意不要迷路
渲染
代码
目录结构
这是我的目录结构,adapter包下是适配器,dao包下是访问数据库的接口和实现方法,database包下是一些与数据库相关的类,dialog包下是自定义对话框,model包下是数据模型
添加依赖
由于使用了RecyclerView,所以必须添加依赖
implementation 'com.android.support:recyclerview-v7:28.0 .0'
1
具体代码
1.User.java
public类User{
私有 UUID id;
私有字符串名称; p>
私有字符串电话;
私有字符串地址;
私有 int 性别; p>
公共 User() {
}
公共 UUID getId() {
using using using using through through through through through through through ' through '' through through 's'‐‐‐‐‐‐‐‐‐‐‐‐ 返回 id; }
public String getName() {
返回名称;
}
public void setName(String name) {
>this.name = name;
}
public String getPhone() {
返回电话;
}< /p>
public void setPhone(Stringphone) {
this.phone = Phone;
}
public String getAddress() { p>
寄回地址;
返回地址; > }
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public User(UUID id, 字符串名称,字符串电话,字符串地址,int 性别){
this.id = id;
this.name = name;
this.phone = 电话;
this.address = 地址;
this.sex = 性别;
}
public User(String name, String Phone, String address, int sex) {
this.id =UUID.randomUUID();
this.name = name;
this.phone = 电话;
this.address = 地址;
this.sex = 性别;
}
}
2.UserCursorWrapper.java
public class UserCursorWrapper extends CursorWrapper {
/**
* 创建一个游标包装器。
*
* @paramcursor 要包装的基础游标。
*/
public UserCursorWrapper(Cursorcursor) {
super(cursor);
}
< p> public User getUser(){//获取每一行数据 p>
String uuidString = getString(getColumnIndex(UserDbSchema.UserTable.Columns.UUID));
< p> String name = getString(getColumnIndex(UserDbSchema.UserTable.Columns.NAME));字符串电话 = getString(getColumnIndex(UserDbSchema.UserTable.Columns.PHONE));
字符串地址 = getString(getColumnIndex(UserDbSchema.UserTable.Columns.ADDRESS));
int sex = getInt(getColumnIndex(UserDbSchema.UserTable) .Columns.SEX));
return new User(UUID.fromString(uuidString),姓名,电话,地址,性别);
}
< p>}3.UserDbSchema.java
public class UserDbSchema {
//使用内部类定义用户表结构
public STATIC FINAL CLASS Usertable {
// 定义表名
Public Static String Table_name = "User";
// 定义数据表字段
公共静态最终类列{
公共静态最终字符串UUID =“uuid”;
公共静态最终字符串NAME =“名称”;
公共静态最终字符串 PHONE = "电话";
公共静态最终字符串 ADDRESS = "地址";
公共静态最终字符串 SEX = "性别";
< p> } }}
}
4.UserSqlHelper.java p>
公共类 UserSqlHelper 扩展 SQLiteOpenHelper {
私有静态最终 int VERSION = 1; //定义版本
private static final String DATABASE_NAME = "course21DataBase";
public UserSqlHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
/**
< p> 此时数据库尚未创建或打开,直到 getReadableDatabase,getWritableDatabase 调用这两个方法之一
*/
db. execSQL("创建表 "+ UserDbSchema.UserTable.TABLE_NAME+
"("+"_id 整数主键自增,"+
UserDbSchema.UserTable.Columns.UUID+","+
UserDbSchema.UserTable.Columns.NAME+",""+
UserDbSchema.UserTable.Columns.PHONE+","+
UserDbSchema.UserTable.Columns.ADDRESS+",""+
UserDbSchema.UserTable.Columns.SEX +" )"
);
}
@覆盖
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//不更新数据库
}
}
5.IUserDao.java
公共接口IUserDao {
/**
* 获取所有用户信息
* */
ArrayList
/ **
* 获取指定名称的用户信息,默认名称不重复
* */
User getUserByName(String name);
< p> /***添加用户信息< /p>
* */
void addUser(User user);
/**
* 修改指定用户信息
* */
void updateUser(User user);
/**
* 删除指定用户信息
* */
void deleteUser(User user);
}
6.UserDao .java
公共类 UserDao 实现 IUserDao{< /p>
私有静态 UserDao sUserDao;
私有上下文 mContext;
private SQLiteDatabase mDatabase;
public UserDao(Context context) {
mContext = context.getApplicationContext();
mDatabase = new UserSqlHelper(mContext).getWritableDatabase ();//此时数据库可写
}
/**
* 全局保留一个userDao实例
* */
public static UserDao getUserDao(Context context){ p>
if (sUserDao == null){
sUserDao = new UserDao(context);< /p>
}
return sUserDao;
}
/**
* 获取所有用户信息
*/
@Override
Public ArrayList
ArrayList
UserCursorWrappercursorWrapper = queryUsers(null,null);
尝试{
cursorWrapper.moveToFirst();
Cursorwrapper.movetonext();
}
} 最后{
Cursorwrapper.close();
}
返回已使用的;
}
/**
*
* @param name
*/
@Override
public User getUserByName(String name) {
//定义查询条件
String whereeClause = UserDbSchema.UserTable.Columns.NAME + " = ?";
String [] whereArgs = new String[]{ name };
UserCursorWrappercursorWrapper = queryUsers(whereClause,whereArgs );
try {
//查询失败
if (cursorWrapper.getCount() == 0){
return null ;
。
// 关闭
Cursorwrapper.close();
}
}
/**
< p> * 添加用户信息*
< p> * @param user*/
@Override
public void addUser(User user) {
使用 using ' ' s ' t Data
mDatabase.insert(UserDbSchema.UserTable.TABLE_NAME, null, value); /p>
* 修改指定用户信息
*
* @param user
*/
@Override< / p>
public void updateUser(User user) {
String uuidString = user.getId().toString();
ContentValues 值 = getContentValues( user);
p>mDatabase.update(UserDbSchema.UserTable.TABLE_NAME,
uuidString });
}
/* *
* 删除指定用户信息
*
* @param user
*/
@Override
公共无效删除eUser(用户用户) {
String uuidString = user.getId( ).toString();
mDatabase.delete(UserDbSchema.UserTable.TABLE_NAME,
UserDbSchema.UserTable.Columns.UUID+" = ? ",
new String[] { uuidString });
}
//私有方法,返回一个ContentValues对象
private ContentValues getContentValues(User user){
ContentValues values = new ContentValues( );
//添加键值对
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());
返回值;
}
/**
*查询记录,返回一个Cursorwrapper对象,可以调用里面的getuser()方法获取User值
*
* 无论您如果你要查询具体或者全部,可以调用这个方法
*/
private UserCursorWrapper queryUsers(String whereClause,String [] whereArgs){
Cursor 光标= mDatabase.query(
UserDbSchema.UserTable.TABLE_NAME,
null,
参数,
null,
< p> null,null
);
return new UserCursorWrapper(cursor);
}
}
7.UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter
private ArrayList
private Context mContext;//上下文对象
private LayoutInflater mInflater;
private DialogListener mListener = new DialogListener() {
@Override p>
public void sendMessage() {
updateView();
}
} ;
public UserAdapter(Context context,ArrayList
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);
ViewHolderholder = new ViewHolder(view);
returnholder;
ViewHolderholder = new ViewHolder(view);
returnholder;
p>
}
@Override
public void onBindViewHolder(@NonNull ViewHolderholder,intposition) {
// mPosition =position;
p>
Final User user = mUsers.get(position);
p>//性别判断照片
holder.mImageView.setImageResource(user.getSex()== 1?R.drawable.boy:R.drawable.girl);
holder.mTextViewPhone.setText("手机:"+user.getPhone());
holder.mTextViewName .setText(user.getName());
holder.mTextViewAddress .setText("Address: "+user.getAddress());
//弹出对话框点击
持有者后.itemView.setOnClickListener(new View.OnClickListener() {
@override
Public Void OnClick (View v) {
UpdatedDialog 对话框 = new UpdatedDialog (MCONTEXT) , 用户, Mlistener);
dialog.show();
} }
});
}
public void updateView(){
mUsers = UserDao.getUserDao(mContext).getAllUser();
notificationDataSetChanged();
} p>
@Override
public int getItemCount() {
return mUsers.size();
}
类ViewHolder 扩展了 RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextViewName,mTextViewAddress,mTextViewPhone;
public ViewHolder(@NonNull View itemView) { p>
super(itemView);
mImageView = itemView.findViewById(R.id.info_image);
mTextViewName = itemView.findViewById(R.id.info_name);
mTextViewAddress = itemView.findViewById(R.id.info_address);
< p> mTextViewPhone = itemView.findViewById(R.id.info_phone);ViewById(R.id.info_phone); 执行吗? java
public class AddDialog extends Dialog {
private EditText mEditTextName,mEditTextAddress,mEditTextPhone;
private Button mButtonAdd,mButtonCancel;
private RadioGroup mRadioGroup;
private int sex = 1;//性别
private Context mContext;
private DialogListener mListener;
public AddDialog (@NonNull Context 上下文,DialogListener 监听器) {
super(context); p>
this.mContext = context;
this.mListener = 监听器; p>
}
@Override
protected void onCreate(Bundle savingInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_dialog_layout);
initView();
Mradiogroup.SetonCheckedChangelistener (New Radiogroup.OncheckedChangelistener () {
@override < p> Public VoidCheDChaanged (RA.diogroup group, int Checkid) {switch (checkedId){
case R.id.add_radio_sex_boy:
sex = 1;
break;< /p> p>
case R .id.add_radio_sex_girl:
性别 = 0;
中断;
}
}) ;
mButtonCancel.setOnClickListener(new View.OnClickListener() {
@Override< /p>
public void onClick(View v) {
; .OnClickListener () {
@override
public void onClick (view v) {
字符串名称 = MedittextName.gettext(); <); <); <); <); <); <); <); /p>
字符串地址 = mEditTextAddress.getText().toString();
字符串电话 = mEditTextPhone.getText().toString();
用户 user = new User(姓名、电话、地址、性别);
UserDao.getUserDao(mContext).addUser(user);
p>
}
//初始化接口
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对应布局add_dialog_layout.xml
android:orientation="vertical" android:layout_width="250dp" android:layout_height="400dp" android:background="#FDF5F5" > android:layout_width="match_parent" android:layout_height="80dp"> android:layout_centerInParent "true" android:text="添加联系人"/> <查看 android:layout_width="match_parent"
android android 10dp"/>
<相对L
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
ot;
android:layout_width="180dp"
android:layout_height="200dp"
android :方向=“垂直”>
<线性布局
Android:layout_width = "match_parent"
Android:layout_height = "0dp"
Layout_weight = "1">>
Android:layout_gravity =“中心”Android:layout_width =“wrap_content”
Android:layout_height =“wrap_content”/>
Edittext
&roid android :layout_height="match_parent"android:textSize="12dp"
  ; /p>
android:layout_height="0dp"
android: android: android:text=" 性别:"android:layout_marginLeft="10dp"
android:; android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
add_radio_sex"
Android:layout_width="wrap_content"
Android:layout_height =“wrap_content”
Android:layout_Gravity =“Center” P>
android:orientation =“horizontal”>
bsp; "
android:checked="true"
android:text="男" />
android:id="@+id/add_radio_sex_girl "
android:layout_width="wrap_content"
inearLayout>
Android: text = "电话:" android:layout_marginLeft="10dp" android:layout_height="包装内容“/> Android:id =“@+ID/edit_add_phone” Android:layout_width =“0dp” android:layout_height="match_parent" android:textSize="12dp" android:hint="请输入..."/> > android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> ‐ 至视图 android:text="地址:" android:text="地址:" ; android:layout_gravity="center" android:layout_width="wrap_content" EditText android:id="@+id/edit_add_address" android:layout_width="0dp" android:layout_height="match_parent" android:textSize="12dp" p> <查看 android:layout_width="match_parent" android:layout_height="1dp" android:background="#ccc" android:layout_marginLeft= "10dp" android:layout_marginRight="10dp"/> android:layout_width= "match_parent" android :layout_height="50dp"> <按钮 android:id="@+id/button_add_add" Android:layout_width = "0dp" Android:layout_gravity = "Center" Android:layout_w 八 = "3" android:布局高度=“40dp”和 android:layout_width "0dp" android:id="@+id/button_add_cancel" &nandroid:text="取消" " android:layout_gravity="center" android:textSize="12dp"/> android:layout_gravity="center" 10.UpdateDialog.java public class UpdateDialog extends Dialog { public User mUser;//弹出框中要显示的信息 private EditText mEditTextName,mEditTextAddress,mEditTextPhone; private Button mButtonUpdate,mButtonDelete,mButtonCancel; private RadioGroup mRadioGroup; private int sex; private int sex; p> private ImageView mImageView; private DialogListener mListener; private Context mContext; public UpdateDialog(@NonNull Context context,User 用户,DialogListener 监听器) { super(context); p> this.mUser = user; this.mContext = context; this.mListener = 监听器; } protected void onCreate(Bundle savingInstanceState) { 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) { 案例 R. id.Update_radio_sex_boy: Sex = 1; Break; case R.id.update_radio_sex_girl: } }); //删除按钮n 操作 mButtonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UserDao.getUserDao(mContext).deleteUser(mUser); mLListener.sendMessage(); 解雇(); @override 公共void onClick(view v) { DISMISS(); } }); < }); mButtonUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { / / tag = 2; 字符串名称 = mEditTextName.getText().toString( ); 字符串地址 = mEditTextAddress.getText().toString();
User user = new User(mUser.getId(),姓名,电话,地址,性别);
UserDao.getUserDao(mContext).updateUser(user); );
miss();> setCanceledOnTouchOutside(false);
}
//初始化接口
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() ;
//初始化内容
mRadioGroup.check(mUser.getSex()==1?R.id.update_radio_sex_boy:R.id.update_radio_sex_girl);
< p> mEditTextName.setText(mUser.getName());mEditTextPhone.setText(mUser.getPhone());
mEditTextAddress.setText(mUser.getAddress());< /p>
mImageView.setImageResource(mUser.getSex()==1? R.drawable.boy:R.drawable.girl);
}
}
11. UpdateDialog对应布局update_dialog_layout.xml
android:orientation="vertical" android:layout_width="250dp" android:layout_height="400dp"
android:layout_width="match_parent" android:layout_height="80dp">< /p> android:id="@+id/image_update" android:src="@drawable/girl" android:layout_centerInParent="true" android:layout_width="60dp" android:layout_height="60dp"/>
<视图
android:layout_width="match_parent"
android:layout_height= "1dp"
android:background="#ccc"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
android:layout_width= “match_parent” android:layout_height="0dp" android:layout_weight="1"> 和 /p> android:layout_width="180dp" android :layout_height="200dp" android:orientation="vertical"> LinearLayout android:layout_width="match_parent" p> android:layout_marginLeft="10dp"
android:id="@+id/edit_update_name"
:layout_height = "match_parent"
Android: TextSize = "12dp"/>
线性布局t>
<线性布局
Android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight= "1">
&roid:textView p> android:layout_width="wrap_content"
android:id="@+id/ update_radio_sex" p>android:layout_width=" wrap_content"
Android:layout_height = "wrap_content"
Android:layout_gravity = "center"
Android: 方向 = "水平">
<单选按钮android:id="@+id/update_radio_sex_boy"
android:layout_width="wrap_content"
android:lay out_height="wrap_content" < /p>
android:checked="true"
android:text="男" />
width="wrap_content"
Android:layout_height = "wrap_content"
Android: text = "female"/>
LinearLayout>
_parent"
android:layout_height="0dp" android: text ="电话:"
android:layout_width="包裹内容“
android:layout_height="wrap_content"/>
android:nbsp;android:id="@+id/edit_update_phone"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height = “match_parent”
Android:TextSize = “12dp”/>
线性布局>
<线性布局
Android:layout_width= "match_parent"
android:layout_height="0dp"
android:layout_weight="1">
&roid:textView p> android:layout_宽度=“wrap_content” "
android:id="@+id/edit_update_address"android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:textSize="12dp"/>
p>
<视图
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ccc"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
android:layout_width="match_parent" android:layout_height="50dp">
android:id="@+id/button_update_delete"
android:textSize="12dp"
android:layout_width="0dp"
android:layout_gravity="center"
Android:layout_height = "40dp"
Android: Text = "删除"/ >
Android:layout_width = "0dp"
android:layout_weight="1"
android:layout_height="match_parent"/ >
android: android :text="修改"
android:textSize="12dp"/>
android: p> android:layout_weight="1"
android:layout_height="
Android: id = "@+ ID/button_cancel"
Android: text = "取消"
android: android : “中心” p>
android:textSize="12dp"/>
12 DialogListener .java
公共接口DialogListener {
void sendMessage();
}
1
2
3
13.MainActivity.java
public class MainActivity extends AppCompatActivity{
private Button mButtonAdd;
private RecyclerView mRecyclerView;< /p>
私有 UserAdapter mAdapter;
私有 ArrayList
私有 ImageView mImageView ;
private EditText mEditText;
private DialogListener mListener = new DialogListener() {
@Override
public void sendMessage() {
mAdapter .updateView();捆绑savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();< /p>
init();
initData();
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mAdapter = new UserAdapter(MainActivity.this,mUsers);
mRecyclerView.setAdapter(mAdapter);
P>mbuttonaddd.SetonClickListener(New View.onClickListener() {
@override
Public Void Onclick(视图 V){
新建 AddDialog (MainActivity.this,mListener).show();
mListener)(新点击查看Listener() {
@Override
public void onClick(View v) {
String name = mEditText.getText().toString(); p>
if (name.equals("")){
Toast.makeText(MainActivity.this,"查询名称不允许为空",Toast.LENGTH_SHORT).show( );
。
UpdateDialog 对话框 = new UpdateDialog(MainActivity.this,user,mListener);
对话框.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.获取用户Dao(MainActivity.this).getAllUser();
}
}
14.主布局文件activity_main.xml
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="垂直"> android:layout_width="match_parent" android:layout_height="60dp"> android:id="@+id/main_edit_name" android:layout_gravity="bottom" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight= "3" android:hint="请输入您要查询的名称" android:layout_marginRight="10dp" /> android:p; android:layout_weight="1"> 可绘制/查找" ndroid:layout_width="35dp" android:layout_height="35dp" android:layout_centerInParent="true"/> p> p> android:id="@+id /main_recycler_view" android :layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> <按钮 android:layout_width="match_parent" android:layout_height="40dp" android: text="添加联系人"/>
15.子布局文件info_item.xml
android:orientation="vertical" android:layout_width="match_parent" p> android:layout_height="100dp"> android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> android:background="#F8F4D3" android:layout_width="80dp" 和 info_image" android:layout_centerInParent="true" android:src="@drawable/girl" android:layout_width="60dp" 安卓:layout_height="60dp"/> " android:background="#E1F5EC" android :layout_height="match_parent" <线性布局 Android:layout_width = "match_parent" Android:layout_height = "0dp" Layout_weight = "2">> 2 "> android:layout_height="wrap_content" < /p> android:layout_gravity="center" android:textColor="#333"/>< /p>
android: layout_weight= "1"
Android: id = "@+ID/info_phone " Android:layout_gravity = "center"
android:text="电话: 1322222 40503" android:layout_width="wrap_content"
info_address ”
Android:layout_gravity =“中心”
一个droid: text="地址:江苏苏州"
Android:layout_Marginleft="10dp"
< /LinearLayout>
android:layout_height="1dp"
android:background="#666"/>
LinearLayout>
读完这篇文章,相信你对“如何使用Sqlite+RecyclerView+Dialog进行数据的增删改查”有了一定的了解。如果您想了解更多相关知识,请关注行业资讯频道。谢谢你们。阅读!
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 编程技术 > 如何使用Sqlite+RecyclerView+Dialog进行数据的增删改查