1. 程式人生 > >GreenDao的簡單使用說明(二)單表的增,刪,改,查

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<Users> loadAllNote(){
        return userDao.loadAll();
    }

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

    /**
     * 根據查詢條件,返回資料列表
     * @param where        條件
     * @param params       引數
     * @return             資料列表
     */
    public List<Users> 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<Users> list){
        if(list == null || list.isEmpty()){
            return;
        }
        userDao.getSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for(int i=0; i<list.size(); i++){
                    Users user = list.get(i);
                    userDao.insertOrReplace(user);
                }
            }
        });

    }

    /**
     * 刪除所有資料
     */
    public void deleteAllNote(){
        userDao.deleteAll();
    }

    /**
     * 根據id,刪除資料
     * @param id      使用者id
     */
    public void deleteNote(long id){
        userDao.deleteByKey(id);
        Log.i(TAG, "delete");
    }

    /**
     * 根據使用者類,刪除資訊
     * @param user    使用者資訊類
     */
    public void deleteNote(Users user){
        userDao.delete(user);
    }
}
  這個類就不多說了,大家一看就明白,很簡單,而且裡面也已經比較明確的給出了註解.

  第三步,設定佈局檔案

    1,Toolbar的程式碼:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar">

</android.support.v7.widget.Toolbar>

   當然了,你要是想使用toolbar,還要為其設定樣式,style.xml
<resources>

    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <!-- toolbar(actionbar)顏色 -->
        <item name="colorPrimary">#4876FF</item>
        <!-- 狀態列顏色 -->
        <item name="colorPrimaryDark">#3A5FCD</item>
        <!--toolbar文字的顏色-->
        <item name="@android:textColorPrimary">@android:color/white</item>
        <!-- 視窗的背景顏色 -->
        <item name="android:windowBackground">@android:color/white</item>
        <!-- SearchView -->
        <item name="searchViewStyle">@style/MySearchViewStyle</item>

        <item name="actionMenuTextColor">#ffffff</item>

    </style>

    <style name="AppTheme" parent="@style/AppBaseTheme">
        <item name="android:windowIsTranslucent">true</item>
    </style>

    <style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView"></style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

</resources>

 現在來看一下頁面主佈局,這個佈局其實很簡單,就是一個Toolbar,Toolbar上選單有一個新增的按鈕,而且下面是一個listView用來顯示使用者,點選新增按鈕,彈出一個對話方塊,顯示你要新增的項,填寫完後,儲存,新加的資料就會在listView中顯示出來.點選列表項,會彈出對框,上面有刪除與修改的選項,可以對此項進行刪除與修改,

  好,先來看一下activity_one_table.xml檔案

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.cg.greendaolearn.oneTableActivity"
    android:orientation="vertical">
    <include
        layout="@layout/toolbar" />

    <ListView
        android:id="@+id/lv_oneTable"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

 接下來,看一下,toolbar選單欄的佈局檔案,menu_one_table.xml.主要就是添加了一個新增的按鈕

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.cg.greendaolearn.oneTableActivity">

    <item android:id="@+id/menu_onetable_add"
        android:title="新增"
        app:showAsAction="never" />
</menu>

下面是listView列表顯示,哪麼我們先為這個列表設定一個item的佈局.程式碼比較簡單:'

  activity_onetable_lv_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/coral">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="姓名:"
                android:textColor="@color/white"
                android:padding="5dp"/>
            <TextView
                android:id="@+id/txt_onetable_uName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:padding="5dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="性別:"
                android:textColor="@color/white"
                android:padding="5dp"/>
            <TextView
                android:id="@+id/txt_onetable_uSex"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:padding="5dp"/>
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="年紀:"
                android:textColor="@color/white"
                android:padding="5dp"/>
            <TextView
                android:id="@+id/txt_onetable_age"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:padding="5dp"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="電話:"
                android:textColor="@color/white"
                android:padding="5dp"/>
            <TextView
                android:id="@+id/txt_onetable_tel"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/white"
                android:padding="5dp"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

 為再為它設計一個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<Users> list_user;

    public onetable_adapter(Context context,List<Users> 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

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="姓名:"/>
                <EditText
                    android:id="@+id/edit_onetable_name"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColor="@color/black"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="性別:"/>
                <EditText
                    android:id="@+id/edit_onetable_sex"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColor="@color/black"/>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1">
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="電話:"/>
                <EditText
                    android:id="@+id/edit_onetable_tel"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColor="@color/black"/>
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                >
                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:text="年紀:"/>
                <EditText
                    android:id="@+id/edit_onetable_age"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColor="@color/black"/>
            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

程式碼: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

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

    <TextView
        android:id="@+id/txt_onetable_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改"
        android:padding="10dp"
        android:gravity="center"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/gray"/>
    <TextView
        android:id="@+id/txt_onetable_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="刪除"
        android:padding="10dp"
        android:gravity="center"/>
</LinearLayout>

程式碼: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<Users> 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(),"修改");
        }


    }
}

執行效果圖: