GreenDao的简单使用说明(二)单表的增,删,改,查

        通过上一篇文章,我们已经把GreenDao框架架起来了,而且三个基础操作类和Users的用户类也建立起来了,哪么下面我们就来实现一下,对于这个单表的增,删,改,查功能.

        这里说明一下,因为是做一个简单的例子,所以这里我对数据库的操作,没有做异步处理.

       第一步,我们要先来写一个类BaseApplication.java,此类是用来取得GreenDao中的DaoMaster和DaoSession的,先看代码.

      

package com.example.cg.greendaolearn.db;

import android.app.Application;
import android.content.Context;

import com.example.cg.greendaolearn.THDevOpenHelper;
import com.guangda.dao.DaoMaster;
import com.guangda.dao.DaoSession;

/**
 * 官方推荐将取得DaoMaster对象的方法放到Application层这样避免多次创建生成Session对象。
 * Created by cg on 2015/12/29.
 */
public class BaseApplication extends Application {
    private static BaseApplication mInstance;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    @Override
    public void onCreate() {
        super.onCreate();
        if(mInstance == null)
            mInstance = this;
    }

    /**
     * 取得DaoMaster
     *
     * @param context        上下文
     * @return               DaoMaster
     */
    public static DaoMaster getDaoMaster(Context context) {
        if (daoMaster == null) {
            DaoMaster.OpenHelper helper = new THDevOpenHelper(context,"myDb",null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 取得DaoSession
     *
     * @param context        上下文
     * @return               DaoSession
     */
    public static DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                daoMaster = getDaoMaster(context);
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }
}
    通过代码上的注释,我们也知道了,只所以要继承自application,主要就是为了避免多次创建生成Session对象,提高性能.

   第二步,建立一个操作类,把增,删,改,查的方法,全写进去.方便调用.代码如下

   DbService.java

  

package com.example.cg.greendaolearn.db;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.guangda.dao.DaoSession;
import com.guangda.dao.UsersDao;

import java.util.List;

import greendao.Users;

/**
 * 用户操作类
 * Created by cg on 2015/12/29.
 */
public class DbService {
    private static final String TAG = DbService.class.getSimpleName();
    private static DbService instance;
    private static Context appContext;
    private DaoSession mDaoSession;
    private UsersDao userDao;


    private DbService() {
    }

    /**
     * 采用单例模式
     * @param context     上下文
     * @return            dbservice
     */
    public static DbService getInstance(Context context) {
        if (instance == null) {
            instance = new DbService();
            if (appContext == null){
                appContext = context.getApplicationContext();
            }
            instance.mDaoSession = BaseApplication.getDaoSession(context);
            instance.userDao = instance.mDaoSession.getUsersDao();
        }
        return instance;
    }

    /**
     * 根据用户id,取出用户信息
     * @param id           用户id
     * @return             用户信息
     */
    public Users loadNote(long id) {
        if(!TextUtils.isEmpty(id + "")) {
            return userDao.load(id);
        }
        return  null;
    }

    /**
     * 取出所有数据
     * @return      所有数据信息
     */
    public List loadAllNote(){
        return userDao.loadAll();
    }

    /**
     * 生成按id倒排序的列表
     * @return      倒排数据
     */
    public List loadAllNoteByOrder()
    {
        return userDao.queryBuilder().orderDesc(UsersDao.Properties.Id).list();
    }

    /**
     * 根据查询条件,返回数据列表
     * @param where        条件
     * @param params       参数
     * @return             数据列表
     */
    public List queryNote(String where, String... params){
        return userDao.queryRaw(where, params);
    }


    /**
     * 根据用户信息,插件或修改信息
     * @param user              用户信息
     * @return 插件或修改的用户id
     */
    public long saveNote(Users user){
        return userDao.insertOrReplace(user);
    }


    /**
     * 批量插入或修改用户信息
     * @param list      用户信息列表
     */
    public void saveNoteLists(final List list){
        if(list == null || list.isEmpty()){
            return;
        }
        userDao.getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for(int i=0; i
  这个类就不多说了,大家一看就明白,很简单,而且里面也已经比较明确的给出了注解.

  第三步,设置布局文件

    1,Toolbar的代码:

       





   当然了,你要是想使用toolbar,还要为其设置样式,style.xml

  



    

    

    

    



 现在来看一下页面主布局,这个布局其实很简单,就是一个Toolbar,Toolbar上菜单有一个添加的按钮,而且下面是一个listView用来显示用户,点击添加按钮,弹出一个对话框,显示你要添加的项,填写完后,保存,新加的数据就会在listView中显示出来.点击列表项,会弹出对框,上面有删除与修改的选项,可以对此项进行删除与修改,

  好,先来看一下activity_one_table.xml文件

 


    

    



 接下来,看一下,toolbar菜单栏的布局文件,menu_one_table.xml.主要就是添加了一个添加的按钮

 



    


下面是listView列表显示,哪么我们先为这个列表设置一个item的布局.代码比较简单:'

  activity_onetable_lv_item.xml

 



    
        
            
            
        
        
            
            
        
    
    
        
            
            
        
        
            
            
        
    


 为再为它设计一个Adapter

  onetable_adapter.java

 

package com.example.cg.greendaolearn.adpater;

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

import com.example.cg.greendaolearn.R;

import java.util.List;

import greendao.Users;

/**
 * 用户信息显示Adapter
 * Created by cg on 2015/12/29.
 */
public class onetable_adapter extends BaseAdapter {

    private LayoutInflater inflater;
    private List list_user;

    public onetable_adapter(Context context,List list_user) {
        this.inflater = LayoutInflater.from(context);
        this.list_user = list_user;
    }

    @Override
    public int getCount() {
        return list_user.size();
    }

    @Override
    public Object getItem(int position) {
        return list_user.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        userInfo uInfo;
        if(convertView==null)
        {
            uInfo = new userInfo();
            convertView = inflater.inflate(R.layout.activity_onetable_lv_item,null);
            uInfo.uAge = (TextView)convertView.findViewById(R.id.txt_onetable_age);
            uInfo.uName = (TextView)convertView.findViewById(R.id.txt_onetable_uName);
            uInfo.uSex = (TextView)convertView.findViewById(R.id.txt_onetable_uSex);
            uInfo.uTel = (TextView)convertView.findViewById(R.id.txt_onetable_tel);

            convertView.setTag(uInfo);
        }else
        {
            uInfo = (userInfo)convertView.getTag();
        }

        uInfo.uSex.setText(list_user.get(position).getUSex());
        uInfo.uTel.setText(list_user.get(position).getUTelphone());
        uInfo.uName.setText(list_user.get(position).getUName());
        uInfo.uAge.setText(list_user.get(position).getUAge());


        return convertView;
    }

    public class userInfo
    {
        TextView uName;
        TextView uSex;
        TextView uAge;
        TextView uTel;
    }
}

  listVIew搞定了.我们来完成点击添加时,弹出的对话框,这里采用的DialogFragment

  先看布局文件fragment_onetable_dialog.xml

 




    
        
            
                
                
            
            
                
                
            
        
        
            
                
                
            
            
                
                
            
        

    



代码:oneTableDialogFragment.java

package com.example.cg.greendaolearn;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

/**
 * 用户添加与修改
 * Created by cg on 2015/12/30.
 */
public class oneTableDialogFragment extends DialogFragment {

    private  EditText edit_onetable_name;
    private  EditText edit_onetable_sex;
    private EditText edit_onetable_tel;
    private EditText edit_onetable_age;

    private String uName;                                      //用户姓名
    private String uSex;                                       //用户性别
    private String uAge;                                       //用户年纪
    private String uTel;                                       //用户电话

    private int flag;                                          //flag 标识 0:添加 1:修改
    private long uId;                                          //用户id,添加时为0,修改时为正确的id


    /**
     * 定义点击事件接口
     */
    public interface addUserOnClickListener
    {

        void onAddUserOnClick(long id,String uName, String uSex,String uAge,String uTel,int flag);
    }

    public oneTableDialogFragment(long uId,String uName, String uSex, String uAge, String uTel,int flag) {
        this.uName = uName;
        this.uSex = uSex;
        this.uAge = uAge;
        this.uTel = uTel;
        this.flag = flag;
        this.uId = uId;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.fragment_onetable_dialog, null);
        edit_onetable_name = (EditText) view.findViewById(R.id.edit_onetable_name);
        edit_onetable_sex = (EditText) view.findViewById(R.id.edit_onetable_sex);
        edit_onetable_tel = (EditText) view.findViewById(R.id.edit_onetable_tel);
        edit_onetable_age = (EditText)view.findViewById(R.id.edit_onetable_age);


        edit_onetable_name.setText(uName);
        edit_onetable_age.setText(uAge);
        edit_onetable_sex.setText(uSex);
        edit_onetable_tel.setText(uTel);

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(view)
                // Add action buttons
                .setTitle("添加用户")
                .setPositiveButton("添加",
                        new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int id)
                            {
                                addUserOnClickListener listener = (addUserOnClickListener) getActivity();
                                listener.onAddUserOnClick(uId,edit_onetable_name.getText().toString(),
                                        edit_onetable_sex.getText().toString(),
                                        edit_onetable_age.getText().toString(),
                                        edit_onetable_tel.getText().toString(),
                                        flag);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                edit_onetable_name.setText("");
                                edit_onetable_sex.setText("");
                                edit_onetable_age.setText("");
                                edit_onetable_tel.setText("");
                            }
        });
        return builder.create();
    }
}

这里就不多说了,一是代码比较简单,二是里面的注释也比较清楚,大家一眼就明白了.

下面就是对点击item项的时候,弹出的对框进行设计,先看布局,就两个textView

fragment_onetable_itemdialog.xml




    
    
    


代码:oneTableItemDialogFragment.java

package com.example.cg.greendaolearn;

import android.app.DialogFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

/**
 * Created by cg on 2015/12/30.
 */
public class oneTableItemDialogFragment extends DialogFragment {

    private long id;                                  //用户id
    private int postion;                              //list中的编号
    private TextView txt_onetable_update;
    private TextView txt_onetable_delete;

    public interface EditUserOnClickListener
    {
        //flag标识,0表示删除,1表示修改
        void onEditUserOnClick(long id,int postion,int flag);
    }

    public oneTableItemDialogFragment(long id,int postion) {
        this.id = id;
        this.postion = postion;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.fragment_onetable_itemdialog,container);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        txt_onetable_update = (TextView)view.findViewById(R.id.txt_onetable_update);
        txt_onetable_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditUserOnClickListener listener = (EditUserOnClickListener) getActivity();
                listener.onEditUserOnClick(id,postion,1);
            }
        });
        txt_onetable_delete = (TextView)view.findViewById(R.id.txt_onetable_delete);
        txt_onetable_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditUserOnClickListener listener = (EditUserOnClickListener) getActivity();
                listener.onEditUserOnClick(id,postion,0);
            }
        });
    }
}

OK了,现在我们来看一下,主程序的代码:oneTableActivity.java

package com.example.cg.greendaolearn;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.cg.greendaolearn.adpater.onetable_adapter;
import com.example.cg.greendaolearn.db.DbService;

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

import greendao.Users;

public class oneTableActivity extends AppCompatActivity implements oneTableDialogFragment.addUserOnClickListener,oneTableItemDialogFragment.EditUserOnClickListener {

    private Toolbar toolbar;                                                   //定义toolbar
    private ListView lv_oneTable;

    private List list_user;
    private onetable_adapter oAdapter;

    private DbService db;

    private oneTableItemDialogFragment oneItemDialog;

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

        toolbar = (Toolbar)this.findViewById(R.id.toolbar);
        toolbar.setTitle("单表操作");                     // 标题的文字需在setSupportActionBar之前,不然会无效
        setSupportActionBar(toolbar);

        db = DbService.getInstance(this);

        initControls();

        initData();
    }

    /**
     * 初始化数据,刚进入页面时加载
     */
    private void initData() {

        list_user = new ArrayList<>();
        list_user = db.loadAllNoteByOrder();
        oAdapter = new onetable_adapter(this,list_user);
        lv_oneTable.setAdapter(oAdapter);
    }

    /**
     * 初始化控件
     */
    private void initControls() {

        lv_oneTable = (ListView)findViewById(R.id.lv_oneTable);
        lv_oneTable.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Toast.makeText(oneTableActivity.this,list_user.get(position).getUName() + "--" +
                        list_user.get(position).getId(),Toast.LENGTH_SHORT).show();

                oneItemDialog = new oneTableItemDialogFragment(list_user.get(position).getId(),position);
                oneItemDialog.show(getFragmentManager(),"编辑");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_one_table, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.menu_onetable_add) {
            oneTableDialogFragment oneDialog = new oneTableDialogFragment(0,"","","","",0);
            oneDialog.show(getFragmentManager(),"添加用户");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onAddUserOnClick(long uId,String uName, String uSex, String uAge, String uTel,int flag) {
        Users user = new Users();
        if(flag==1) {
            user.setId(uId);
        }
        user.setUSex(uSex);
        user.setUTelphone(uTel);
        user.setUAge(uAge);
        user.setUName(uName);
        if(flag==0) {
            if (db.saveNote(user) > 0) {
                list_user.add(0, user);
                oAdapter.notifyDataSetChanged();
            }
        }else
        {
            if (db.saveNote(user) > 0) {

                int num = 0;
                for(Users u:list_user)
                {
                    if(u.getId()==uId)
                    {
                        list_user.remove(num);
                        list_user.add(num,user);

                        break;
                    }
                    num++;
                }
                oAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onEditUserOnClick(long id,int postion,int flag) {
        if(flag==0) {
            db.deleteNote(id);
            list_user.remove(postion);
            oAdapter.notifyDataSetChanged();
            oneItemDialog.dismiss();
        }else
        {
            Users updateUser = db.loadNote(id);
            oneTableDialogFragment oDialog = new oneTableDialogFragment(updateUser.getId(),updateUser.getUName(),updateUser.getUSex(),
                    updateUser.getUAge(), updateUser.getUTelphone(),1);
            oneItemDialog.dismiss();
            oDialog.show(getFragmentManager(),"修改");
        }


    }
}

运行效果图:


你可能感兴趣的:(Android)