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 getAllPerson() {
        List persons = new ArrayList();
        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 persons;
    PersonDao1 personDao;
    BaseAdapter personAdapter;
    Map radioStates;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_sqlsql_lite);
        radioStates=new HashMap();
        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();
                        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();
            personAdapter.notifyDataSetChanged();

        }else{
            Toast.makeText(this,"请选择要删除的行",Toast.LENGTH_SHORT);
        }
    }
    public void updatePerson(View view){
        int position=-1;
        for(int i=0;i();
                            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,源码例子文档一网打尽。 

 

 

  • sqlite 增删改查_第1张图片
  • 大小: 6.4 MB
  • 查看图片附件

你可能感兴趣的:(sqllite,sqllite增删改查,android数据库)