sqlite 增删改查

PersonDao1.java
package mm.shandong.com.testsqlsqllite.dao; import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList;
import java.util.List; import mm.shandong.com.testsqlsqllite.entity.Person;
import mm.shandong.com.testsqlsqllite.util.StudySQLiteOpenHelper; /**
* Created by buyadong on 2016/8/7.
*/
public class PersonDao1 {
Context context;
StudySQLiteOpenHelper studySQLiteOpenHelper; public PersonDao1(Context context) {
this.context = context;
studySQLiteOpenHelper = new StudySQLiteOpenHelper(context, "androidStudy.db", 7);
} public void addPerson(Person person) {
SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
String sql = "insert into person(_id,name,sex,age,code) values(null,?,?,?,?)";
db.execSQL(sql,new Object[]{person.getName(),
person.getSex(), person.getAge(), person.getCode()});
} public void deletePerson(Person person) {
SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
String sql = "delete from person where _id=?";
db.execSQL(sql, new Object[]{person.get_id()});
} public void updatePerson(Person person) {
SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
String sql = "update person set name=?,sex=?,age=?,code=? where _id=?";
db.execSQL(sql, new Object[]{person.getName(), person.getSex(),
person.getAge(), person.getCode(), person.get_id()});
} public List<Person> getAllPerson() {
List<Person> persons = new ArrayList<Person>();
SQLiteDatabase db = studySQLiteOpenHelper.getWritableDatabase();
String sql = "select * from person";
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
String code = cursor.getString(cursor.getColumnIndex("code"));
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
Person person = new Person(name, sex, age, code);
person.set_id(_id);
persons.add(person);
}
return persons;
}
}
Person实体类
package mm.shandong.com.testsqlsqllite.entity; import java.io.Serializable; /**
* Created by 安卓无忧 on 2016/7/27.
*/
public class Person implements Serializable{
private String name;
private int age;
private String code;
private String sex; public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} private String first_letter;
private int _id; public void set_id(int _id) {
this._id = _id;
} public int get_id() { return _id;
} public void setFirst_letter(String first_letter) {
this.first_letter = first_letter;
} public String getFirst_letter() { return first_letter;
} public Person(){ }
public Person(String name, int age, String code){
this.name=name;
this.age=age;
this.code=code;
}
public Person(String name,String sex, int age, String code){
this.name=name;
this.age=age;
this.code=code;
this.sex=sex;
}
@Override
public String toString() {
return name +" "+age+" "+code;
} public void setAge(int age) {
this.age = age;
} public void setCode(String code) {
this.code = code;
} public void setName(String name) {
this.name = name;
} public int getAge() { return age;
} public String getCode() {
return code;
} public String getName() {
return name;
}
}
StudySQLiteOpenHelper
package mm.shandong.com.testsqlsqllite.util; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; /**
* Created by 安卓无忧 on 2016/7/10.
*/
public class StudySQLiteOpenHelper extends SQLiteOpenHelper {
String dataBase_name;
Context context;
String create_TABLE_sql="create table person(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name varchar(30),age integer,sex varchar(30),code varchar(30))" ;
String delete_Sql="delete from person"; public StudySQLiteOpenHelper(Context context, String name, int verson){
super(context,name,null,verson);
this.context=context;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(create_TABLE_sql);
} @Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { }
}
activity
package mm.shandong.com.testsqlsqllite; import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import mm.shandong.com.testsqlsqllite.dao.PersonDao1;
import mm.shandong.com.testsqlsqllite.entity.Person; public class TestSQLSqlLiteActivity extends AppCompatActivity {
ListView listView;
List<Person> persons;
PersonDao1 personDao;
BaseAdapter personAdapter;
Map<String,Boolean> radioStates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_sqlsql_lite);
radioStates=new HashMap<String,Boolean>();
personDao=new PersonDao1(this);
listView= (ListView) findViewById(R.id.listView);
persons=personDao.getAllPerson();
initListView();
}
public void initListView(){
personAdapter=new BaseAdapter() {
@Override
public int getCount() {
return persons.size();
}
@Override
public Object getItem(int position) {
return persons.get(position);
} @Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
view=getLayoutInflater().inflate(R.layout.item_sqlite_listview,null);
TextView textViewPerson_name= (TextView) view.findViewById(R.id.textViewPerson_name);
TextView textViewPerson_sex= (TextView) view.findViewById(R.id.textViewPerson_sex);
TextView textViewPerson_code=(TextView)view.findViewById(R.id.textViewPerson_code);
TextView textViewPerson_age= (TextView) view.findViewById(R.id.textViewPerson_age);
final Person person= (Person) getItem(position);
textViewPerson_name.setText(person.getName());
textViewPerson_age.setText(person.getAge()+"");
textViewPerson_sex.setText(person.getSex());
textViewPerson_code.setText(person.getCode());
RadioButton radioButton= (RadioButton) view.findViewById(R.id.radioButton);
radioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(view instanceof RadioButton) {
RadioButton radioButton = (RadioButton) view;
if (radioButton.isChecked()) {
radioStates.put(String.valueOf(position), true);
for (String key : radioStates.keySet()) {
if (!key.equals(String.valueOf(position))) {
radioStates.put(key, false);
}
}
notifyDataSetChanged();
}
} }
}
);
Boolean tempState=radioStates.get(String.valueOf(position));
if(tempState!=null&&tempState){
radioButton.setChecked(true);
view.setBackgroundColor(Color.BLUE);
}else{
radioButton.setChecked(false);
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
listView.setAdapter(personAdapter);
}
public void addPerson(View view){
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setTitle("新增用户").create();
View childView=getLayoutInflater().inflate(R.layout.layout_sqlite_alert,null);
builder.setView(childView);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Field field = null;
try {
field = dialogInterface.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialogInterface, true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) { try {
Field field = dialogInterface.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialogInterface,false);
AlertDialog ad;
if(dialogInterface instanceof AlertDialog){
ad= (AlertDialog) dialogInterface;
EditText editViewPerson_name=
(EditText) ad.findViewById(R.id.editViewPerson_name);
EditText editViewPerson_code=
(EditText) ad.findViewById(R.id.editViewPerson_code);
EditText editViewPerson_age=
(EditText) ad.findViewById(R.id.editViewPerson_age);
RadioGroup radioGroupSex=
(RadioGroup) ad.findViewById(R.id.radioGroupSex);
if(TextUtils.isEmpty(editViewPerson_name.getText().toString())){
Toast.makeText(TestSQLSqlLiteActivity.this,
"姓名不能为空",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(editViewPerson_code.getText().toString())){
Toast.makeText(TestSQLSqlLiteActivity.this,
"编号不能为空",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(editViewPerson_age.getText().toString())){
Toast.makeText(TestSQLSqlLiteActivity.this,
"年龄不能为空",Toast.LENGTH_SHORT).show();
return;
}
Person person=new Person();
person.setAge(Integer.parseInt(editViewPerson_age.getText().toString()));
person.setName(editViewPerson_name.getText().toString());
person.setCode(editViewPerson_code.getText().toString());
RadioButton radioButton= (RadioButton) radioGroupSex.
findViewById(radioGroupSex.getCheckedRadioButtonId());
person.setSex(radioButton.getText().toString());
personDao.addPerson(person);
persons=personDao.getAllPerson();
radioStates=new HashMap<String,Boolean>();
personAdapter.notifyDataSetChanged();
field.set(dialogInterface,true);
} } catch (Exception e) {
e.printStackTrace();
}
}
});
builder.show(); }
public void deletePerson(View view){
int position=-1;
for(int i=0;i<listView.getChildCount();i++){
View childView=listView.getChildAt(i);
RadioButton radioButton= (RadioButton) childView.findViewById(R.id.radioButton);
if(radioButton.isChecked()){
position=i;
break;
}
}
if(position!=-1){
Person person= persons.get(position);
personDao.deletePerson(person);
persons=personDao.getAllPerson();
radioStates=new HashMap<String,Boolean>();
personAdapter.notifyDataSetChanged(); }else{
Toast.makeText(this,"请选择要删除的行",Toast.LENGTH_SHORT);
}
}
public void updatePerson(View view){
int position=-1;
for(int i=0;i<listView.getChildCount();i++){
View childView=listView.getChildAt(i);
RadioButton radioButton= (RadioButton) childView.findViewById(R.id.radioButton);
if(radioButton.isChecked()){
position=i;
break;
}
}
if(position!=-1){
final Person person= persons.get(position);
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setTitle("修改用户").create();
View childView=getLayoutInflater().inflate(R.layout.layout_sqlite_alert,null);
EditText editViewPerson_name=
(EditText) childView.findViewById(R.id.editViewPerson_name);
EditText editViewPerson_code=
(EditText) childView.findViewById(R.id.editViewPerson_code);
EditText editViewPerson_age=
(EditText) childView.findViewById(R.id.editViewPerson_age);
RadioGroup radioGroupSex=
(RadioGroup) childView.findViewById(R.id.radioGroupSex);
editViewPerson_name.setText(person.getName());
editViewPerson_age.setText(String.valueOf(person.getAge()));
editViewPerson_code.setText(person.getCode());
if(person.getSex().equals("男")){
((RadioButton)radioGroupSex.getChildAt(0)).setChecked(true);
}else{
((RadioButton)radioGroupSex.getChildAt(1)).setChecked(true);
}
builder.setView(childView);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) { }
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) { try {
Field field = dialogInterface.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialogInterface,false);
AlertDialog ad;
if(dialogInterface instanceof AlertDialog){
ad= (AlertDialog) dialogInterface;
EditText editViewPerson_name=
(EditText) ad.findViewById(R.id.editViewPerson_name);
EditText editViewPerson_age=
(EditText) ad.findViewById(R.id.editViewPerson_age);
EditText editViewPerson_code=
(EditText) ad.findViewById(R.id.editViewPerson_code);
RadioGroup radioGroupSex= (RadioGroup) ad.findViewById(R.id.radioGroupSex); if(TextUtils.isEmpty(editViewPerson_name.getText().toString())){
Toast.makeText(TestSQLSqlLiteActivity.this,
"姓名不能为空",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(editViewPerson_age.getText().toString())){
Toast.makeText(TestSQLSqlLiteActivity.this,
"年龄不能为空",Toast.LENGTH_SHORT).show();
return;
} person.setAge(Integer.parseInt(editViewPerson_age.getText().toString()));
person.setName(editViewPerson_name.getText().toString());
RadioButton radioButton= (RadioButton) radioGroupSex.
findViewById(radioGroupSex.getCheckedRadioButtonId());
person.setSex(radioButton.getText().toString());
person.setCode(editViewPerson_code.getText().toString());
personDao.updatePerson(person);
persons=personDao.getAllPerson();
radioStates=new HashMap<String,Boolean>();
personAdapter.notifyDataSetChanged();
field.set(dialogInterface,true);
} } catch (Exception e) {
e.printStackTrace();
}
}
});
builder.show(); }else{
Toast.makeText(this,"请选择要删除的行",Toast.LENGTH_SHORT);
}
} }
布局文件
<?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="match_parent"
android:orientation="vertical"> <LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addPerson"
android:text="新增" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="deletePerson"
android:text="删除" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="updatePerson"
android:text="修改" />
</LinearLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"> <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="姓名" /> <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="编号" /> <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="年龄" /> <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="性别" /> <TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="请选择" />
</LinearLayout> <ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>
如果想要源码,请留下邮箱。
Demo下载
最后,以上例子都来源与安卓无忧,请去应用宝或者豌豆荚下载:http://android.myapp.com/myapp/detail.htm?apkName=com.shandong.mm.androidstudy,源码例子文档一网打尽
sqlite 增删改查的更多相关文章
- android 入门 006(sqlite增删改查)
android 入门 006(sqlite增删改查) package cn.rfvip.feb_14_2_sqlite; import android.content.Context; import ...
- iOS sqlite 增删改查 简单封装(基于 FMDB)
/** * 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * * 基于 FMDB * * 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...
- C#Sqlite增删改查
说到使用数据库的话,无非也就是对数据的增加,删除和修改以及查询.前文已经 创建好了程序,现在我们就可以来具体实现Sqlite的数据操作,增删改查. 第一步,创建连接字符串来连接数据库: private ...
- iOS SQLite 增删改查的封装(关系型)
在工程里导入libsqlite3.tbd库(Xcode 7) #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder &l ...
- C# 使用 Dapper 实现 SQLite 增删改查
Dapper 是一款非常不错的轻型 ORM 框架,使用起来非常方便,经常使用 EF 框架的人几乎感觉不到差别,下面是自己写的 Sqlite 通用帮助类: 数据连接类: public class SQL ...
- 回家前的挣扎——SQLite增删改查
引言 最后一天,公司就两个人,也不知道弄点什么,就在网上找了Sqlite的文档,看了看,这里也是现学现卖,给自己找点事做,感觉时间过得还是比较快的,不然焦急等待,滋味不好受啊. SQLite简介 SQ ...
- iOS SQLite增删改查(简单应用)
// 注意: 在工程里导入libsqlite3.tbd库(Xcode7,如果Xcode7以下的版本则导入libsqlite3.dylib). #import <UIKit/UIKit.h> ...
- sqlite增删改查
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=&q ...
- Android Sqlite 增删改查
模拟 查询所有数据,增加一条数据,修改某一条数据,删除某一条数据: SQLiteOpenHelper 帮助类的介绍: import android.content.Context; import an ...
随机推荐
- 解决MVC EF Code First错误:Model compatibility cannot be checked because the EdmMetadata type was not included in the model.
Model compatibility cannot be checked because the EdmMetadata type was not included in the model. En ...
- LINUX总结
LINUX总结 crazyacking 2016-02-26 主要对socket编程,多线程,定时器,条件变量总结 多线程篇 概念: 多线程就是允许一个进程内存存在多个控制权,实现多个线程并发执行. ...
- Microsoft Orleans 之 入门指南
Microsoft Orleans 在.net用简单方法构建高并发.分布式的大型应用程序框架. 原文:http://dotnet.github.io/orleans/ 在线文档:http://dotn ...
- cdnjquery加载失败加载本地
<script type="text/javascript" src="//libs.baidu.com/jquery/1.7.2/jquery.min.js&qu ...
- 【iOS】配置和使用静态库
上一篇 我们演示了了如何创建自己的静态库,最终生成多个.a文件,根据需要引用工程就可以直接使用静态库了,但是有个很麻烦的问题,模拟器用的库和真机的不是同一个,当我们切换的时候需要更换静态库,有两种方式 ...
- asp.net中Ajax控件的用途(二)
1.个人觉得对于新手最为实用的PopupControlExtender,弹出层载体,在实例中可以弹出登录框,百度的登陆页面基本都用的这种形式,可以把浮动的panel宽高都设置为100%,以屏蔽底层操作 ...
- 【C#】回调方法不通过object参数获得委托实例
回调方法中几乎都会存在获取委托实例的需求,进而通过委托实例调用EndInvoke以得到异步执行的返回值.在我看过的相关文章中,获取委托实例的方法几乎都是同一个,就是向BeginInvoke的最后一个参 ...
- C# IDisposable接口
public class MyClass : IDisposable { public int a; public MyClass() { //构造 } public void Dispose() { ...
- html5学习笔记(3)--主题结构元素-1
Article元素 以下为对应代码: <!DOCTYPE html> <html> <head lang="en"> <meta char ...
- Microsoft.Practices.Unity入门
Unity是微软Patterns & Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器,它支持常用的三种依赖注入方式:构造器注入 ...