你的位置:首页 > 操作系统

[操作系统]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);    }  }}

  布局文件

<?

  

如果想要源码,请留下邮箱。

Demo下载
最后,以上例子都来源与安卓无忧,请去应用宝或者豌豆荚下载:http://android.myapp.com/myapp/detail.htm?apkName=com.shandong.mm.androidstudy,源码例子文档一网打尽




到巴厘岛旅游要花多少钱去巴厘岛签证要几天办理巴厘岛签证费用出发去巴厘岛旅游巴厘岛旅游报价中山逍遥谷攻略?五桂山逍遥谷坐几路车直达? 中山逍遥谷地址?五桂山逍遥谷自驾游攻略? 中山逍遥谷图片?五桂山逍遥谷漂亮吗? 中山逍遥谷开车怎么走?五桂山逍遥谷开车需要多长时间? 信宜石根山景点介绍?石根山有什么好玩的? 信宜石根山旅游风情区好玩吗?石根山旅游风情区怎么样? 信宜石根山驾车路线?广州到石根山开车怎么走? 石根山交通线路?信宜石根山怎样去? 台湾旅游购物必读指南,台湾购物指南,台湾旅游购物事项 2013第十六届中国沈阳国际冰雪节开幕 2013年春节高速免费通行时间 台湾旅游特产介绍,台湾有哪些土特产,台湾土特产有什么 内蒙古旅游注意事项 成吉思汗陵墓在哪_鄂尔多斯成吉思汗陵墓地理位置怎么走 太湖在哪个省_苏州太湖国家湿地公园、无锡市太湖鼋头渚风景区交通信息 冠豸山门票_龙岩连城冠豸山门票价格多少钱 HL-32604YW Datasheet HL-32604YW Datasheet HL-32605GD Datasheet HL-32605GD Datasheet HL-32605Q7YD Datasheet HL-32605Q7YD Datasheet 2月旅游去哪里好 2月旅游去哪里好 2月旅游去哪里好 2月到哪旅游好 2月到哪旅游好 2月到哪旅游好 3月最适合旅游的地方 3月最适合旅游的地方 3月最适合旅游的地方