GreenDao和Adapter实现学生信息管理

本文介绍如何在Android应用中使用GreenDAO进行高效的数据管理,包括依赖配置、实体类定义、适配器创建及数据操作等关键步骤。

添加依赖:

implementation 'org.greenrobot:greendao:3.1.0'

implementation 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

implementation "com.daimajia.swipelayout:library:1.2.0@aar"

 

 

app中的build.gradle

apply plugin: 'com.android.application'

apply plugin: 'org.greenrobot.greendao'

android {

    compileSdkVersion 27

    defaultConfig {

        applicationId "com.wanghuanlong.studentinformatica"

        minSdkVersion 22

        targetSdkVersion 27

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }





    greendao {

        schemaVersion 1

        targetGenDir 'src/main/java'

    }

}



dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:27.1.0'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.1'

    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation 'org.greenrobot:greendao:3.1.0'



    implementation 'com.jakewharton:butterknife:8.5.1'

    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'



    implementation "com.daimajia.swipelayout:library:1.2.0@aar"



}

 

 

 

model中

 

@Entity

public class Student implements Serializable{



    private String headSculpture;//头像

    @Id

    private String stuid;//学号

    private String ID;//身份证号码

    @Property(nameInDb = "name")

    private String name;//姓名

    private String age;//年龄

    private Date datOfBirth;//出生日期

    private String gender;//性别

    private String fromClass;//班级

    private String hobby;//爱好

    private String EmotionalState;//情感状态

    private String WordOfMouth;//口头禅

    private String phone;//手机号

    private String QQ;//QQ号

    private String weichat;//微信

    private String email;//电子邮箱

    private String PhotosOfLife1;//生活照1

    private String PhotosOfLife2;//生活照2

    private String PhotosOfLife3;//生活照3



    public String getPhotosOfLife1() {

        return PhotosOfLife1;

    }



    public void setPhotosOfLife1(String photosOfLife1) {

        PhotosOfLife1 = photosOfLife1;

    }



    public String getPhotosOfLife2() {

        return PhotosOfLife2;

    }



    public void setPhotosOfLife2(String photosOfLife2) {

        PhotosOfLife2 = photosOfLife2;

    }



    public String getPhotosOfLife3() {

        return PhotosOfLife3;

    }



    public void setPhotosOfLife3(String photosOfLife3) {

        PhotosOfLife3 = photosOfLife3;

    }



    private String detailedIntroduction;//详细介绍

    private int NumberOfFans;//粉丝数



    @Generated(hash = 167811149)

    public Student(String headSculpture, String stuid, String ID, String name,

            String age, Date datOfBirth, String gender, String fromClass,

            String hobby, String EmotionalState, String WordOfMouth, String phone,

            String QQ, String weichat, String email, String PhotosOfLife1,

            String PhotosOfLife2, String PhotosOfLife3,

            String detailedIntroduction, int NumberOfFans) {

        this.headSculpture = headSculpture;

        this.stuid = stuid;

        this.ID = ID;

        this.name = name;

        this.age = age;

        this.datOfBirth = datOfBirth;

        this.gender = gender;

        this.fromClass = fromClass;

        this.hobby = hobby;

        this.EmotionalState = EmotionalState;

        this.WordOfMouth = WordOfMouth;

        this.phone = phone;

        this.QQ = QQ;

        this.weichat = weichat;

        this.email = email;

        this.PhotosOfLife1 = PhotosOfLife1;

        this.PhotosOfLife2 = PhotosOfLife2;

        this.PhotosOfLife3 = PhotosOfLife3;

        this.detailedIntroduction = detailedIntroduction;

        this.NumberOfFans = NumberOfFans;

    }



    @Generated(hash = 1556870573)

    public Student() {

    }



    public String getHeadSculpture() {

        return headSculpture;

    }



    public void setHeadSculpture(String headSculpture) {

        this.headSculpture = headSculpture;

    }



    public String getStuid() {

        return stuid;

    }



    public void setStuid(String stuid) {

        this.stuid = stuid;

    }



    public String getID() {

        return ID;

    }



    public void setID(String ID) {

        this.ID = ID;

    }



    public String getName() {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public String getAge() {

        return age;

    }



    public void setAge(String age) {

        this.age = age;

    }



    public Date getDatOfBirth() {

        return datOfBirth;

    }



    public void setDatOfBirth(Date datOfBirth) {

        this.datOfBirth = datOfBirth;

    }



    public String getGender() {

        return gender;

    }



    public void setGender(String gender) {

        this.gender = gender;

    }



    public String getFromClass() {

        return fromClass;

    }



    public void setFromClass(String fromClass) {

        this.fromClass = fromClass;

    }



    public String getHobby() {

        return hobby;

    }



    public void setHobby(String hobby) {

        this.hobby = hobby;

    }



    public String getEmotionalState() {

        return EmotionalState;

    }



    public void setEmotionalState(String emotionalState) {

        EmotionalState = emotionalState;

    }



    public String getWordOfMouth() {

        return WordOfMouth;

    }



    public void setWordOfMouth(String wordOfMouth) {

        WordOfMouth = wordOfMouth;

    }



    public String getPhone() {

        return phone;

    }



    public void setPhone(String phone) {

        this.phone = phone;

    }



    public String getQQ() {

        return QQ;

    }



    public void setQQ(String QQ) {

        this.QQ = QQ;

    }



    public String getWeichat() {

        return weichat;

    }



    public void setWeichat(String weichat) {

        this.weichat = weichat;

    }



    public String getEmail() {

        return email;

    }



    public void setEmail(String email) {

        this.email = email;

    }





    public String getDetailedIntroduction() {

        return detailedIntroduction;

    }



    public void setDetailedIntroduction(String detailedIntroduction) {

        this.detailedIntroduction = detailedIntroduction;

    }



    public int getNumberOfFans() {

        return NumberOfFans;

    }



    public void setNumberOfFans(int numberOfFans) {

        NumberOfFans = numberOfFans;

    }





}

 

 

 

 

新建包adapter:

 

 

 

 

public abstract class ArrayListAdapter<T> extends BaseAdapter {



   protected List<T> mList;

   protected Context mContext;



   public ArrayListAdapter(Context context) {

      mContext = context;

   }



   public ArrayListAdapter(Context context, List<T> list) {

      mContext = context;

      mList = new ArrayList<T>();

      if (list != null) {

         mList.addAll(list);

      }

   }



   public List<T> getList() {

      return mList;

   }



   public void setList(List<T> list) {

      mList = list;

      notifyDataSetChanged();

   }



   public void setList(T[] array) {

      List<T> list = new ArrayList<T>(array.length);

      for (T t : array) {

         list.add(t);

      }

      setList(list);

   }



   @Override

   public int getCount() {

      if (mList != null)

         return mList.size();

      else

         return 0;

   }



   @Override

   public T getItem(int position) {

      return mList == null ? null : mList.get(position);

   }



   @Override

   public long getItemId(int position) {

      return position;

   }



}

 

 

 

public class StudentAdapter extends ArrayListAdapter<Student> {

    public StudentAdapter(Context context, List<Student> list) {

        super(context, list);

    }



    public StudentAdapter(Context context) {

        super(context);



    }



    @Override

    public View getView(int position, View view, ViewGroup viewGroup) {



        ViewHolder holder = null;

        if (view == null) {

            view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_student, null);

            holder = new ViewHolder(view);

            view.setTag(holder);

        } else {

            holder = (ViewHolder) view.getTag();

        }



       final Student item = mList.get(position);

        holder.tvStuid.setText(item.getStuid());

        holder.tvName.setText(item.getName());

        holder.tvAge.setText(item.getAge());

        holder.tvPhone.setText(item.getPhone());

        holder.tvQQ.setText(item.getQQ());

        holder.delete.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                if(deleteListener!=null){

                    deleteListener.deleteStudent(item);



                }

            }

        });



        holder.tvEdit.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {



                Intent intent=new Intent(mContext,StudentAddActivity.class);

                intent.putExtra("student",item);

                mContext.startActivity(intent);

            }

        });



        return view;

    }



    public DeleteListener deleteListener;



    public void setDeleteListener(DeleteListener deleteListener){

        this.deleteListener=deleteListener;

    }

    public  interface DeleteListener{

         void deleteStudent(final Student stu);

    }





    static class ViewHolder {

        @BindView(R.id.tv_edit)

        TextView tvEdit;

        @BindView(R.id.delete)

        TextView delete;

        @BindView(R.id.bottom_wrapper)

        LinearLayout bottomWrapper;

        @BindView(R.id.magnifier2)

        ImageView magnifier2;

        @BindView(R.id.star2)

        ImageView star2;

        @BindView(R.id.trash2)

        ImageView trash2;

        @BindView(R.id.bottom_wrapper_2)

        LinearLayout bottomWrapper2;

        @BindView(R.id.star)

        ImageView star;

        @BindView(R.id.bottom_wrapper_child1)

        RelativeLayout bottomWrapperChild1;

        @BindView(R.id.starbott)

        LinearLayout starbott;

        @BindView(R.id.tv_stuid)

        TextView tvStuid;

        @BindView(R.id.tv_name)

        TextView tvName;

        @BindView(R.id.tv_age)

        TextView tvAge;

        @BindView(R.id.tv_phone)

        TextView tvPhone;

        @BindView(R.id.tv_QQ)

        TextView tvQQ;



        ViewHolder(View view) {

            ButterKnife.bind(this, view);

        }

    }

Activity中

 

public abstract class BaseActivity extends AppCompatActivity {



    private DaoMaster.DevOpenHelper helper;

    private SQLiteDatabase db;

    private DaoMaster daoMaster;

    protected DaoSession daoSession;

    private Context mActivity;





    protected  void onCreate(Bundle savedInstanceState){



        super.onCreate(savedInstanceState);



        mActivity=this;

        setDataBase();

    }





    public void  showToast(String msg){



        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();

    }





    public void setDataBase(){



        helper=new DaoMaster.DevOpenHelper(this,"student.db",null);

        db=helper.getWritableDatabase();

        daoMaster=new DaoMaster(db);

        daoSession=daoMaster.newSession();

    }



    public void insertStu(Student stu){



        if(searchStuByStuId(stu.getStuid())>0)

        {

            showToast("该数据已存在");

            return;

        }

        daoSession.insert(stu);

    }



    public void delStu(Student stu){

        daoSession.delete(stu);

    }



    public void searchStuByName(String name){

        List<Student> studentList=daoSession.queryRaw(Student.class,"where name=?",new String[]{name});

        for (Student stu:studentList){



            Log.i("学生",stu.getStuid()+"   "+stu.getName()+"  "+stu.getID());

        }



    }





    public long searchStuByStuId(String stuid){

        List<Student>studentList=daoSession.queryRaw(Student.class,"where stuid=?",new String[]{stuid});

        for (Student stu:studentList){



            Log.i("学生",stu.getStuid()+"   "+stu.getName()+"  "+stu.getID());

        }



        return studentList.size();



    }



    public void searchStuByID(String ID){

        List<Student>studentList=daoSession.queryRaw(Student.class,"where ID=?",new String[]{ID});

        for (Student stu:studentList){



            Log.i("学生",stu.getStuid()+"   "+stu.getName()+"  "+stu.getID());

        }



    }



    public void updateStu(Student stu){

        daoSession.update(stu);

        showToast("更新中" );

    }



    public void updataByID(String ID,Student stu){



        String sql="update student set \"name\"="+stu.getName()+",\"ID\"="+stu.getID()+",\"age\"="+stu.getAge()+",\"phone\"="+stu.getPhone()+",\"QQ\"="+stu.getQQ()+"where";

        db.execSQL(sql);

    }





}
 

 

 

public class MainActivity extends BaseActivity {



    @BindView(R.id.tv_add)

    TextView tvAdd;

    @BindView(R.id.lv_in_main)

    ListView lvInMain;

    private List<Student> students;

    private StudentAdapter mAdapter;



    @Override

    protected void onResume() {

        super.onResume();

        refreshData();

    }



    public void refreshData(){

        students = daoSession.loadAll(Student.class);

        mAdapter.setList(students);

        mAdapter.notifyDataSetChanged();



    }



    public void initDataBase(){

        students = daoSession.loadAll(Student.class);

        mAdapter = new StudentAdapter(this, students);

        mAdapter.setDeleteListener(new StudentAdapter.DeleteListener() {

            @Override

            public void deleteStudent(Student stu) {

                delStu(stu);

                refreshData();

            }

        });

        lvInMain.setAdapter(mAdapter);

    }



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);





        initDataBase();

    }





    @OnClick(R.id.tv_add)

    public void onClick() {

        startActivity(new Intent(MainActivity.this,StudentAddActivity.class));

    }

}

 

 

 

public class StudentAddActivity extends BaseActivity {



    @BindView(R.id.et_name)

    EditText etName;

    @BindView(R.id.et_ID)

    EditText etID;

    @BindView(R.id.et_age)

    EditText etAge;

    @BindView(R.id.btn_add)

    Button btnAdd;

    @BindView(R.id.et_phone)

    EditText etPhone;

    @BindView(R.id.et_QQ)

    EditText etQQ;



    private Student student;

    private String mode="add";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_student_add);

        ButterKnife.bind(this);



        if(getIntent().getSerializableExtra("student")!=null){

            mode="edit";

            btnAdd.setText("保存");



            student=(Student)getIntent().getSerializableExtra("student");

            etName.setText(student.getName());

            etID.setText(student.getID());

            etAge.setText(student.getAge());

            etPhone.setText(student.getPhone());

            etQQ.setText(student.getQQ());

        }



    }



    @OnClick(R.id.btn_add)

    public void onClick() {

        String stuid = UUID.randomUUID().toString().substring(0, 8);

        String name = etName.getText().toString();

        String ID = etID.getText().toString();

        String age = etAge.getText().toString();

        String phone= etPhone.getText().toString();

        String QQ= etQQ.getText().toString();



        if (TextUtils.isEmpty(name)) {

            showToast("姓名不能为空");

            return;

        }

        if (TextUtils.isEmpty(ID)) {

            showToast("身份证号码不能为空");

            return;

        }

        if (TextUtils.isEmpty(age)) {

            showToast("年龄不能为空");

            return;

        }

        if (TextUtils.isEmpty(phone)) {

            showToast("手机号码不能为空");

            return;

        }

        if (TextUtils.isEmpty(QQ)) {

            showToast("QQ不能为空");

            return;

        }

        Student stu = new Student();



        stu.setStuid(stuid);

        stu.setName(name);

        stu.setID(ID);

        stu.setAge(age);

        stu.setPhone(phone);

        stu.setQQ(QQ);

        if(mode.equals("add"))

        insertStu(stu);

        else if(mode.equals("edit")){

            updateStu(stu);

        }

        finish();



    }

}

https://pan.baidu.com/s/1qz5yWAFOy52WU0D7uEVKOw

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值