一般常见于安卓客户端。用于存储一些重要数据,因其操作容易、使用简单的好处博得一大批迷妹。今天就来说一说sqlite一些简单的使用方法。
先来效果图,因为我觉得没有效果图的文章基本上都是没有什么卵用。
一步一步开始做吧,我先创建个项目,主要是使用sqlite的代码。
ok,当需求步骤明确后,先开始第一步,创建数据库并新建user表:
//初次运行,创建数据库并新建user表(username+password字段,并设置userid主键)
SQLiteDB.getInstance(this);
注:activity调用一下就可以了;
public class SQLiteDB {
/** 数据库名 */
public static final String DB_NAME = "SQLite_Test";
/** 数据库版本 */
public static final int VERSION = 1;
/** 数据库 */
private static SQLiteDB sqliteDB;
private SQLiteDatabase db;
private SQLiteDB(Context context) {
/** 初始化数据库 */
OpenHelper dbHelper = new OpenHelper(context, DB_NAME, null, VERSION);
/** 获取db */
db = dbHelper.getWritableDatabase();
}
/**
* 获取SqliteDB实例
* @param context
*/
public synchronized static SQLiteDB getInstance(Context context) {
if (sqliteDB == null) {
sqliteDB = new SQLiteDB(context);
}
return sqliteDB;
}
}
package com.cc.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by admin on 2018/6/11.
*/
public class OpenHelper extends SQLiteOpenHelper {
//建表语句(创建用户表)
public static final String CREATE_USER = "create table user ("
+ "userid integer primary key autoincrement, "
+ "username text, "
+ "password text)";
/**
* 构造方法
* @param context
* @param name
* @param factory
* @param version
*/
public OpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
}
/**
* 初次创建
* @param db
*/
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_USER);//创建用户表
}
/**
* 当数据库版本出现改变时
* @param db
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
建库建表的代码就是这样,当app运行之后,名为SQLite_Test的数据库里面就有了一张user表。
user表里面有3个参数:userid 主键、username、password
当数据库和表创建好之后,开始对表进行操作:
首先:增加数据
int temdId = v.getId();
if(temdId == R.id.bt_add){
addDialog();
}
/**
* add
*/
private void addDialog() {
new CommomDialog(this, R.style.dialog, "add", new CommomDialog.OnCloseListener() {
@Override
public void onClick(Dialog dialog, boolean confirm, UserInfo us) {
if(confirm){
//调用save方法添加数据
int result = SQLiteDB.getInstance(MainActivity.this).saveUser(us);
if(result == 1){
Log.i("add", "succ");
dialog.dismiss();
selDialog();
}
}
}
},1).setTitle("提示").show();
}
注:自定义dialog弹框进行数据的添加;
自定义dialog界面:
public CommomDialog(Context context, int themeResId, String content, OnCloseListener listener, int position, List userInfo, int num) {
super(context, themeResId);
this.mContext = context;
this.content = content;
this.listener = listener;
this.position = position;
this.userInfo = userInfo;
this.num = num;
}
并在自定义dialog里面的onCreate启动方法中添加xml布局文件并且初始化控件:
//add
setContentView(R.layout.dialog);
add_initView();
/**
*add
*/
private void add_initView() {
add_usn = findViewById(R.id.txt_username);
add_psd = findViewById(R.id.txt_password);
Button add_ok = findViewById(R.id.add_ok);
Button add_no = findViewById(R.id.add_no);
add_ok.setOnClickListener(this);
add_no.setOnClickListener(this);
}
//设置点击事件,并设置回调处理新增逻辑
int temdId = v.getId();
if(temdId == R.id.add_ok){
if(listener != null){
us.setUsername(add_usn.getText().toString().trim());
us.setPassword(add_psd.getText().toString().trim());
listener.onClick(this, true, us);
}
}else if(temdId == R.id.add_no){
if(listener != null){
listener.onClick(this, false, us);
}
this.dismiss();
}
注:以上为新增步骤和逻辑;
第二步:新增数据后,通过查询让新增的数据显示出来在listview上,便于后续操作:
先把下拉刷新的jar包放出来:下拉刷新下载地址
/**
* sel全部
*/
private void selDialog() {
showPross();
}
private void showPross() {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("正在查询User信息中...");
dialog.show();
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
int progress = 0;
@Override
public void run() {
progress += 1;
if (progress == 3) {
timer.cancel();
dialog.dismiss();
Intent intent = new Intent(MainActivity.this, ListViewActivity.class);
startActivity(intent);
}
}
}, 0, 1000);
}
注:通过一个定时器跳转到ListViewActivity中去加载数据
ListViewActivity.class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
switchPreference = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayout);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
initData();
}
private void initData() {
//第一个参数表示刷新的那个圈是否缩放
//第二个表示下来的最低位置
//第三个表示下来的最高位置
switchPreference.setProgressViewOffset(true, 10, 15);
//刷新的颜色
switchPreference.setColorSchemeResources(R.color.colorAccent);
//
switchPreference.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//因为涉及到主线程刷新,所以还是走runnable吧
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.d("TAG", "加载刷新后的数据");
recyAdapter.notifyDataSetChanged();
//停止刷新
switchPreference.setRefreshing(false);
}
}, 3000);
}
});
//查询所有的user对象
userInfos = SQLiteDB.getInstance(this).getUsers();
//根据userid查询user对象
// userInfos = SQLiteDB.getInstance(this).selectByIdUser("2");
Log.i("sel", "succ" + userInfos.get(0).getUsername());
recyAdapter = new RecyAdapter(userInfos);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(recyAdapter);
}
package com.cc.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cc.activity.R;
import com.cc.info.UserInfo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 2018/6/12.
*/
public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.ViewHolder> {
List userInfos = new ArrayList<>();
public RecyAdapter(List users){
this.userInfos = users;
}
/**
* 加载xml布局小文件
* @param viewGroup
* @param i
* @return
*/
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sel_item, viewGroup, false);
return new ViewHolder(view);
}
/**
* 绑定数据
* @param viewHolder
* @param i
*/
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.txt_item_user_id.setText(String.valueOf(userInfos.get(i).getUserid()));
viewHolder.txt_item_username.setText(userInfos.get(i).getUsername());
viewHolder.txt_item_password.setText(userInfos.get(i).getPassword());
}
/**
* 绑定数据
* @param viewHolder
* @param i
*/
/**
* 加载小文件的个数
* 来个6
* @return
*/
@Override
public int getItemCount() {
if(userInfos == null){
return 0;
}
return userInfos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout lin_manager;
TextView txt_item_user_id, txt_item_username, txt_item_password, txt_item_age, txt_item_address;
public ViewHolder(final View view) {
super(view);
lin_manager = view.findViewById(R.id.lin_manager);
txt_item_user_id = view.findViewById(R.id.txt_item_user_id);
txt_item_username = view.findViewById(R.id.txt_item_username);
txt_item_password = view.findViewById(R.id.txt_item_password);
txt_item_age = view.findViewById(R.id.txt_item_age);
txt_item_address = view.findViewById(R.id.txt_item_address);
txt_item_user_id.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Linster.textItemOnClick(v, getPosition());
}
});
lin_manager.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Linster.textItemOnClick(v, getPosition());
}
});
lin_manager.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
LongLinster.textItemOnLongClick(v, getPosition());
return false;
}
});
}
}
public ItemOnClickLinster Linster;
public void setLinster(ItemOnClickLinster linster) {
Linster = linster;
}
public interface ItemOnClickLinster{
void textItemOnClick(View view, int position);
}
public ItemOnLongClickLinster LongLinster;
public void setlongLinster(ItemOnLongClickLinster longLinster) {
LongLinster = longLinster;
}
public interface ItemOnLongClickLinster{
void textItemOnLongClick(View view, int position);
}
}
注:查询步骤。
更新和删除分别使用了单击和长按事件来触发:
recyAdapter.setLinster(new RecyAdapter.ItemOnClickLinster() {
@Override
public void textItemOnClick(View view, int position) {
Log.d("TAG", "单击事件");
//修改position对应的user对象
updetaUserData(position);
}
});
recyAdapter.setlongLinster(new RecyAdapter.ItemOnLongClickLinster() {
@Override
public void textItemOnLongClick(View view, int position) {
Log.d("TAG", "长按事件");
//删除position对应的user对象
delUserData(position);
}
});
/**
* del
* @param position
*/
private void delUserData(int position) {
new CommomDialog(this, R.style.dialog, "delete", new CommomDialog.OnCloseListener() {
@Override
public void onClick(Dialog dialog, boolean confirm, UserInfo us) {
if(confirm){
int result = SQLiteDB.getInstance(ListViewActivity.this).deleteById(us.getUserid());
if(result == 1){
}
Log.i("del", "succ");
dialog.dismiss();
initData();
}
}
},position, userInfos, 3).setTitle("提示").show();
}
/**
* edit
*/
private void updetaUserData(final int position) {
new CommomDialog(this, R.style.dialog, "edit", new CommomDialog.OnCloseListener() {
@Override
public void onClick(Dialog dialog, boolean confirm, UserInfo us) {
if(confirm){
SQLiteDB.getInstance(ListViewActivity.this).updateUser(us.getUsername(), us.getPassword(), String.valueOf(us.getUserid()));
Log.i("edit", "succ");
dialog.dismiss();
initData();
}
}
},position, userInfos, 2).setTitle("提示").show();
}
这是查询、修改和删除的数据库操作方法:
/**
* 从数据库user表中读取数据
*/
public List getUsers() {
List list = new ArrayList();
Cursor cursor = db.query("user", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
UserInfo userInfo = new UserInfo();
userInfo.setUserid(cursor.getInt(cursor.getColumnIndex("userid")));
userInfo.setUsername(cursor.getString(cursor.getColumnIndex("username")));
userInfo.setPassword(cursor.getString(cursor.getColumnIndex("password")));
list.add(userInfo);
} while (cursor.moveToNext());
}
return list;
}
/**
* 根据当前userid获取对应的user对象
* @param userId
*/
public List selectByIdUser(String userId){
List list = new ArrayList();
String id = String.valueOf(userId);
Cursor cursor = db.rawQuery("select * from user where userid=?", new String[]{id});
if(cursor.moveToFirst()){
UserInfo userInfo = new UserInfo();
userInfo.setUserid(cursor.getInt(cursor.getColumnIndex("userid")));
userInfo.setUsername(cursor.getString(cursor.getColumnIndex("username")));
userInfo.setPassword(cursor.getString(cursor.getColumnIndex("password")));
list.add(userInfo);
}
return list;
}
/**
* 修改收藏属性值
* @param username
* @param password
*/
public void updateUser(String username, String password, String userId) {
ContentValues values = new ContentValues();
values.put("username", username);
values.put("password", password);
long ret = -1;
do {
ret = db.update("user", values, "userid=?",
new String[] { userId });
} while (ret < 0);
}
/**
* 根据当前id所对应的的user对象
* @param userId
* @return
*/
public int deleteById(int userId) {
if (userId == 0) {
return -1;
}
return db.delete("user", "userid=?", new String[]{ String.valueOf(userId) });
}
具体代码工作还是看demo,通过运行demo对增删改查的步骤和操作方法会更加清晰。
最后附上demo:
https://download.csdn.net/download/qq_35840038/10478552
q:486789970
email:[email protected]