Android的用GreenDao操作数据库

1、GreenDao简介
GreenDao就是实现Java对象和SQLite Datebase的一个媒介人,简化了SQLite的操作。如果学过ssh的人都知道类似Hibernia。

GreenDao

官方网站http://greendao-orm.com/

2、创建一个Android项目,把greendao-1.3.7.jar添加到libs中
3、创建一个Student.class类

package com.example.androidgreendao1;

import java.util.Date;

public class Student {

    private Long id;
    private String firstName;
    private String secondName;
    private java.util.Date birthday;
    private Long age;

    public Student() {

    }

    public Student(Long id) {
        this.id = id;
    }

    public Student(Long id, String firstName, String secondName, Long age,
            Date birthday) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.secondName = secondName;
        this.birthday = birthday;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSecondName() {
        return secondName;
    }

    public void setSecondName(String secondName) {
        this.secondName = secondName;
    }

    public java.util.Date getBirthday() {
        return birthday;
    }

    public void setBirthday(java.util.Date birthday) {
        this.birthday = birthday;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

}

4、创建StudentDao,继承AbstractDao

package com.example.androidgreendao1;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;

public class StudentDao extends AbstractDao<Student, Long> {

    public static final String TABLENAME = "STUDENT";

    /** * Properties of entity Note.<br/> * Can be used for QueryBuilder and for referencing column names. */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id",
                true, "_id");
        public final static Property FirstName = new Property(1, String.class,
                "firstName", false, "firstName");
        public final static Property SecondName = new Property(2, String.class,
                "secondName", false, "secondName");
        public final static Property Age = new Property(3, String.class, "age",
                false, "age");
        public final static Property Birthday = new Property(4,
                java.util.Date.class, "birthday", false, "birthday");
    };

    public StudentDao(DaoConfig config, AbstractDaoSession daoSession) {
        super(config, daoSession);
        // TODO Auto-generated constructor stub
    }

    public StudentDao(DaoConfig config) {
        super(config);
        // TODO Auto-generated constructor stub
    }

    /** Creates the underlying database table. */
    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
        String constraint = ifNotExists ? "IF NOT EXISTS " : "";
        db.execSQL("CREATE TABLE " + constraint + "\"" + TABLENAME + "\" (" + //
                "\"_id\" INTEGER PRIMARY KEY ," + // 0: id
                "\"firstName\" TEXT NOT NULL ," + // 1: firstName
                "\"secondName\" TEXT NOT NULL ," + // 2: secondName
                "\"age\" INTEGER ," + // 3: age
                "\"birthday\" INTEGER);"); // 4: birthday
    }

    /** Drops the underlying database table. */
    public static void dropTable(SQLiteDatabase db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\""
                + TABLENAME + "\"";
        db.execSQL(sql);
    }

    @Override
    protected void bindValues(SQLiteStatement stmt, Student entity) {
        // TODO Auto-generated method stub
        stmt.clearBindings();

        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }

        String fristName = entity.getFirstName();
        if (fristName != null) {
            stmt.bindString(2, fristName);
        }

        String secondName = entity.getSecondName();
        if (secondName != null) {
            stmt.bindString(3, secondName);
        }

        Long age = entity.getAge();
        if (age != null) {
            stmt.bindLong(4, age);
        }

        java.util.Date birthday = entity.getBirthday();
        if (birthday != null) {
            stmt.bindLong(5, birthday.getTime());
        }
    }

    @Override
    protected Student readEntity(Cursor cursor, int offset) {
        // TODO Auto-generated method stub
        Student entity = new Student(
                //
                cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
                cursor.getString(offset + 1), // text
                cursor.getString(offset + 2), // text
                cursor.isNull(offset + 3) ? null : cursor.getLong(offset + 3), // comment
                cursor.isNull(offset + 4) ? null : new java.util.Date(cursor
                        .getLong(offset + 4)) // date
        );
        return entity;
    }

    @Override
    protected Long readKey(Cursor cursor, int offset) {
        // TODO Auto-generated method stub
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }

    @Override
    protected void readEntity(Cursor cursor, Student entity, int offset) {
        // TODO Auto-generated method stub
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setFirstName(cursor.getString(offset + 1));
        entity.setSecondName(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
        entity.setAge(cursor.isNull(offset + 3) ? null : cursor.getLong(offset + 3));
        entity.setBirthday(cursor.isNull(offset + 4) ? null : new java.util.Date(cursor.getLong(offset + 4)));
    }

    @Override
    protected Long updateKeyAfterInsert(Student entity, long rowId) {
        // TODO Auto-generated method stub
        entity.setId(rowId);
        return rowId;
    }

    @Override
    protected Long getKey(Student entity) {
        // TODO Auto-generated method stub
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    @Override
    protected boolean isEntityUpdateable() {
        // TODO Auto-generated method stub
        return false;
    }

}

5、创建DaoSession

package com.example.androidgreendao1;

import android.database.sqlite.SQLiteDatabase;

import java.util.Map;

import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.AbstractDaoSession;
import de.greenrobot.dao.identityscope.IdentityScopeType;
import de.greenrobot.dao.internal.DaoConfig;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.

/** * {@inheritDoc} * * @see de.greenrobot.dao.AbstractDaoSession */
public class DaoSession extends AbstractDaoSession {

    private final DaoConfig studentDaoConfig;

    private final StudentDao studentDao;

    public DaoSession(SQLiteDatabase db, IdentityScopeType type,
            Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> daoConfigMap) {
        super(db);

        studentDaoConfig = daoConfigMap.get(StudentDao.class).clone();
        studentDaoConfig.initIdentityScope(type);

        studentDao = new StudentDao(studentDaoConfig, this);

        registerDao(Student.class, studentDao);
    }

    public void clear() {
        studentDaoConfig.getIdentityScope().clear();
    }

    public StudentDao getNoteDao() {
        return studentDao;
    }

}

6、DaoMaster
package com.example.androidgreendao1;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import de.greenrobot.dao.AbstractDaoMaster;
import de.greenrobot.dao.identityscope.IdentityScopeType;

public class DaoMaster extends AbstractDaoMaster {

public static final int SCHEMA_VERSION = 1;

/** Creates underlying database table using DAOs. */
public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {
    StudentDao.createTable(db, ifNotExists);
}

/** Drops underlying database table using DAOs. */
public static void dropAllTables(SQLiteDatabase db, boolean ifExists) {
    StudentDao.dropTable(db, ifExists);
}

public static abstract class OpenHelper extends SQLiteOpenHelper {

    public OpenHelper(Context context, String name, CursorFactory factory) {
        super(context, name, factory, SCHEMA_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i("greenDAO", "Creating tables for schema version "
                + SCHEMA_VERSION);
        createAllTables(db, false);
    }
}

/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
    public DevOpenHelper(Context context, String name, CursorFactory factory) {
        super(context, name, factory);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("greenDAO", "Upgrading schema from version " + oldVersion
                + " to " + newVersion + " by dropping all tables");
        dropAllTables(db, true);
        onCreate(db);
    }
}

public DaoMaster(SQLiteDatabase db, int schemaVersion) {
    super(db, SCHEMA_VERSION);
    // TODO Auto-generated constructor stub
    registerDaoClass(StudentDao.class);
}

@Override
public DaoSession newSession() {
    // TODO Auto-generated method stub
    return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}

@Override
public DaoSession newSession(IdentityScopeType type) {
    // TODO Auto-generated method stub
    return new DaoSession(db, type, daoConfigMap);
}

}
7、单例GreenDaoSingleton

package com.example.androidgreendao1;

import com.example.androidgreendao1.DaoMaster.DevOpenHelper;

import de.greenrobot.dao.query.QueryBuilder;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

public class GreenDaoSingleton {

    private DevOpenHelper helper;
    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private StudentDao studentDao;

    private GreenDaoSingleton(Context context) {
        helper = new DaoMaster.DevOpenHelper(context, "greendao-db", null);
        // enable SQL and parameter logging on the QueryBuilder:
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db, 1);
        daoSession = daoMaster.newSession();
        studentDao = daoSession.getNoteDao();
    }

    private static GreenDaoSingleton single = null;

    // 静态工厂方法
    public static synchronized GreenDaoSingleton getInstance(Context context) {
        if (single == null) {
            synchronized (GreenDaoSingleton.class) {
                if (single == null) {
                    single = new GreenDaoSingleton(context);
                }
            }

        }
        return single;
    }

    public StudentDao getStudentDao() {
        return studentDao;
    }
}

8、listview的适配器

package com.example.androidgreendao1;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {

    private List<Student> list=new ArrayList<>();
    private Context context;

    public MyAdapter(List<Student> list, Context context) {
        this.list = list;
        this.context = context;
    }

    public void setList(List<Student> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return list.get(arg0);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder viewHolder=null;
        if(convertView==null){
            viewHolder=new ViewHolder();
            convertView=View.inflate(context, R.layout.list_item, null);
            viewHolder.textView1=(TextView)convertView.findViewById(R.id.textView1);
            viewHolder.textView2=(TextView)convertView.findViewById(R.id.textView2);
            viewHolder.textView3=(TextView)convertView.findViewById(R.id.textView3);
            viewHolder.textView4=(TextView)convertView.findViewById(R.id.textView4);
            viewHolder.textView5=(TextView)convertView.findViewById(R.id.textView5);
            convertView.setTag(viewHolder);
        }else{
            viewHolder=(ViewHolder)convertView.getTag();
        }
        Student student=list.get(position);
        viewHolder.textView1.setText(student.getId()+"");
        viewHolder.textView2.setText(student.getFirstName()+"");
        viewHolder.textView3.setText(student.getSecondName()+"");
        viewHolder.textView4.setText(student.getAge()+"");
        viewHolder.textView5.setText(student.getBirthday()+"");
        return convertView;
    }

    class ViewHolder{
        TextView textView1;
        TextView textView2;
        TextView textView3;
        TextView textView4;
        TextView textView5;
    }
}

9、MainActivity

package com.example.androidgreendao1;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.example.androidgreendao1.StudentDao.Properties;

public class MainActivity extends Activity implements OnClickListener, OnItemLongClickListener {

    private EditText editTextFirst, editTextSecond;
    private Button button;
    private ListView listView;
    private MyAdapter myAdapter;
    private List<Student> list = new ArrayList<>();

    // GreenDao

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);

        this.editTextFirst = (EditText) findViewById(R.id.firstname);
        this.editTextSecond = (EditText) findViewById(R.id.secondname);
        this.button = (Button) findViewById(R.id.buttonAdd);
        this.listView = (ListView) findViewById(R.id.listView);

        this.button.setOnClickListener(this);
        this.myAdapter = new MyAdapter(list, this);
        this.listView.setAdapter(myAdapter);
        this.listView.setOnItemLongClickListener(this);

        resh();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String noteTextFrist = editTextFirst.getText().toString();
        editTextFirst.setText("");
        String noteTextSecond = editTextSecond.getText().toString();
        editTextSecond.setText("");

        final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                DateFormat.MEDIUM);
        String comment = noteTextSecond + df.format(new Date());
        Student student = new Student(null, noteTextFrist, comment, 17L,
                new Date());
        GreenDaoSingleton.getInstance(this).getStudentDao().insert(student);

        resh();
    }

    private void resh() {
        List<Student> joes = GreenDaoSingleton.getInstance(this)
                .getStudentDao().queryBuilder()
                // .where(Properties.FirstName.eq("常"))
                // .or(Properties.Birthday.gt(1970)
                .orderAsc(Properties.FirstName)
                // .limit(2)
                // .offset(1)
                .list();
        /* * QueryBuilder qb = studentDao.queryBuilder(); * qb.where(Properties.FirstName.eq("Joe"), * qb.or(Properties.Birthday.gt(1970), * qb.and(Properties.Birthday.eq(1970), Properties.Birthday.ge(10)))); * List<Student> joes=qb.list(); */
        list.clear();
        list.addAll(joes);
        myAdapter.setList(list);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        Student student = list.get(arg2);
        GreenDaoSingleton.getInstance(this).getStudentDao()
                .deleteByKey(student.getId());
        resh();
        return false;
    }
}

10、activity_main.xml、list_item.xml
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
    <LinearLayout  android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:orientation="horizontal">
        <EditText  android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:inputType="text" android:imeOptions="actionDone" android:id="@+id/firstname" android:hint="firstname"></EditText>
        <EditText  android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="wrap_content" android:inputType="text" android:imeOptions="actionDone" android:id="@+id/secondname" android:hint="secondname"></EditText>
        <Button  android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Add" android:id="@+id/buttonAdd" android:onClick="onMyButtonClick"></Button>
    </LinearLayout>
    <ListView  android:layout_height="wrap_content" android:id="@+id/listView" android:layout_width="fill_parent"></ListView>
</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" >

    <TextView  android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="TextView" />

    <TextView  android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="26dp" android:layout_toRightOf="@+id/textView1" android:text="TextView" />

    <TextView  android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="36dp" android:layout_toRightOf="@+id/textView2" android:text="TextView" />

    <TextView  android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:layout_marginTop="14dp" android:text="TextView" />

    <TextView  android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView4" android:layout_alignBottom="@+id/textView4" android:layout_alignLeft="@+id/textView3" android:text="TextView" />

</RelativeLayout>

源码下载在评论中,菜鸟一枚,欢迎大神指导。。。

你可能感兴趣的:(java,android,数据库,greenDAO)