GreenDao使用说明(三)多表的使用

 我们在使用数据库的时候,大多数都会是多表联合操作,不会只有一个表的,下面我们就来说一下,多表的操作,这里先拿1:n来说。这是我们平时在设计数据库时最常用的模式。下面我来看一下,GreenDao对1:n的模式是怎么处理的。

        一,我们先要新建两个表,用来实现1:n。我们先来修改MyDaoGenerator.Java这个文件。代码如下:

      

[java]   view plain  copy
  1. package pl.surecase.eu;  
  2.   
  3. import de.greenrobot.daogenerator.DaoGenerator;  
  4. import de.greenrobot.daogenerator.Entity;  
  5. import de.greenrobot.daogenerator.Property;  
  6. import de.greenrobot.daogenerator.Schema;  
  7. import de.greenrobot.daogenerator.ToMany;  
  8.   
  9. public class MyDaoGenerator {  
  10.   
  11.     public static void main(String args[]) throws Exception {  
  12.         Schema schema = new Schema(3"greendao");  
  13.         schema.setDefaultJavaPackageDao("com.guangda.dao");  
  14.         Entity userBean = schema.addEntity("Users");  
  15.         userBean.setTableName("Users");  
  16.         //userBean.addLongProperty("id").primaryKey().index().autoincrement();  
  17.         userBean.addIdProperty();  
  18.         userBean.addStringProperty("uSex");  
  19.         userBean.addStringProperty("uTelphone");  
  20.         userBean.addStringProperty("uAge");  
  21.         userBean.addStringProperty("uName");  
  22.   
  23.         //上面是我们用于单表操作的时建立的表  
  24.   
  25.   
  26.         //下面是我们要建的两个新表,一个上信息类别,一个是信自,它们的关系是1:n.  
  27.         //对于信息类别表,没有什么好说的,和上面一样,直接建立一个表就完了,我们主要来看一下信息表中,如何设置外键  
  28.         Entity infoTypeBean = schema.addEntity("infoType");  
  29.         //此处是用来实现序列化的接口  
  30.         infoTypeBean.implementsSerializable();  
  31.         infoTypeBean.addIdProperty();  
  32.         infoTypeBean.addStringProperty("infoName");  
  33.   
  34.         //信息表进行建立  
  35.         Entity infoBean = schema.addEntity("infos");  
  36.         infoBean.implementsSerializable();  
  37.         infoBean.addIdProperty();  
  38.         infoBean.addStringProperty("infoTitle");  
  39.         infoBean.addStringProperty("infoAuthor");  
  40.         infoBean.addStringProperty("infoContent");  
  41.         //这里我们为信息表,添加一个typeId外键,它就是infoType表的id  
  42.         Property typeId = infoBean.addLongProperty("typeId").getProperty();  
  43.           
  44.         //这里是重点,我们为这两个表建立1:n的关系,并设置关联字段。  
  45.         infoBean.addToOne(infoTypeBean, typeId);  
  46.         ToMany addToMany = infoTypeBean.addToMany(infoBean,typeId);  
  47.         addToMany.setName("infoes");  
  48.   
  49.         new DaoGenerator().generateAll(schema, args[0]);  
  50.     }  
  51. }  
          我在代码中加了比较详细的注解,相信大家一看就明白了。

         注意:

                    Schema schema = new Schema(3, "greendao");这里的版本号,你要比之前的版本号大1,原来咱们是1,我这里是3,是因为我当时写代码的时候,写错了一个地方,没法子,就又升了一次。哈哈。。。。。。。。

       

       二,修改我们封装的DaoMaster.OpenHelper代码,让他进行升级,代码如下

       

[java]   view plain  copy
  1. package com.example.cg.greendaolearn;  
  2.   
  3.   
  4. import android.content.Context;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6.   
  7. import com.guangda.dao.DaoMaster;  
  8. import com.guangda.dao.infoTypeDao;  
  9. import com.guangda.dao.infosDao;  
  10.   
  11. /** 
  12.  * 封装DaoMaster.OpenHelper方法, 在更新的时候,用来保存原来的数据 
  13.  * greenDao默认在更新的时候,会新建表,原来的数据就丢失了 
  14.  * Created by cg on 2015/12/28. 
  15.  */  
  16. public class THDevOpenHelper extends DaoMaster.OpenHelper {  
  17.   
  18.     public THDevOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {  
  19.         super(context, name, factory);  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  24.         switch (oldVersion) {  
  25.             case 2:  
  26.                 //创建新表,注意createTable()是静态方法  
  27.                 infosDao.createTable(db, true);  
  28.                 infoTypeDao.createTable(db,true);  
  29.   
  30.                 // 加入新字段  
  31.                 // db.execSQL("ALTER TABLE 'moments' ADD 'audio_path' TEXT;");  
  32.   
  33.                 // TODO  
  34.                 break;  
  35.         }  
  36.     }  
  37. }  

       这里我们修改就是onUpgrade方法,在这里添加了创建新表的方法,在这里我多说一句,就是GreenDao在修改原表的时候,它会把原表删除,这样就会有一个问题,你原有的数据会丢,这样,我们就要在这里处理一下,把原表数据存入临时表中,然后再删除,最后把数据再导回来。

     三,生成建表,我们运行代码,来看一下生成后的效果

             这里有时候,我们在运行MyDaoGenerator.java代码,生成类的时候,会提示GKB代码无法运行,这是因为你在这个文件里写了中文,它不认,就算是你把这个文件转成了utf-8,也会报这个错,这时候,我们只能用记事本打开这个文件,然后覆盖保存,在保存时,编码选择 ANSI。就ok了,下面我们看一下,生成的文件列表

         

           

         这样,我们的新建的两个表的bean和操作dao文件都已经生成好了。我们就可以进行后面的,增,删,改,查工作了。

    四, 查看生成的bean文件

            我们来看一下这里生成的infos.java和infoType.java两个文件有什么特别之后。我们先来看一下infoType.java代码,处了代码被序列化外,我们发现里面多了一些方法,这里主要说一下与1:N关联有关的方法

           

[java]   view plain  copy
  1. public List<infos> getInfoes() {  
  2.         if (infoes == null) {  
  3.             if (daoSession == null) {  
  4.                 throw new DaoException("Entity is detached from DAO context");  
  5.             }  
  6.             infosDao targetDao = daoSession.getInfosDao();  
  7.             List<infos> infoesNew = targetDao._queryInfoType_Infoes(id);  
  8.             synchronized (this) {  
  9.                 if(infoes == null) {  
  10.                     infoes = infoesNew;  
  11.                 }  
  12.             }  
  13.         }  
  14.         return infoes;  
  15.     }  

这个方法,一看名字就知道,这是得到信息列表的,也就是说,我们在得到一个信息分类的同时,只要点一下这个方法,你就可以同时得到此分类下所有的信息,这对于信息量比较少的操作来说,是相当方便的方法。但是对于大数据量来说,就没有什么意义了。因为List这个分页处理不行,你可能会说,我直接修改它的代码不就完了吗,这个可行,可是GreenDao给出的说明是这个类,最好不要进行修改。

         它里面其它的方法,update,delete个人感觉没什么意义,我一直开始以为,它会产生联动的效果,就是删除这个分类的时候,子信息也会被删除,可是却没有发生。

         我们再来看一下infos.java里面的代码

       

[java]   view plain  copy
  1. public void setInfoType(infoType infoType) {  
  2.         synchronized (this) {  
  3.             this.infoType = infoType;  
  4.             typeId = infoType == null ? null : infoType.getId();  
  5.             infoType__resolvedKey = typeId;  
  6.         }  
  7.     }  

        这个个人感觉相当使用,就是我们在得到条信息的时候,可以同时取得它的分类信息。这个在显示详细信息的时候相当有用啊。

       下面我写的一些代码片断,就是两个页,一个显示信息分类,点击信息分类,显示此分类下所有的信息。信息分类和信息的添加,依然采用,toolbar的menu,修改与删除功能,是长按listView。下面我把代码放出来:

      1,  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. import com.guangda.dao.infoTypeDao;  
  10. import com.guangda.dao.infosDao;  
  11.   
  12. import java.util.List;  
  13.   
  14. import greendao.Users;  
  15. import greendao.infoType;  
  16. import greendao.infos;  
  17.   
  18. /** 
  19.  * 用户操作类 
  20.  * Created by cg on 2015/12/29. 
  21.  */  
  22. public class DbService {  
  23.     private static final String TAG = DbService.class.getSimpleName();  
  24.     private static DbService instance;  
  25.     private static Context appContext;  
  26.     private DaoSession mDaoSession;  
  27.     private UsersDao userDao;  
  28.     private infosDao infoDao;  
  29.     private infoTypeDao typeDao;  
  30.   
  31.   
  32.     private DbService() {  
  33.     }  
  34.   
  35.     /** 
  36.      * 采用单例模式 
  37.      * @param context     上下文 
  38.      * @return            dbservice 
  39.      */  
  40.     public static DbService getInstance(Context context) {  
  41.         if (instance == null) {  
  42.             instance = new DbService();  
  43.             if (appContext == null){  
  44.                 appContext = context.getApplicationContext();  
  45.             }  
  46.             instance.mDaoSession = BaseApplication.getDaoSession(context);  
  47.             instance.userDao = instance.mDaoSession.getUsersDao();  
  48.             instance.infoDao = instance.mDaoSession.getInfosDao();  
  49.             instance.typeDao = instance.mDaoSession.getInfoTypeDao();  
  50.         }  
  51.         return instance;  
  52.     }  
  53.   
  54.     /** 
  55.      * 根据用户id,取出用户信息 
  56.      * @param id           用户id 
  57.      * @return             用户信息 
  58.      */  
  59.     public Users loadNote(long id) {  
  60.         if(!TextUtils.isEmpty(id + "")) {  
  61.             return userDao.load(id);  
  62.         }  
  63.         return  null;  
  64.     }  
  65.   
  66.     /** 
  67.      * 取出所有数据 
  68.      * @return      所有数据信息 
  69.      */  
  70.     public List<Users> loadAllNote(){  
  71.         return userDao.loadAll();  
  72.     }  
  73.   
  74.     /** 
  75.      * 生成按id倒排序的列表 
  76.      * @return      倒排数据 
  77.      */  
  78.     public List<Users> loadAllNoteByOrder()  
  79.     {  
  80.         return userDao.queryBuilder().orderDesc(UsersDao.Properties.Id).list();  
  81.     }  
  82.   
  83.     /** 
  84.      * 根据查询条件,返回数据列表 
  85.      * @param where        条件 
  86.      * @param params       参数 
  87.      * @return             数据列表 
  88.      */  
  89.     public List<Users> queryNote(String where, String... params){  
  90.         return userDao.queryRaw(where, params);  
  91.     }  
  92.   
  93.   
  94.     /** 
  95.      * 根据用户信息,插件或修改信息 
  96.      * @param user              用户信息 
  97.      * @return 插件或修改的用户id 
  98.      */  
  99.     public long saveNote(Users user){  
  100.         return userDao.insertOrReplace(user);  
  101.     }  
  102.   
  103.   
  104.     /** 
  105.      * 批量插入或修改用户信息 
  106.      * @param list      用户信息列表 
  107.      */  
  108.     public void saveNoteLists(final List<Users> list){  
  109.         if(list == null || list.isEmpty()){  
  110.             return;  
  111.         }  
  112.         userDao.getSession().runInTx(new Runnable() {  
  113.             @Override  
  114.             public void run() {  
  115.                 for(int i=0; i<list.size(); i++){  
  116.                     Users user = list.get(i);  
  117.                     userDao.insertOrReplace(user);  
  118.                 }  
  119.             }  
  120.         });  
  121.   
  122.     }  
  123.   
  124.     /** 
  125.      * 删除所有数据 
  126.      */  
  127.     public void deleteAllNote(){  
  128.         userDao.deleteAll();  
  129.     }  
  130.   
  131.     /** 
  132.      * 根据id,删除数据 
  133.      * @param id      用户id 
  134.      */  
  135.     public void deleteNote(long id){  
  136.         userDao.deleteByKey(id);  
  137.         Log.i(TAG, "delete");  
  138.     }  
  139.   
  140.     /** 
  141.      * 根据用户类,删除信息 
  142.      * @param user    用户信息类 
  143.      */  
  144.     public void deleteNote(Users user){  
  145.         userDao.delete(user);  
  146.     }  
  147.   
  148.   
  149.     /**********************信息类别*********************************/  
  150.   
  151.     /** 
  152.      * 添加或修改信息类别 
  153.      * @param iType     信息类别 
  154.      * @return          返回修改信息的id或是新增的信息id 
  155.      */  
  156.     public Long SaveInfoType(infoType iType)  
  157.     {  
  158.         return typeDao.insertOrReplace(iType);  
  159.     }  
  160.   
  161.     /** 
  162.      * 根据类别id,删除信息类别 
  163.      * @param id      信息id 
  164.      */  
  165.     public void deleteInfoType(long id)  
  166.     {  
  167.         typeDao.load(id).delete();  
  168.   
  169.     }  
  170.   
  171.     /** 
  172.      * 按id倒排序,来显示所信息类别 
  173.      * @return      信息类别列表 
  174.      */  
  175.     public List<infoType> getAllInfoTypeList()  
  176.     {  
  177.         return  typeDao.queryBuilder().orderDesc(infoTypeDao.Properties.Id).list();  
  178.     }  
  179.   
  180.     /** 
  181.      * 根据类别id,取出类别信息 
  182.      * @param id 
  183.      * @return 
  184.      */  
  185.     public infoType getInfoType(long id)  
  186.     {  
  187.         return typeDao.load(id);  
  188.     }  
  189.   
  190.   
  191.     /**********************信息列表*********************************/  
  192.   
  193.     /** 
  194.      * 根据信息类别id,取出其类别下所有的信息 
  195.      * @param typeid         类别id 
  196.      * @return               信息列表 
  197.      */  
  198.     public List<infos> getInfosByTypeId(long typeid)  
  199.     {  
  200.         return typeDao.load(typeid).getInfoes();  
  201.     }  
  202.   
  203.     /** 
  204.      * 添加或修改 
  205.      * @param info    信息 
  206.      * @return        添加或修改的id 
  207.      */  
  208.     public long saveInfo(infos info)  
  209.     {  
  210.         return infoDao.insertOrReplace(info);  
  211.     }  
  212.   
  213.     /** 
  214.      * 返回所有新闻,用于测试类别删除的同步性 
  215.      * @return    返回所有新闻 
  216.      */  
  217.     public List<infos> getAllInfos()  
  218.     {  
  219.         return infoDao.loadAll();  
  220.     }  
  221.   
  222.     /** 
  223.      * 分页显示信息 
  224.      * @param typeid          信息类别 
  225.      * @param pageNum         当前页数 
  226.      * @param pageSize        每页显示数 
  227.      * @return                信息列表 
  228.      */  
  229.     public List<infos> getInfosBypageSize(long typeid,int pageNum,int pageSize)  
  230.     {  
  231.         return infoDao.queryBuilder().where(infosDao.Properties.TypeId.eq(typeid)).offset(pageNum-1).limit(pageSize).list();  
  232.     }  
  233. }  

   2, 分类信息页面布局代码:

     activity_two_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" android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     tools:context="com.example.cg.greendaolearn.twoTableActivity"  
  5.     android:orientation="vertical"  
  6.     android:background="@color/cornflowerblue">  
  7.   
  8.     <include  
  9.         layout="@layout/toolbar" />  
  10.   
  11.     <ListView  
  12.         android:id="@+id/lv_twoTable"  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="0dp"  
  15.         android:layout_weight="1" />  
  16.   
  17. </LinearLayout>  

   3, 分类信息页面中listView的item布局:

      activity_twotable_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.   
  6.     <TextView  
  7.         android:id="@+id/txt_twotable_item_typeName"  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:padding="5dp"  
  11.         android:textColor="@color/greenyellow"/>  
  12.   
  13. </LinearLayout>  

  4,信息列表的Adapter代码:

     twotable_type_adpter.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.infoType;  
  15.   
  16. /** 
  17.  * 两表间,1:n中主表信息列表的adapter 
  18.  * Created by cg on 2016/1/4. 
  19.  */  
  20. public class twotable_type_adpter extends BaseAdapter {  
  21.   
  22.     private List<infoType> list_type;  
  23.     private LayoutInflater inflater;  
  24.   
  25.     public twotable_type_adpter(Context context,List<infoType> list_type) {  
  26.         this.inflater = LayoutInflater.from(context);  
  27.         this.list_type = list_type;  
  28.     }  
  29.   
  30.     @Override  
  31.     public int getCount() {  
  32.         return list_type.size();  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object getItem(int position) {  
  37.         return list_type.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.   
  48.         twoTableType tType;  
  49.         if(convertView==null)  
  50.         {  
  51.             tType = new twoTableType();  
  52.             convertView = inflater.inflate(R.layout.activity_twotable_lv_item,null);  
  53.             tType.typeName = (TextView)convertView.findViewById(R.id.txt_twotable_item_typeName);  
  54.   
  55.             convertView.setTag(tType);  
  56.         }else  
  57.         {  
  58.             tType = (twoTableType)convertView.getTag();  
  59.         }  
  60.   
  61.         tType.typeName.setText(list_type.get(position).getInfoName());  
  62.   
  63.         return convertView;  
  64.     }  
  65.   
  66.     class twoTableType  
  67.     {  
  68.         TextView typeName;  
  69.     }  
  70. }  

    5, 信息列表程序代码:

       twoTableActivity.java

      

[java]   view plain  copy
  1. package com.example.cg.greendaolearn;  
  2.   
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.support.v7.app.AppCompatActivity;  
  6. import android.support.v7.widget.Toolbar;  
  7. import android.view.Menu;  
  8. import android.view.MenuItem;  
  9. import android.view.View;  
  10. import android.widget.AdapterView;  
  11. import android.widget.ListView;  
  12. import android.widget.Toast;  
  13.   
  14. import com.example.cg.greendaolearn.adpater.twotable_type_adpter;  
  15. import com.example.cg.greendaolearn.db.DbService;  
  16.   
  17. import java.util.ArrayList;  
  18. import java.util.List;  
  19.   
  20. import greendao.infoType;  
  21.   
  22. public class twoTableActivity extends AppCompatActivity implements twoTableDialogTypeFragment.addInfoTypeOnClickListener,twoTableDialogTypeItemFragment.txtClickListener {  
  23.   
  24.     private Toolbar toolbar;                                                   //定义toolbar  
  25.   
  26.     private ListView lv_twoTable;  
  27.     private List<infoType> list_type;  
  28.     private twotable_type_adpter tAdapter;  
  29.   
  30.     private DbService db;  
  31.   
  32.     private twoTableDialogTypeFragment twoDialogType;  
  33.     private twoTableDialogTypeItemFragment twoDialogTypeItem;  
  34.   
  35.     @Override  
  36.     protected void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.activity_two_table);  
  39.   
  40.         toolbar = (Toolbar)this.findViewById(R.id.toolbar);  
  41.         toolbar.setTitle("多表操作");                     // 标题的文字需在setSupportActionBar之前,不然会无效  
  42.         setSupportActionBar(toolbar);  
  43.   
  44.         db = DbService.getInstance(this);  
  45.   
  46.         initControls();  
  47.   
  48.         initData();  
  49.     }  
  50.   
  51.     /** 
  52.      * 初始化控件 
  53.      */  
  54.     private void initControls() {  
  55.         lv_twoTable = (ListView)findViewById(R.id.lv_twoTable);  
  56.         lv_twoTable.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  57.             @Override  
  58.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  59.                 Intent dIntent = new Intent();  
  60.                 dIntent.setClass(twoTableActivity.this,twoTableDetailActivity.class);  
  61.                 dIntent.putExtra("typeId", list_type.get(position).getId());  
  62.                 dIntent.putExtra("typeName", list_type.get(position).getInfoName());  
  63.                 startActivity(dIntent);  
  64.             }  
  65.         });  
  66.         /** 
  67.          * 长按事件 
  68.          */  
  69.         lv_twoTable.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {  
  70.             @Override  
  71.             public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {  
  72.                 twoDialogTypeItem = new twoTableDialogTypeItemFragment(list_type.get(position).getId(),position);  
  73.                 twoDialogTypeItem.show(getFragmentManager(),"item");  
  74.                 return true;  
  75.             }  
  76.         });  
  77.     }  
  78.   
  79.   
  80.     private void initData()  
  81.     {  
  82.         list_type = new ArrayList<>();  
  83.         list_type = db.getAllInfoTypeList();  
  84.         tAdapter = new twotable_type_adpter(this,list_type);  
  85.         lv_twoTable.setAdapter(tAdapter);  
  86.     }  
  87.   
  88.     @Override  
  89.     public boolean onCreateOptionsMenu(Menu menu) {  
  90.         // Inflate the menu; this adds items to the action bar if it is present.  
  91.         getMenuInflater().inflate(R.menu.menu_two_table, menu);  
  92.         return true;  
  93.     }  
  94.   
  95.     @Override  
  96.     public boolean onOptionsItemSelected(MenuItem item) {  
  97.         // Handle action bar item clicks here. The action bar will  
  98.         // automatically handle clicks on the Home/Up button, so long  
  99.         // as you specify a parent activity in AndroidManifest.xml.  
  100.         int id = item.getItemId();  
  101.   
  102.         //noinspection SimplifiableIfStatement  
  103.         if (id == R.id.menu_twoTable_typeAdd) {  
  104.             twoDialogType = new twoTableDialogTypeFragment(0,"",0);  
  105.             twoDialogType.show(getFragmentManager(),"add");  
  106.             return true;  
  107.         }  
  108.   
  109.         return super.onOptionsItemSelected(item);  
  110.     }  
  111.   
  112.   
  113.     @Override  
  114.     public void OnaddInfoTypeOnClickListener(String typeName, long typeId,int postion) {  
  115.         infoType iType = new infoType();  
  116.         iType.setInfoName(typeName);  
  117.         if(typeId!=0)  
  118.         {  
  119.             iType.setId(typeId);  
  120.         }  
  121.   
  122.         if(db.SaveInfoType(iType) < 1)  
  123.         {  
  124.             Toast.makeText(this"数据修改失败!", Toast.LENGTH_SHORT).show();  
  125.         }  
  126.   
  127.         if(typeId!=0)  
  128.         {  
  129.             list_type.remove(postion);  
  130.         }  
  131.         list_type.add(postion,iType);  
  132.         tAdapter.notifyDataSetChanged();  
  133.   
  134.         twoDialogType.dismiss();  
  135.     }  
  136.   
  137.     @Override  
  138.     public void OntxtClickListener(int flag,long typeId,int postion) {  
  139.         //0:删除 1:修改  
  140.         if(flag==0)  
  141.         {  
  142.             db.deleteInfoType(typeId);  
  143.             list_type.remove(postion);  
  144.             tAdapter.notifyDataSetChanged();  
  145.             Toast.makeText(this,"删除成功!",Toast.LENGTH_SHORT).show();  
  146.         }else  
  147.         {  
  148.             twoDialogType = new twoTableDialogTypeFragment(list_type.get(postion).getId(),list_type.get(postion).getInfoName(),postion);  
  149.             twoDialogType.show(getFragmentManager(),"edit");  
  150.         }  
  151.         twoDialogTypeItem.dismiss();  
  152.     }  
  153. }  

      6,点击add按钮弹出框布局:

      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.     <TextView  
  7.         android:layout_width="0dp"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_weight="1"  
  10.         android:text="新闻类别:"  
  11.         android:textColor="@color/black"  
  12.         android:padding="5dp"/>  
  13.     <EditText  
  14.         android:id="@+id/edit_twotable_typeName"  
  15.         android:layout_width="0dp"  
  16.         android:layout_height="wrap_content"  
  17.         android:layout_weight="2"  
  18.         android:textColor="@color/black"/>  
  19. </LinearLayout>  

   7,点击add按钮弹出框代码:

    twoTableDialogTypeFragment.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.  * 两表操作,1:n 新闻类别添加弹出框 
  14.  * Created by cg on 2016/1/4. 
  15.  */  
  16. public class twoTableDialogTypeFragment extends DialogFragment {  
  17.   
  18.   
  19.     private String typeName;  
  20.     private long typeId;  
  21.     private int postion;  
  22.   
  23.     private String btnText;  
  24.   
  25.     public twoTableDialogTypeFragment(long typeId,String typeName,int postion) {  
  26.         this.typeId = typeId;  
  27.         this.typeName = typeName;  
  28.         this.postion = postion;  
  29.     }  
  30.   
  31.     public interface addInfoTypeOnClickListener  
  32.     {  
  33.         void OnaddInfoTypeOnClickListener(String typeName,long typeId,int postion);  
  34.     }  
  35.   
  36.     private EditText edit_twotable_typeName;  
  37.   
  38.     @Override  
  39.     public Dialog onCreateDialog(Bundle savedInstanceState) {  
  40.         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  
  41.         // Get the layout inflater  
  42.         LayoutInflater inflater = getActivity().getLayoutInflater();  
  43.         View view = inflater.inflate(R.layout.fragment_twotable_typedialog, null);  
  44.   
  45.         edit_twotable_typeName = (EditText)view.findViewById(R.id.edit_twotable_typeName);  
  46.         edit_twotable_typeName.setText(typeName);  
  47.   
  48.         if(typeId!=0)  
  49.         {  
  50.             btnText = "修改";  
  51.         }else  
  52.         {  
  53.             btnText = "添加";  
  54.         }  
  55.   
  56.         builder.setView(view)  
  57.                 .setTitle("添加新闻类别")  
  58.                 .setPositiveButton(btnText,  
  59.                         new DialogInterface.OnClickListener() {  
  60.                             @Override  
  61.                             public void onClick(DialogInterface dialog, int id) {  
  62.                                 addInfoTypeOnClickListener addtype = (addInfoTypeOnClickListener)getActivity();  
  63.                                 addtype.OnaddInfoTypeOnClickListener(edit_twotable_typeName.getText().toString(),typeId,postion);  
  64.                             }  
  65.                         })  
  66.                 .setNegativeButton("取消",  
  67.                         new DialogInterface.OnClickListener() {  
  68.                             @Override  
  69.                             public void onClick(DialogInterface dialog, int which) {  
  70.                                 edit_twotable_typeName.setText("");  
  71.                             }  
  72.                         });  
  73.   
  74.         return builder.show();  
  75.     }  
  76. }  

 8,长按item弹出操作框布局:

   fragment_twotable_typeitemdialog.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_twotable_typeitem_edit"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="编辑"  
  12.         android:textSize="18sp"  
  13.         android:gravity="center"  
  14.         android:padding="15dp"/>  
  15.     <View  
  16.         android:layout_width="match_parent"  
  17.         android:layout_height="1dp"  
  18.         android:background="@color/gray"/>  
  19.     <TextView  
  20.         android:id="@+id/txt_twotable_typeitem_delete"  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="删除"  
  24.         android:textSize="18sp"  
  25.         android:gravity="center"  
  26.         android:padding="15dp"/>  
  27. </LinearLayout>  

9,长按item弹出操作框代码:

    twoTableDialogTypeItemFragment.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.  * 两表操作 1:n,长按弹出修改与删除按钮 
  14.  * Created by cg on 2016/1/4. 
  15.  */  
  16. public class twoTableDialogTypeItemFragment extends DialogFragment {  
  17.   
  18.   
  19.     public interface txtClickListener  
  20.     {  
  21.         void OntxtClickListener(int flag,long typeId,int postion);  
  22.     }  
  23.   
  24.     private long typeId;  
  25.     private int postion;  
  26.   
  27.     public twoTableDialogTypeItemFragment(long typeId,int postion) {  
  28.         this.typeId = typeId;  
  29.         this.postion = postion;  
  30.     }  
  31.   
  32.     private TextView txt_twotable_typeitem_edit;  
  33.     private TextView txt_twotable_typeitem_delete;  
  34.   
  35.     @Override  
  36.     public void onViewCreated(View view, Bundle savedInstanceState) {  
  37.         super.onViewCreated(view, savedInstanceState);  
  38.   
  39.         txt_twotable_typeitem_edit = (TextView)view.findViewById(R.id.txt_twotable_typeitem_edit);  
  40.         txt_twotable_typeitem_edit.setOnClickListener(new View.OnClickListener() {  
  41.             @Override  
  42.             public void onClick(View v) {  
  43.                 txtClickListener txtClick = (txtClickListener)getActivity();  
  44.                 txtClick.OntxtClickListener(1,typeId,postion);  
  45.             }  
  46.         });  
  47.         txt_twotable_typeitem_delete = (TextView)view.findViewById(R.id.txt_twotable_typeitem_delete);  
  48.         txt_twotable_typeitem_delete.setOnClickListener(new View.OnClickListener() {  
  49.             @Override  
  50.             public void onClick(View v) {  
  51.                 txtClickListener txtClick = (txtClickListener)getActivity();  
  52.                 txtClick.OntxtClickListener(0,typeId,postion);  
  53.             }  
  54.         });  
  55.     }  
  56.   
  57.     @Nullable  
  58.     @Override  
  59.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  60.   
  61.         getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);  
  62.         View view = inflater.inflate(R.layout.fragment_twotable_typeitemdialog,container);  
  63.   
  64.         return view;  
  65.     }  
  66. }  

 10,子页,信息列表布局:

    activity_two_table_detail.xml

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

11,子页,listview中item的布局:

 activty_twotable_detail_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.   
  7.     <TextView  
  8.         android:id="@+id/txt_twotable_detail_item_title"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:padding="5dp"  
  12.         android:textColor="@color/black"/>  
  13.     <TextView  
  14.         android:id="@+id/txt_twotable_detail_item_author"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:padding="5dp"  
  18.         android:textColor="@color/black"  
  19.         android:gravity="right"/>  
  20.     <TextView  
  21.         android:id="@+id/txt_twotable_detail_item_content"  
  22.         android:layout_width="match_parent"  
  23.         android:layout_height="wrap_content"  
  24.         android:padding="5dp"  
  25.         android:textColor="@color/black"/>  
  26. </LinearLayout>  

12, 子页,Adatper代码:

   twotable_info_adpter.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.infos;  
  15.   
  16. /** 
  17.  * 两表操作 1:n  子表的列表Adapter 
  18.  * Created by cg on 2016/1/4. 
  19.  */  
  20. public class twotable_info_adpter extends BaseAdapter {  
  21.   
  22.     private List<infos> list_info;  
  23.     private LayoutInflater inflater;  
  24.   
  25.     public twotable_info_adpter(Context context,List<infos> list_info) {  
  26.         this.inflater = LayoutInflater.from(context);  
  27.         this.list_info = list_info;  
  28.     }  
  29.   
  30.     @Override  
  31.     public int getCount() {  
  32.         return list_info.size();  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object getItem(int position) {  
  37.         return list_info.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.   
  48.         infoDetail iDetail;  
  49.         if(convertView==null)  
  50.         {  
  51.             iDetail = new infoDetail();  
  52.             convertView = inflater.inflate(R.layout.activty_twotable_detail_lv_item,null);  
  53.             iDetail.title = (TextView)convertView.findViewById(R.id.txt_twotable_detail_item_title);  
  54.             iDetail.author = (TextView)convertView.findViewById(R.id.txt_twotable_detail_item_author);  
  55.             iDetail.content = (TextView)convertView.findViewById(R.id.txt_twotable_detail_item_content);  
  56.   
  57.             convertView.setTag(iDetail);  
  58.         }else  
  59.         {  
  60.             iDetail = (infoDetail)convertView.getTag();  
  61.         }  
  62.   
  63.         iDetail.title.setText(list_info.get(position).getInfoTitle());  
  64.         iDetail.author.setText(list_info.get(position).getInfoType().getInfoName() + "-" + list_info.get(position).getInfoAuthor());  
  65.         iDetail.content.setText(list_info.get(position).getInfoContent());  
  66.   
  67.         return convertView;  
  68.     }  
  69.   
  70.     class infoDetail  
  71.     {  
  72.         TextView title;  
  73.         TextView author;  
  74.         TextView content;  
  75.     }  
  76. }  

13, 子页,代码:

    twoTableDetailActivity.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.widget.ListView;  
  9.   
  10. import com.example.cg.greendaolearn.adpater.twotable_info_adpter;  
  11. import com.example.cg.greendaolearn.db.DbService;  
  12.   
  13. import java.util.ArrayList;  
  14. import java.util.List;  
  15.   
  16. import greendao.infos;  
  17.   
  18. public class twoTableDetailActivity extends AppCompatActivity implements twoTableDetailDailogFragment.addDetailClickListener {  
  19.   
  20.     private Toolbar toolbar;                                                   //定义toolbar  
  21.   
  22.     private ListView lv_twoTable_detail;  
  23.     private List<infos> list_info;  
  24.     private twotable_info_adpter iAdapter;  
  25.   
  26.     public long typeId;  
  27.     public String typeName;  
  28.   
  29.     private DbService db;  
  30.   
  31.     private twoTableDetailDailogFragment detail;  
  32.   
  33.     @Override  
  34.     protected void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.         setContentView(R.layout.activity_two_table_detail);  
  37.   
  38.         typeId = getIntent().getLongExtra("typeId",0);  
  39.         typeName = getIntent().getStringExtra("typeName");  
  40.   
  41.         toolbar = (Toolbar)this.findViewById(R.id.toolbar);  
  42.         toolbar.setTitle(typeName);                     // 标题的文字需在setSupportActionBar之前,不然会无效  
  43.         setSupportActionBar(toolbar);  
  44.   
  45.   
  46.   
  47.         db = DbService.getInstance(this);  
  48.   
  49.         initControls();  
  50.   
  51.         initData();  
  52.     }  
  53.   
  54.     /** 
  55.      * 初始化数据 
  56.      */  
  57.     private void initData() {  
  58.         list_info = new ArrayList<>();  
  59.         list_info = db.getInfosByTypeId(typeId);  
  60.         iAdapter = new twotable_info_adpter(this,list_info);  
  61.         lv_twoTable_detail.setAdapter(iAdapter);  
  62.     }  
  63.   
  64.     /** 
  65.      * 初始化控件 
  66.      */  
  67.     private void initControls() {  
  68.         lv_twoTable_detail = (ListView)findViewById(R.id.lv_twoTable_detail);  
  69.     }  
  70.   
  71.     @Override  
  72.     public boolean onCreateOptionsMenu(Menu menu) {  
  73.         // Inflate the menu; this adds items to the action bar if it is present.  
  74.         getMenuInflater().inflate(R.menu.menu_two_table_detail, menu);  
  75.         return true;  
  76.     }  
  77.   
  78.     @Override  
  79.     public boolean onOptionsItemSelected(MenuItem item) {  
  80.         // Handle action bar item clicks here. The action bar will  
  81.         // automatically handle clicks on the Home/Up button, so long  
  82.         // as you specify a parent activity in AndroidManifest.xml.  
  83.         int id = item.getItemId();  
  84.   
  85.         //noinspection SimplifiableIfStatement  
  86.         if (id == R.id.menu_twoTable_detailAddAdd) {  
  87.   
  88.             detail = new twoTableDetailDailogFragment("","","",0,0);  
  89.             detail.show(getFragmentManager(),"add");  
  90.             return true;  
  91.         }  
  92.   
  93.         return super.onOptionsItemSelected(item);  
  94.     }  
  95.   
  96.   
  97.     @Override  
  98.     public void OnaddDetailClickListener(String title, String author, String content, long infoId, int postion) {  
  99.         infos info = new infos();  
  100.         info.setInfoAuthor(author);  
  101.         info.setInfoTitle(title);  
  102.         info.setInfoContent(content);  
  103.         info.setTypeId(typeId);  
  104.   
  105.         db.saveInfo(info);  
  106.         detail.dismiss();  
  107.   
  108.         list_info.add(0,info);  
  109.         iAdapter.notifyDataSetChanged();  
  110.     }  
  111. }  

14, 子页,添加信息布局:

     fragment_twotable_typedetaildialog.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.     <LinearLayout  
  7.         android:layout_width="match_parent"  
  8.         android:layout_height="wrap_content">  
  9.         <TextView  
  10.             android:layout_width="0dp"  
  11.             android:layout_height="wrap_content"  
  12.             android:layout_weight="1"  
  13.             android:text="标题:"  
  14.             android:gravity="center"  
  15.             android:padding="5dp"/>  
  16.         <EditText  
  17.             android:id="@+id/edit_detail_title"  
  18.             android:layout_width="0dp"  
  19.             android:layout_height="wrap_content"  
  20.             android:layout_weight="2"  
  21.             android:textColor="@color/black"/>  
  22.     </LinearLayout>  
  23.     <LinearLayout  
  24.         android:layout_width="match_parent"  
  25.         android:layout_height="wrap_content">  
  26.         <TextView  
  27.             android:layout_width="0dp"  
  28.             android:layout_height="wrap_content"  
  29.             android:layout_weight="1"  
  30.             android:text="作者:"  
  31.             android:gravity="center"  
  32.             android:padding="5dp"/>  
  33.         <EditText  
  34.             android:id="@+id/edit_detail_author"  
  35.             android:layout_width="0dp"  
  36.             android:layout_height="wrap_content"  
  37.             android:layout_weight="2"  
  38.             android:textColor="@color/black"/>  
  39.     </LinearLayout>  
  40.     <LinearLayout  
  41.         android:layout_width="match_parent"  
  42.         android:layout_height="wrap_content">  
  43.         <TextView  
  44.             android:layout_width="0dp"  
  45.             android:layout_height="wrap_content"  
  46.             android:layout_weight="1"  
  47.             android:text="内容:"  
  48.             android:gravity="center"  
  49.             android:padding="5dp"/>  
  50.         <EditText  
  51.             android:id="@+id/edit_detail_content"  
  52.             android:layout_width="0dp"  
  53.             android:layout_height="wrap_content"  
  54.             android:layout_weight="2"  
  55.             android:lines="3"  
  56.             android:gravity="top|left"  
  57.             android:textColor="@color/black"/>  
  58.     </LinearLayout>  
  59. </LinearLayout>  

15,子页,添加代码

      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.     }  

猜你喜欢

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