GreenDao的使用说明(二)


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

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

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

      

[java]   view plain  copy
  1. package com.example.cg.greendaolearn.db;  
  2.   
  3. import android.app.Application;  
  4. import android.content.Context;  
  5.   
  6. import com.example.cg.greendaolearn.THDevOpenHelper;  
  7. import com.guangda.dao.DaoMaster;  
  8. import com.guangda.dao.DaoSession;  
  9.   
  10. /** 
  11.  * 官方推荐将取得DaoMaster对象的方法放到Application层这样避免多次创建生成Session对象。 
  12.  * Created by cg on 2015/12/29. 
  13.  */  
  14. public class BaseApplication extends Application {  
  15.     private static BaseApplication mInstance;  
  16.     private static DaoMaster daoMaster;  
  17.     private static DaoSession daoSession;  
  18.   
  19.     @Override  
  20.     public void onCreate() {  
  21.         super.onCreate();  
  22.         if(mInstance == null)  
  23.             mInstance = this;  
  24.     }  
  25.   
  26.     /** 
  27.      * 取得DaoMaster 
  28.      * 
  29.      * @param context        上下文 
  30.      * @return               DaoMaster 
  31.      */  
  32.     public static DaoMaster getDaoMaster(Context context) {  
  33.         if (daoMaster == null) {  
  34.             DaoMaster.OpenHelper helper = new THDevOpenHelper(context,"myDb",null);  
  35.             daoMaster = new DaoMaster(helper.getWritableDatabase());  
  36.         }  
  37.         return daoMaster;  
  38.     }  
  39.   
  40.     /** 
  41.      * 取得DaoSession 
  42.      * 
  43.      * @param context        上下文 
  44.      * @return               DaoSession 
  45.      */  
  46.     public static DaoSession getDaoSession(Context context) {  
  47.         if (daoSession == null) {  
  48.             if (daoMaster == null) {  
  49.                 daoMaster = getDaoMaster(context);  
  50.             }  
  51.             daoSession = daoMaster.newSession();  
  52.         }  
  53.         return daoSession;  
  54.     }  
  55. }  
    通过代码上的注释,我们也知道了,只所以要继承自application,主要就是为了避免多次创建生成Session对象,提高性能.

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

   DbService.java

  

[java]   view plain  copy
  1. package com.example.cg.greendaolearn.db;  
  2.   
  3. import android.content.Context;  
  4. import android.text.TextUtils;  
  5. import android.util.Log;  
  6.   
  7. import com.guangda.dao.DaoSession;  
  8. import com.guangda.dao.UsersDao;  
  9.   
  10. import java.util.List;  
  11.   
  12. import greendao.Users;  
  13.   
  14. /** 
  15.  * 用户操作类 
  16.  * Created by cg on 2015/12/29. 
  17.  */  
  18. public class DbService {  
  19.     private static final String TAG = DbService.class.getSimpleName();  
  20.     private static DbService instance;  
  21.     private static Context appContext;  
  22.     private DaoSession mDaoSession;  
  23.     private UsersDao userDao;  
  24.   
  25.   
  26.     private DbService() {  
  27.     }  
  28.   
  29.     /** 
  30.      * 采用单例模式 
  31.      * @param context     上下文 
  32.      * @return            dbservice 
  33.      */  
  34.     public static DbService getInstance(Context context) {  
  35.         if (instance == null) {  
  36.             instance = new DbService();  
  37.             if (appContext == null){  
  38.                 appContext = context.getApplicationContext();  
  39.             }  
  40.             instance.mDaoSession = BaseApplication.getDaoSession(context);  
  41.             instance.userDao = instance.mDaoSession.getUsersDao();  
  42.         }  
  43.         return instance;  
  44.     }  
  45.   
  46.     /** 
  47.      * 根据用户id,取出用户信息 
  48.      * @param id           用户id 
  49.      * @return             用户信息 
  50.      */  
  51.     public Users loadNote(long id) {  
  52.         if(!TextUtils.isEmpty(id + "")) {  
  53.             return userDao.load(id);  
  54.         }  
  55.         return  null;  
  56.     }  
  57.   
  58.     /** 
  59.      * 取出所有数据 
  60.      * @return      所有数据信息 
  61.      */  
  62.     public List<Users> loadAllNote(){  
  63.         return userDao.loadAll();  
  64.     }  
  65.   
  66.     /** 
  67.      * 生成按id倒排序的列表 
  68.      * @return      倒排数据 
  69.      */  
  70.     public List<Users> loadAllNoteByOrder()  
  71.     {  
  72.         return userDao.queryBuilder().orderDesc(UsersDao.Properties.Id).list();  
  73.     }  
  74.   
  75.     /** 
  76.      * 根据查询条件,返回数据列表 
  77.      * @param where        条件 
  78.      * @param params       参数 
  79.      * @return             数据列表 
  80.      */  
  81.     public List<Users> queryNote(String where, String... params){  
  82.         return userDao.queryRaw(where, params);  
  83.     }  
  84.   
  85.   
  86.     /** 
  87.      * 根据用户信息,插件或修改信息 
  88.      * @param user              用户信息 
  89.      * @return 插件或修改的用户id 
  90.      */  
  91.     public long saveNote(Users user){  
  92.         return userDao.insertOrReplace(user);  
  93.     }  
  94.   
  95.   
  96.     /** 
  97.      * 批量插入或修改用户信息 
  98.      * @param list      用户信息列表 
  99.      */  
  100.     public void saveNoteLists(final List<Users> list){  
  101.         if(list == null || list.isEmpty()){  
  102.             return;  
  103.         }  
  104.         userDao.getSession().runInTx(new Runnable() {  
  105.             @Override  
  106.             public void run() {  
  107.                 for(int i=0; i<list.size(); i++){  
  108.                     Users user = list.get(i);  
  109.                     userDao.insertOrReplace(user);  
  110.                 }  
  111.             }  
  112.         });  
  113.   
  114.     }  
  115.   
  116.     /** 
  117.      * 删除所有数据 
  118.      */  
  119.     public void deleteAllNote(){  
  120.         userDao.deleteAll();  
  121.     }  
  122.   
  123.     /** 
  124.      * 根据id,删除数据 
  125.      * @param id      用户id 
  126.      */  
  127.     public void deleteNote(long id){  
  128.         userDao.deleteByKey(id);  
  129.         Log.i(TAG, "delete");  
  130.     }  
  131.   
  132.     /** 
  133.      * 根据用户类,删除信息 
  134.      * @param user    用户信息类 
  135.      */  
  136.     public void deleteNote(Users user){  
  137.         userDao.delete(user);  
  138.     }  
  139. }  
  这个类就不多说了,大家一看就明白,很简单,而且里面也已经比较明确的给出了注解.

  第三步,设置布局文件

    1,Toolbar的代码:

       

[java]   view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     android:id="@+id/toolbar"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="wrap_content"  
  7.     android:background="?attr/colorPrimary"  
  8.     android:minHeight="?attr/actionBarSize"  
  9.     app:popupTheme="@style/ThemeOverlay.AppCompat.Light"  
  10.     app:theme="@style/ThemeOverlay.AppCompat.ActionBar">  
  11.   
  12. </android.support.v7.widget.Toolbar>  

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

  

[java]   view plain  copy
  1. <resources>  
  2.   
  3.     <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">  
  4.   
  5.         <!-- toolbar(actionbar)颜色 -->  
  6.         <item name="colorPrimary">#4876FF</item>  
  7.         <!-- 状态栏颜色 -->  
  8.         <item name="colorPrimaryDark">#3A5FCD</item>  
  9.         <!--toolbar文字的颜色-->  
  10.         <item name="@android:textColorPrimary">@android:color/white</item>  
  11.         <!-- 窗口的背景颜色 -->  
  12.         <item name="android:windowBackground">@android:color/white</item>  
  13.         <!-- SearchView -->  
  14.         <item name="searchViewStyle">@style/MySearchViewStyle</item>  
  15.   
  16.         <item name="actionMenuTextColor">#ffffff</item>  
  17.   
  18.     </style>  
  19.   
  20.     <style name="AppTheme" parent="@style/AppBaseTheme">  
  21.         <item name="android:windowIsTranslucent">true</item>  
  22.     </style>  
  23.   
  24.     <style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView"></style>  
  25.   
  26.     <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">  
  27.         <item name="spinBars">true</item>  
  28.         <item name="color">@android:color/white</item>  
  29.     </style>  
  30.   
  31. </resources>  

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

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

 

[html]   view plain  copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context="com.example.cg.greendaolearn.oneTableActivity"  
  6.     android:orientation="vertical">  
  7.     <include  
  8.         layout="@layout/toolbar" />  
  9.   
  10.     <ListView  
  11.         android:id="@+id/lv_oneTable"  
  12.         android:layout_width="match_parent"  
  13.         android:layout_height="0dp"  
  14.         android:layout_weight="1" />  
  15.   
  16. </LinearLayout>  

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

 

[html]   view plain  copy
  1. <menu xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     tools:context="com.example.cg.greendaolearn.oneTableActivity">  
  5.   
  6.     <item android:id="@+id/menu_onetable_add"  
  7.         android:title="添加"  
  8.         app:showAsAction="never" />  
  9. </menu>  

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

  activity_onetable_lv_item.xml

 

[html]   view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     android:background="@color/coral">  
  7.     <LinearLayout  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content">  
  10.         <LinearLayout  
  11.             android:layout_width="0dp"  
  12.             android:layout_height="wrap_content"  
  13.             android:layout_weight="1">  
  14.             <TextView  
  15.                 android:layout_width="0dp"  
  16.                 android:layout_height="wrap_content"  
  17.                 android:layout_weight="1"  
  18.                 android:gravity="center"  
  19.                 android:text="姓名:"  
  20.                 android:textColor="@color/white"  
  21.                 android:padding="5dp"/>  
  22.             <TextView  
  23.                 android:id="@+id/txt_onetable_uName"  
  24.                 android:layout_width="0dp"  
  25.                 android:layout_height="wrap_content"  
  26.                 android:layout_weight="1"  
  27.                 android:textColor="@color/white"  
  28.                 android:padding="5dp"/>  
  29.         </LinearLayout>  
  30.         <LinearLayout  
  31.             android:layout_width="0dp"  
  32.             android:layout_height="wrap_content"  
  33.             android:layout_weight="1">  
  34.             <TextView  
  35.                 android:layout_width="0dp"  
  36.                 android:layout_height="wrap_content"  
  37.                 android:layout_weight="1"  
  38.                 android:gravity="center"  
  39.                 android:text="性别:"  
  40.                 android:textColor="@color/white"  
  41.                 android:padding="5dp"/>  
  42.             <TextView  
  43.                 android:id="@+id/txt_onetable_uSex"  
  44.                 android:layout_width="0dp"  
  45.                 android:layout_height="wrap_content"  
  46.                 android:layout_weight="1"  
  47.                 android:textColor="@color/white"  
  48.                 android:padding="5dp"/>  
  49.         </LinearLayout>  
  50.     </LinearLayout>  
  51.     <LinearLayout  
  52.         android:layout_width="match_parent"  
  53.         android:layout_height="wrap_content"  
  54.         android:layout_marginTop="5dp">  
  55.         <LinearLayout  
  56.             android:layout_width="0dp"  
  57.             android:layout_height="wrap_content"  
  58.             android:layout_weight="1">  
  59.             <TextView  
  60.                 android:layout_width="0dp"  
  61.                 android:layout_height="wrap_content"  
  62.                 android:layout_weight="1"  
  63.                 android:gravity="center"  
  64.                 android:text="年纪:"  
  65.                 android:textColor="@color/white"  
  66.                 android:padding="5dp"/>  
  67.             <TextView  
  68.                 android:id="@+id/txt_onetable_age"  
  69.                 android:layout_width="0dp"  
  70.                 android:layout_height="wrap_content"  
  71.                 android:layout_weight="1"  
  72.                 android:textColor="@color/white"  
  73.                 android:padding="5dp"/>  
  74.         </LinearLayout>  
  75.         <LinearLayout  
  76.             android:layout_width="0dp"  
  77.             android:layout_height="wrap_content"  
  78.             android:layout_weight="1">  
  79.             <TextView  
  80.                 android:layout_width="0dp"  
  81.                 android:layout_height="wrap_content"  
  82.                 android:layout_weight="1"  
  83.                 android:gravity="center"  
  84.                 android:text="电话:"  
  85.                 android:textColor="@color/white"  
  86.                 android:padding="5dp"/>  
  87.             <TextView  
  88.                 android:id="@+id/txt_onetable_tel"  
  89.                 android:layout_width="0dp"  
  90.                 android:layout_height="wrap_content"  
  91.                 android:layout_weight="1"  
  92.                 android:textColor="@color/white"  
  93.                 android:padding="5dp"/>  
  94.         </LinearLayout>  
  95.     </LinearLayout>  
  96. </LinearLayout>  

 为再为它设计一个Adapter

  onetable_adapter.java

 

[java]   view plain  copy
  1. package com.example.cg.greendaolearn.adpater;  
  2.   
  3. import android.content.Context;  
  4. import android.view.LayoutInflater;  
  5. import android.view.View;  
  6. import android.view.ViewGroup;  
  7. import android.widget.BaseAdapter;  
  8. import android.widget.TextView;  
  9.   
  10. import com.example.cg.greendaolearn.R;  
  11.   
  12. import java.util.List;  
  13.   
  14. import greendao.Users;  
  15.   
  16. /** 
  17.  * 用户信息显示Adapter 
  18.  * Created by cg on 2015/12/29. 
  19.  */  
  20. public class onetable_adapter extends BaseAdapter {  
  21.   
  22.     private LayoutInflater inflater;  
  23.     private List<Users> list_user;  
  24.   
  25.     public onetable_adapter(Context context,List<Users> list_user) {  
  26.         this.inflater = LayoutInflater.from(context);  
  27.         this.list_user = list_user;  
  28.     }  
  29.   
  30.     @Override  
  31.     public int getCount() {  
  32.         return list_user.size();  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object getItem(int position) {  
  37.         return list_user.get(position);  
  38.     }  
  39.   
  40.     @Override  
  41.     public long getItemId(int position) {  
  42.         return position;  
  43.     }  
  44.   
  45.     @Override  
  46.     public View getView(int position, View convertView, ViewGroup parent) {  
  47.         userInfo uInfo;  
  48.         if(convertView==null)  
  49.         {  
  50.             uInfo = new userInfo();  
  51.             convertView = inflater.inflate(R.layout.activity_onetable_lv_item,null);  
  52.             uInfo.uAge = (TextView)convertView.findViewById(R.id.txt_onetable_age);  
  53.             uInfo.uName = (TextView)convertView.findViewById(R.id.txt_onetable_uName);  
  54.             uInfo.uSex = (TextView)convertView.findViewById(R.id.txt_onetable_uSex);  
  55.             uInfo.uTel = (TextView)convertView.findViewById(R.id.txt_onetable_tel);  
  56.   
  57.             convertView.setTag(uInfo);  
  58.         }else  
  59.         {  
  60.             uInfo = (userInfo)convertView.getTag();  
  61.         }  
  62.   
  63.         uInfo.uSex.setText(list_user.get(position).getUSex());  
  64.         uInfo.uTel.setText(list_user.get(position).getUTelphone());  
  65.         uInfo.uName.setText(list_user.get(position).getUName());  
  66.         uInfo.uAge.setText(list_user.get(position).getUAge());  
  67.   
  68.   
  69.         return convertView;  
  70.     }  
  71.   
  72.     public class userInfo  
  73.     {  
  74.         TextView uName;  
  75.         TextView uSex;  
  76.         TextView uAge;  
  77.         TextView uTel;  
  78.     }  
  79. }  

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

  先看布局文件fragment_onetable_dialog.xml

 

[html]   view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <LinearLayout  
  7.         android:layout_width="match_parent"  
  8.         android:layout_height="wrap_content"  
  9.         android:orientation="vertical">  
  10.         <LinearLayout  
  11.             android:layout_width="match_parent"  
  12.             android:layout_height="wrap_content">  
  13.             <LinearLayout  
  14.                 android:layout_width="0dp"  
  15.                 android:layout_height="wrap_content"  
  16.                 android:layout_weight="1">  
  17.                 <TextView  
  18.                     android:layout_width="0dp"  
  19.                     android:layout_height="wrap_content"  
  20.                     android:layout_weight="1"  
  21.                     android:gravity="center"  
  22.                     android:text="姓名:"/>  
  23.                 <EditText  
  24.                     android:id="@+id/edit_onetable_name"  
  25.                     android:layout_width="0dp"  
  26.                     android:layout_height="wrap_content"  
  27.                     android:layout_weight="1"  
  28.                     android:textColor="@color/black"/>  
  29.             </LinearLayout>  
  30.             <LinearLayout  
  31.                 android:layout_width="0dp"  
  32.                 android:layout_height="wrap_content"  
  33.                 android:layout_weight="1">  
  34.                 <TextView  
  35.                     android:layout_width="0dp"  
  36.                     android:layout_height="wrap_content"  
  37.                     android:layout_weight="1"  
  38.                     android:gravity="center"  
  39.                     android:text="性别:"/>  
  40.                 <EditText  
  41.                     android:id="@+id/edit_onetable_sex"  
  42.                     android:layout_width="0dp"  
  43.                     android:layout_height="wrap_content"  
  44.                     android:layout_weight="1"  
  45.                     android:textColor="@color/black"/>  
  46.             </LinearLayout>  
  47.         </LinearLayout>  
  48.         <LinearLayout  
  49.             android:layout_width="match_parent"  
  50.             android:layout_height="wrap_content">  
  51.             <LinearLayout  
  52.                 android:layout_width="0dp"  
  53.                 android:layout_height="wrap_content"  
  54.                 android:layout_weight="1">  
  55.                 <TextView  
  56.                     android:layout_width="0dp"  
  57.                     android:layout_height="wrap_content"  
  58.                     android:layout_weight="1"  
  59.                     android:gravity="center"  
  60.                     android:text="电话:"/>  
  61.                 <EditText  
  62.                     android:id="@+id/edit_onetable_tel"  
  63.                     android:layout_width="0dp"  
  64.                     android:layout_height="wrap_content"  
  65.                     android:layout_weight="1"  
  66.                     android:textColor="@color/black"/>  
  67.             </LinearLayout>  
  68.             <LinearLayout  
  69.                 android:layout_width="0dp"  
  70.                 android:layout_height="wrap_content"  
  71.                 android:layout_weight="1"  
  72.                 >  
  73.                 <TextView  
  74.                     android:layout_width="0dp"  
  75.                     android:layout_height="wrap_content"  
  76.                     android:layout_weight="1"  
  77.                     android:gravity="center"  
  78.                     android:text="年纪:"/>  
  79.                 <EditText  
  80.                     android:id="@+id/edit_onetable_age"  
  81.                     android:layout_width="0dp"  
  82.                     android:layout_height="wrap_content"  
  83.                     android:layout_weight="1"  
  84.                     android:textColor="@color/black"/>  
  85.             </LinearLayout>  
  86.         </LinearLayout>  
  87.   
  88.     </LinearLayout>  
  89.   
  90. </LinearLayout>  

代码:oneTableDialogFragment.java
[java]   view plain  copy
  1. package com.example.cg.greendaolearn;  
  2.   
  3. import android.app.AlertDialog;  
  4. import android.app.Dialog;  
  5. import android.app.DialogFragment;  
  6. import android.content.DialogInterface;  
  7. import android.os.Bundle;  
  8. import android.view.LayoutInflater;  
  9. import android.view.View;  
  10. import android.widget.EditText;  
  11.   
  12. /** 
  13.  * 用户添加与修改 
  14.  * Created by cg on 2015/12/30. 
  15.  */  
  16. public class oneTableDialogFragment extends DialogFragment {  
  17.   
  18.     private  EditText edit_onetable_name;  
  19.     private  EditText edit_onetable_sex;  
  20.     private EditText edit_onetable_tel;  
  21.     private EditText edit_onetable_age;  
  22.   
  23.     private String uName;                                      //用户姓名  
  24.     private String uSex;                                       //用户性别  
  25.     private String uAge;                                       //用户年纪  
  26.     private String uTel;                                       //用户电话  
  27.   
  28.     private int flag;                                          //flag 标识 0:添加 1:修改  
  29.     private long uId;                                          //用户id,添加时为0,修改时为正确的id  
  30.   
  31.   
  32.     /** 
  33.      * 定义点击事件接口 
  34.      */  
  35.     public interface addUserOnClickListener  
  36.     {  
  37.   
  38.         void onAddUserOnClick(long id,String uName, String uSex,String uAge,String uTel,int flag);  
  39.     }  
  40.   
  41.     public oneTableDialogFragment(long uId,String uName, String uSex, String uAge, String uTel,int flag) {  
  42.         this.uName = uName;  
  43.         this.uSex = uSex;  
  44.         this.uAge = uAge;  
  45.         this.uTel = uTel;  
  46.         this.flag = flag;  
  47.         this.uId = uId;  
  48.     }  
  49.   
  50.     @Override  
  51.     public Dialog onCreateDialog(Bundle savedInstanceState)  
  52.     {  
  53.         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  
  54.         // Get the layout inflater  
  55.         LayoutInflater inflater = getActivity().getLayoutInflater();  
  56.         View view = inflater.inflate(R.layout.fragment_onetable_dialog, null);  
  57.         edit_onetable_name = (EditText) view.findViewById(R.id.edit_onetable_name);  
  58.         edit_onetable_sex = (EditText) view.findViewById(R.id.edit_onetable_sex);  
  59.         edit_onetable_tel = (EditText) view.findViewById(R.id.edit_onetable_tel);  
  60.         edit_onetable_age = (EditText)view.findViewById(R.id.edit_onetable_age);  
  61.   
  62.   
  63.         edit_onetable_name.setText(uName);  
  64.         edit_onetable_age.setText(uAge);  
  65.         edit_onetable_sex.setText(uSex);  
  66.         edit_onetable_tel.setText(uTel);  
  67.   
  68.         // Inflate and set the layout for the dialog  
  69.         // Pass null as the parent view because its going in the dialog layout  
  70.         builder.setView(view)  
  71.                 // Add action buttons  
  72.                 .setTitle("添加用户")  
  73.                 .setPositiveButton("添加",  
  74.                         new DialogInterface.OnClickListener()  
  75.                         {  
  76.                             @Override  
  77.                             public void onClick(DialogInterface dialog, int id)  
  78.                             {  
  79.                                 addUserOnClickListener listener = (addUserOnClickListener) getActivity();  
  80.                                 listener.onAddUserOnClick(uId,edit_onetable_name.getText().toString(),  
  81.                                         edit_onetable_sex.getText().toString(),  
  82.                                         edit_onetable_age.getText().toString(),  
  83.                                         edit_onetable_tel.getText().toString(),  
  84.                                         flag);  
  85.                             }  
  86.                         }).setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  87.                             @Override  
  88.                             public void onClick(DialogInterface dialog, int which) {  
  89.                                 edit_onetable_name.setText("");  
  90.                                 edit_onetable_sex.setText("");  
  91.                                 edit_onetable_age.setText("");  
  92.                                 edit_onetable_tel.setText("");  
  93.                             }  
  94.         });  
  95.         return builder.create();  
  96.     }  
  97. }  

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

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

fragment_onetable_itemdialog.xml

[html]   view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical">  
  6.   
  7.     <TextView  
  8.         android:id="@+id/txt_onetable_update"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="修改"  
  12.         android:padding="10dp"  
  13.         android:gravity="center"/>  
  14.     <View  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="1dp"  
  17.         android:background="@color/gray"/>  
  18.     <TextView  
  19.         android:id="@+id/txt_onetable_delete"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="删除"  
  23.         android:padding="10dp"  
  24.         android:gravity="center"/>  
  25. </LinearLayout>  

代码:oneTableItemDialogFragment.java
[java]   view plain  copy
  1. package com.example.cg.greendaolearn;  
  2.   
  3. import android.app.DialogFragment;  
  4. import android.os.Bundle;  
  5. import android.support.annotation.Nullable;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9. import android.view.Window;  
  10. import android.widget.TextView;  
  11.   
  12. /** 
  13.  * Created by cg on 2015/12/30. 
  14.  */  
  15. public class oneTableItemDialogFragment extends DialogFragment {  
  16.   
  17.     private long id;                                  //用户id  
  18.     private int postion;                              //list中的编号  
  19.     private TextView txt_onetable_update;  
  20.     private TextView txt_onetable_delete;  
  21.   
  22.     public interface EditUserOnClickListener  
  23.     {  
  24.         //flag标识,0表示删除,1表示修改  
  25.         void onEditUserOnClick(long id,int postion,int flag);  
  26.     }  
  27.   
  28.     public oneTableItemDialogFragment(long id,int postion) {  
  29.         this.id = id;  
  30.         this.postion = postion;  
  31.     }  
  32.   
  33.     @Nullable  
  34.     @Override  
  35.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  36.         getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);  
  37.         View view = inflater.inflate(R.layout.fragment_onetable_itemdialog,container);  
  38.   
  39.         return view;  
  40.     }  
  41.   
  42.     @Override  
  43.     public void onViewCreated(View view, Bundle savedInstanceState) {  
  44.         super.onViewCreated(view, savedInstanceState);  
  45.   
  46.         txt_onetable_update = (TextView)view.findViewById(R.id.txt_onetable_update);  
  47.         txt_onetable_update.setOnClickListener(new View.OnClickListener() {  
  48.             @Override  
  49.             public void onClick(View v) {  
  50.                 EditUserOnClickListener listener = (EditUserOnClickListener) getActivity();  
  51.                 listener.onEditUserOnClick(id,postion,1);  
  52.             }  
  53.         });  
  54.         txt_onetable_delete = (TextView)view.findViewById(R.id.txt_onetable_delete);  
  55.         txt_onetable_delete.setOnClickListener(new View.OnClickListener() {  
  56.             @Override  
  57.             public void onClick(View v) {  
  58.                 EditUserOnClickListener listener = (EditUserOnClickListener) getActivity();  
  59.                 listener.onEditUserOnClick(id,postion,0);  
  60.             }  
  61.         });  
  62.     }  
  63. }  

OK了,现在我们来看一下,主程序的代码:oneTableActivity.java
[java]   view plain  copy
  1. package com.example.cg.greendaolearn;  
  2.   
  3. import android.os.Bundle;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.support.v7.widget.Toolbar;  
  6. import android.view.Menu;  
  7. import android.view.MenuItem;  
  8. import android.view.View;  
  9. import android.widget.AdapterView;  
  10. import android.widget.ListView;  
  11. import android.widget.Toast;  
  12.   
  13. import com.example.cg.greendaolearn.adpater.onetable_adapter;  
  14. import com.example.cg.greendaolearn.db.DbService;  
  15.   
  16. import java.util.ArrayList;  
  17. import java.util.List;  
  18.   
  19. import greendao.Users;  
  20.   
  21. public class oneTableActivity extends AppCompatActivity implements oneTableDialogFragment.addUserOnClickListener,oneTableItemDialogFragment.EditUserOnClickListener {  
  22.   
  23.     private Toolbar toolbar;                                                   //定义toolbar  
  24.     private ListView lv_oneTable;  
  25.   
  26.     private List<Users> list_user;  
  27.     private onetable_adapter oAdapter;  
  28.   
  29.     private DbService db;  
  30.   
  31.     private oneTableItemDialogFragment oneItemDialog;  
  32.   
  33.     @Override  
  34.     protected void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.         setContentView(R.layout.activity_one_table);  
  37.   
  38.         toolbar = (Toolbar)this.findViewById(R.id.toolbar);  
  39.         toolbar.setTitle("单表操作");                     // 标题的文字需在setSupportActionBar之前,不然会无效  
  40.         setSupportActionBar(toolbar);  
  41.   
  42.         db = DbService.getInstance(this);  
  43.   
  44.         initControls();  
  45.   
  46.         initData();  
  47.     }  
  48.   
  49.     /** 
  50.      * 初始化数据,刚进入页面时加载 
  51.      */  
  52.     private void initData() {  
  53.   
  54.         list_user = new ArrayList<>();  
  55.         list_user = db.loadAllNoteByOrder();  
  56.         oAdapter = new onetable_adapter(this,list_user);  
  57.         lv_oneTable.setAdapter(oAdapter);  
  58.     }  
  59.   
  60.     /** 
  61.      * 初始化控件 
  62.      */  
  63.     private void initControls() {  
  64.   
  65.         lv_oneTable = (ListView)findViewById(R.id.lv_oneTable);  
  66.         lv_oneTable.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  67.             @Override  
  68.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  69.                 Toast.makeText(oneTableActivity.this,list_user.get(position).getUName() + "--" +  
  70.                         list_user.get(position).getId(),Toast.LENGTH_SHORT).show();  
  71.   
  72.                 oneItemDialog = new oneTableItemDialogFragment(list_user.get(position).getId(),position);  
  73.                 oneItemDialog.show(getFragmentManager(),"编辑");  
  74.             }  
  75.         });  
  76.     }  
  77.   
  78.     @Override  
  79.     public boolean onCreateOptionsMenu(Menu menu) {  
  80.         // Inflate the menu; this adds items to the action bar if it is present.  
  81.         getMenuInflater().inflate(R.menu.menu_one_table, menu);  
  82.         return true;  
  83.     }  
  84.   
  85.     @Override  
  86.     public boolean onOptionsItemSelected(MenuItem item) {  
  87.         // Handle action bar item clicks here. The action bar will  
  88.         // automatically handle clicks on the Home/Up button, so long  
  89.         // as you specify a parent activity in AndroidManifest.xml.  
  90.         int id = item.getItemId();  
  91.   
  92.         //noinspection SimplifiableIfStatement  
  93.         if (id == R.id.menu_onetable_add) {  
  94.             oneTableDialogFragment oneDialog = new oneTableDialogFragment(0,"","","","",0);  
  95.             oneDialog.show(getFragmentManager(),"添加用户");  
  96.             return true;  
  97.         }  
  98.   
  99.         return super.onOptionsItemSelected(item);  
  100.     }  
  101.   
  102.   
  103.   
  104.     @Override  
  105.     public void onAddUserOnClick(long uId,String uName, String uSex, String uAge, String uTel,int flag) {  
  106.         Users user = new Users();  
  107.         if(flag==1) {  
  108.             user.setId(uId);  
  109.         }  
  110.         user.setUSex(uSex);  
  111.         user.setUTelphone(uTel);  
  112.         user.setUAge(uAge);  
  113.         user.setUName(uName);  
  114.         if(flag==0) {  
  115.             if (db.saveNote(user) > 0) {  
  116.                 list_user.add(0, user);  
  117.                 oAdapter.notifyDataSetChanged();  
  118.             }  
  119.         }else  
  120.         {  
  121.             if (db.saveNote(user) > 0) {  
  122.   
  123.                 int num = 0;  
  124.                 for(Users u:list_user)  
  125.                 {  
  126.                     if(u.getId()==uId)  
  127.                     {  
  128.                         list_user.remove(num);  
  129.                         list_user.add(num,user);  
  130.   
  131.                         break;  
  132.                     }  
  133.                     num++;  
  134.                 }  
  135.                 oAdapter.notifyDataSetChanged();  
  136.             }  
  137.         }  
  138.     }  
  139.   
  140.     @Override  
  141.     public void onEditUserOnClick(long id,int postion,int flag) {  
  142.         if(flag==0) {  
  143.             db.deleteNote(id);  
  144.             list_user.remove(postion);  
  145.             oAdapter.notifyDataSetChanged();  
  146.             oneItemDialog.dismiss();  
  147.         }else  
  148.         {  
  149.             Users updateUser = db.loadNote(id);  
  150.             oneTableDialogFragment oDialog = new oneTableDialogFragment(updateUser.getId(),updateUser.getUName(),updateUser.getUSex(),  
  151.                     updateUser.getUAge(), updateUser.getUTelphone(),1);  
  152.             oneItemDialog.dismiss();  
  153.             oDialog.show(getFragmentManager(),"修改");  
  154.         }  
  155.   
  156.   
  157.     }  
  158. }  

运行效果图:


猜你喜欢

转载自blog.csdn.net/zhourui_1021/article/details/74229518