首先上图看效果,由于不能上传视频,多图预警,支持增,删,改,查,搜索。由于篇幅有限,有些xml文件不能上传,想要整个工程可以进行下载,或者私信俺。如果不会xutil数据库操作,可以先进行学习
在这里只贴出,java代码
首先得添加框架依赖
implementation 'com.facebook.stetho:stetho:1.5.1'
implementation 'org.xutils:xutils:3.8.5'
implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.2' //1.0.5及以前版本的老用户升级需谨慎,API改动过大
implementation 'com.scwang.smartrefresh:SmartRefreshHeader:1.1.2' //没有使用特殊Header,可以不加这行
第一个activity.java代码
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.telephony.CellSignalStrength;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.stetho.Stetho;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import org.xutils.DbManager;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.x;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
static DbManager.DaoConfig daoConfig;
//用来增加数据使用,表示id
static int nums;
//用来表示是新建还是修改
static boolean flag=true;
//切换布局
static boolean flagRecycle=true;
static MyAdapter myAdapter;
static List<Messages> users;
static List<Messages> userstemp;
static RecyclerView recyclerView;
Messages messages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Stetho.initializeWithDefaults(this);
x.Ext.init(getApplication());
x.Ext.setDebug(BuildConfig.DEBUG);// 是否输出debug日志, 开启debug会影响性能.
x.view().inject(this);//没有用到view注解可以先不用
final EditText editText=findViewById(R.id.editText2);
//数据库创建
daoConfig= new DbManager.DaoConfig()
.setDbName("messages.db")
// 不设置dbDir时, 默认存储在app的私有目录.
// .setDbDir(new File("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
.setDbVersion(1)
.setDbOpenListener(new DbManager.DbOpenListener() {
@Override
public void onDbOpened(DbManager db) {
// 开启WAL, 对写入加速提升巨大
db.getDatabase().enableWriteAheadLogging();
}
})
.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
// TODO: ...
// db.addColumn(...);
// db.dropTable(...);
// ...
// or
// db.dropDb();
}
});
//查询所有的数据,并显示到recycleview
DbManager db = null;
try {// 删除1
db = x.getDb(daoConfig);
users= new ArrayList<>();
users= db.selector(Messages.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).findAll();
nums=users.size();
} catch (DbException e) {
e.printStackTrace();
return;
}
// 搜索
Button button=findViewById(R.id.button6);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText seachEdit=findViewById(R.id.editText);
String seachContent=seachEdit.getText().toString();
DbManager db = null;
try {// 删除1
db = x.getDb(daoConfig);
List<Messages> newMessge = new ArrayList<>();
String sql="select * from Messages where content like "+"'%"+seachContent+"%'";
Cursor cursor= db.execQuery(sql);
while (cursor.moveToNext()){
Messages m=new Messages();
String seachmess=cursor.getString(1);
m.setContent(seachmess);
String seachdate=cursor.getString(2);
m.setDate(seachdate);
int seachid=cursor.getInt(0);
m.setId(seachid);
newMessge.add(m);
Log.i("hhhh", "onClick: sousuo"+m.getContent()+" "+m.getDate()+" "+seachContent);
}
cursor.close();
// newMessge=db.selector(Messages.class).orderBy("id", true).where("content","like","%"+seachContent+"%").findAll();
users=newMessge;
myAdapter.notifyDataSetChanged();
seachEdit.setText("");
// users= db.selector(User.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).findAll();
} catch (DbException e) {
e.printStackTrace();
return;
}
}
});
// 跳转到编写页面
Button button2 =findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flag=false;
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
Log.i("hhhhh", "onClick: ");
}
});
myAdapter = new MyAdapter();
recyclerView =findViewById(R.id.recyclerView);
recyclerView.setAdapter(myAdapter);
//设置边距
HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.TOP_DECORATION,30);//top间距
stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION,50);//底部间距
stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.LEFT_DECORATION,50);//左间距
stringIntegerHashMap.put(RecyclerViewSpacesItemDecoration.RIGHT_DECORATION,50);//右间距
recyclerView.addItemDecoration(new RecyclerViewSpacesItemDecoration(stringIntegerHashMap));
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
// 刷新
RefreshLayout refreshLayout = findViewById(R.id.refreshLayout);
refreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
DbManager db = null;
try {// 删除1
db = x.getDb(daoConfig);
users= new ArrayList<>();
users= db.selector(Messages.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).orderBy("id", true).limit(1000).findAll();
// users= db.selector(User.class).findAll();
nums=users.size();
} catch (DbException e) {
e.printStackTrace();
return;
}
myAdapter.notifyDataSetChanged();
refreshlayout.finishRefresh(2000);//传入false表示刷新失败
}
});
refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(RefreshLayout refreshlayout) {
myAdapter.notifyDataSetChanged();
refreshlayout.finishLoadMore(2000);//传入false表示加载失败
}
});
// 切换布局
Button button4=findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flagRecycle) {//如果为真,代表线性布局,设置为网格布局
flagRecycle=false;
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2, LinearLayoutManager.VERTICAL, false));
}else {
flagRecycle=true;
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
});
}
public class MyViewHolder extends RecyclerView.ViewHolder{//用来包装每个子项的布局信息
public TextView textView1;
public TextView textView2;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textView1=itemView.findViewById(R.id.textView1);
textView2=itemView.findViewById(R.id.textView2);
}
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
//用来配合recycleview进行加载子项以及填充子项的数据
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, final int viewType) {
final View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item1,parent,false);
final MyViewHolder myViewHolder = new MyViewHolder(view);
//设置子项item监听
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Messages user=new Messages();
//// user.setId();
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
int id=myViewHolder.getAdapterPosition();//得到item的编号,位置
// String date=users.get(id).getDate();
// String content=users.get(id).getContent();
//跳转页面并实现传递参数
intent.putExtra("mess",id);
// Log.i("hhhh", "onClick: "+id+" "+users.get(id).getContent());
startActivity(intent);
}
});
// 设置监听
// view.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//// Messages user=new Messages();
//// user.setId();
// Intent intent=new Intent(MainActivity.this,Main2Activity.class);
//// intent.putExtra("user",users.get())
// Log.i("hhhh", "onClick: "+view.getTag());
// startActivity(intent);
// }
// });
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {//在这里进行子项的文本图片数据填充
holder.textView1.setText(users.get(position).getContent());
holder.textView2.setText(users.get(position).getDate());
}
@Override
public int getItemCount() {//返回子项的数目,即加载多少列表项
return users.size();
}
}
}
第二个activity.java代码
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.stetho.Stetho;
import org.xutils.DbManager;
import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.x;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.c201801020217.tangbo.MainActivity.daoConfig;
import static com.c201801020217.tangbo.MainActivity.flag;
import static com.c201801020217.tangbo.MainActivity.myAdapter;
import static com.c201801020217.tangbo.MainActivity.nums;
import static com.c201801020217.tangbo.MainActivity.users;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Stetho.initializeWithDefaults(this);
// 返回
final Button button=findViewById(R.id.button);
// 保存
Button button2=findViewById(R.id.button7);
// 删除
final Button button3=findViewById(R.id.button5);
final TextView textViewDate=findViewById(R.id.textView);
final TextView textContent=findViewById(R.id.editText2);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());
final String time= simpleDateFormat.format(date);
textViewDate.setText(time);
// Messages messages= (Messages) getIntent().getSerializableExtra("mess");
final int id = getIntent().getIntExtra("mess", 0);
final int itemid = users.get(id).getId();
if(flag) {
String dates = users.get(id).getDate();
String content = users.get(id).getContent();
textViewDate.setText(dates);
textContent.setText(content);
}
// 保存
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DbManager db = null;
try {
if (flag) {//如果为真,代表是点击item进来的,要用更新语句而不是插入语句
//条件更新
String newcontent=textContent.getText().toString();
db = x.getDb(daoConfig);
db.update(Messages.class, WhereBuilder.b("id", "=", itemid),
// WhereBuilder.b("id", "=", 1).and("isAdmin", "=", true).,
new KeyValue("content",newcontent), new KeyValue("date", time));
users.get(id).setDate(time);
users.get(id).setContent(newcontent);
} else {
db = x.getDb(daoConfig);
Messages user = new Messages();//new 一个对象,相当于是表中的一行,相当于一条记录
//相当于插入数据
user.setId(nums + 1);
nums++;
user.setDate(time);
user.setContent(textContent.getText().toString());
db.save(user);//写入数据,保存到数据库
flag=true;
users.add(user);
// myAdapter.notifyDataSetChanged();
}
finish();
} catch (DbException e) {
e.printStackTrace();
return;
}
}
});
// 删除
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//条件删除
DbManager db = null;
try {
db = x.getDb(daoConfig);
db.delete(Messages.class,
WhereBuilder.b("id", "=", itemid));
users.remove(id);
} catch (DbException e) {
e.printStackTrace();
return;
}
finish();
}
});
//返回
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
数据库使用的java类
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
import java.util.Date;
@Table(name = "Messages")
public class Messages {
@Column(name = "id",isId=true)
private int id;
@Column(name = "date")
private String date;
@Column(name = "content")
private String content;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}