Android範例 失物招領

2020-09-28 09:10:23

前言:這是Bmob 的經典案例,但是由於現在版本升級哪裡也不更新了,同時我輔導員助手這個專案正好有這個功能,拿來用一下,上次去計算機程式設計大賽,評委老師提了個建議,說最後用自己的資料庫,不要用公司的,這樣相當於資料不在自己手裡,我自己以前也騰訊上搭過了一個自己的學生Linux伺服器和mysql 也使用過 阿里雲mysql ,最後作為一個學生黨,還是比較喜歡Bomb,對於學生來說,真的是方便與便利。

建立一個失物招領的範例,繼承bmob資料庫,方便獲取、新增資料等。

先講 佈局RecyclerView

在使用RecyclerView時候,必須指定一個介面卡Adapter和一個佈局管理器LayoutManager。介面卡繼承RecyclerView.Adapter類,具體實現類似ListView的介面卡,取決於資料資訊以及展示的UI。佈局管理器用於確定RecyclerView中Item的展示方式以及決定何時複用已經不可見的Item,避免重複建立以及執行高成本的findViewById()方法。

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rl_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Item的佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/ll_item"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="#fff"
              android:orientation="vertical">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:text="@string/t1"
        android:textColor="#000"
        android:textSize="15sp"/>

    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:text="@string/con1"
        android:textColor="#9000"
        android:textSize="15sp"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp">

        <TextView
            android:id="@+id/tv_num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:background="#5CBE6C"
            android:padding="5dp"
            android:text="16642712339"
            android:textColor="#fff"/>

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="2019-05-21 17:04:11"
            android:textColor="#9000"/>
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginTop="5dp"
        android:background="#5000"/>
</LinearLayout>

建立介面卡

標準實現步驟如下:
建立Adapter:建立一個繼承RecyclerView.Adapter<VH>的Adapter類(VH是ViewHolder的類名)
建立ViewHolder:在Adapter中建立一個繼承RecyclerView.ViewHolder的靜態內部類,記為VH。ViewHolder的實現和ListView的ViewHolder實現幾乎一樣。
③ 在Adapter中實現3個方法

nCreateViewHolder()

這個方法主要生成每個Item inflater出一個View,但是該方法返回的是一個ViewHolder。該方法把View直接封裝在ViewHolder中,然後我們面向的是ViewHolder這個範例,當然這個ViewHolder需要我們自己去編寫。

  @Override
    public LostAndFoundHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.lost_item, parent, false);
        LostAndFoundHolder lostAndFoundHolder = new LostAndFoundHolder(view);
        return lostAndFoundHolder;
    }

onBindViewHolder()
這個方法主要用於適配渲染資料到View中。方法提供給你了一viewHolder而不是原來的convertView。

getItemCount()
這個方法就類似於BaseAdapter的getCount方法了,即總共有多少個條目。

public class LostAndFoundAdapter extends RecyclerView.Adapter<LostAndFoundAdapter.LostAndFoundHolder> {
    private Context mContext;
    private List<LostInfomationReq> lostInfosData;
    private ItemClickListener mItemClickListener;
    public final static int EDIT_CODE = 998;
    public final static int DELETE_CODE = 997;

    public LostAndFoundAdapter(Context context) {
        this.mContext = context;
    }


    public void setData(List<LostInfomationReq> data) {
        this.lostInfosData = data;
    }

    @Override
    public LostAndFoundHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.lost_item, parent, false);
        LostAndFoundHolder lostAndFoundHolder = new LostAndFoundHolder(view);
        return lostAndFoundHolder;
    }

    @Override
    public void onBindViewHolder(final LostAndFoundHolder holder, final int position) {
        if (lostInfosData != null) {
            LostInfomationReq lostInfomationReq = lostInfosData.get(position);
            holder.title.setText(lostInfomationReq.getTitle());
            holder.desc.setText(lostInfomationReq.getDesc());
            holder.phoneNum.setText(lostInfomationReq.getPhoneNum());
            holder.time.setText(lostInfomationReq.getCreatedAt());

            holder.llItem.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    //mLongClickListener.onLongClick(position);
                    showWindow(holder, position);
                    return false;
                }
            });
        }
    }

    private void showWindow(LostAndFoundHolder holder, final int pos) {
        //載入佈局檔案
        View contentview = LayoutInflater.from(mContext).inflate(R.layout.pop_window_view,null);
        final PopupWindow popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        //設定焦點
        popupWindow.setFocusable(true);
        //觸控框外
        popupWindow.setOutsideTouchable(true);
        //點選空白處的時候讓PopupWindow消失
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        //設定偏移量
        popupWindow.showAsDropDown(holder.time, 300, -100);

        //showAsDropDown(View anchor):相對某個控制元件的位置(正左下方),無偏移
       // showAsDropDown(View anchor, int xoff, int yoff):相對某個控制元件的位置,有偏移
        //showAtLocation(View parent, int gravity, int x, int y):相對於父控制元件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設定偏移或無偏移

        //點選編輯按鈕
        contentview.findViewById(R.id.edit_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回撥給主介面,進行資料操作
                mItemClickListener.onEditOrDeleteClick(pos, EDIT_CODE);
                //銷燬彈出框
                popupWindow.dismiss();
            }
        });

        //點選刪除按鈕
        contentview.findViewById(R.id.delete_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回撥給主介面,進行資料操作
                mItemClickListener.onEditOrDeleteClick(pos, DELETE_CODE);
                //銷燬彈出框
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public int getItemCount() {
        return lostInfosData.size() == 0 ? 0 : lostInfosData.size();
    }

    public class LostAndFoundHolder extends RecyclerView.ViewHolder {
        private TextView title;
        private TextView desc;
        private TextView time;
        private TextView phoneNum;
        private LinearLayout llItem;

        public LostAndFoundHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.tv_title);
            desc = (TextView) itemView.findViewById(R.id.tv_desc);
            time = (TextView) itemView.findViewById(R.id.tv_time);
            phoneNum = (TextView) itemView.findViewById(R.id.tv_num);
            llItem = (LinearLayout) itemView.findViewById(R.id.ll_item);
        }
    }

    //設定長按事件
    public void setLongClickListener(ItemClickListener clickListener) {
        this.mItemClickListener = clickListener;
    }

    public interface ItemClickListener {
        void onEditOrDeleteClick(int position, int code);
    }
}

其中包括 PopupWindow的使用

長按item 出現彈窗

pop_window_view.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/edit_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/blue"
        android:padding="10dp"
        android:text="新增"
        android:textColor="#fff"/>

    <TextView
        android:id="@+id/delete_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@color/blue"
        android:text="刪除"
        android:textColor="#fff" />
</LinearLayout>

使用PopupWindow很簡單,可以總結為三個步驟:

  1. 建立PopupWindow物件範例;
  2. 設定背景、註冊事件監聽器和新增動畫;
  3. 顯示PopupWindow。
public class LostFoodFragment extends Fragment implements View.OnClickListener, LostAndFoundAdapter.ItemClickListener  {
    private RecyclerView recyclerView;
    private LostAndFoundAdapter lostAndFoundAdapter;
    private List<LostInfomationReq> lostInfomationReqList;

    private long exitTime = 0;
    private final static int REQUEST_CODE = 999;
    public LostFoodFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lost_food,container,false);
        initView(view);
        initData();
        return view;
    }


    private void initView(View view) {
        recyclerView = (RecyclerView) view.findViewById(R.id.rl_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        lostAndFoundAdapter = new LostAndFoundAdapter(getActivity());
        lostAndFoundAdapter.setLongClickListener(this);

    }
    private void initData() {
        BmobQuery<LostInfomationReq> lostInfomationReqBmobQuery = new BmobQuery<>();
        lostInfomationReqBmobQuery.order("-updatedAt");//排序
        lostInfomationReqBmobQuery.findObjects(new FindListener<LostInfomationReq>() {
            @Override
            public void done(List<LostInfomationReq> list, BmobException e) {
                if (e == null) {
                    lostInfomationReqList = list;
                    lostAndFoundAdapter.setData(list);
                    recyclerView.setAdapter(lostAndFoundAdapter);
                } else {
                    showToast("查詢資料失敗");
                }
            }
        });
    }
    private void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onEditOrDeleteClick(int position, int code) {
        if (code == LostAndFoundAdapter.EDIT_CODE) {
            Intent intent = new Intent(getActivity(), Lost_fondActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("editData", lostInfomationReqList.get(position));
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUEST_CODE);
        } else if (code == LostAndFoundAdapter.DELETE_CODE) {
            deleteItemData(position);
        }

    }

    private void deleteItemData(final int position) {
        if (lostInfomationReqList.size() != 0) {
            LostInfomationReq lostInfomationReq = new LostInfomationReq();
            lostInfomationReq.setObjectId(lostInfomationReqList.get(position).getObjectId());
            lostInfomationReq.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        lostInfomationReqList.remove(position);
                        lostAndFoundAdapter.setData(lostInfomationReqList);
                        lostAndFoundAdapter.notifyDataSetChanged();
                    } else {
                        showToast("刪除資料失敗");
                    }
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    refreshData();//資料重新整理
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    /**
     * 查詢資料庫中最新的資料
     * */
    private void refreshData() {
        BmobQuery<LostInfomationReq> lostInfomationReqBmobQuery = new BmobQuery<>();
        lostInfomationReqBmobQuery.order("-updatedAt");//按更新時間排序
        lostInfomationReqBmobQuery.findObjects(new FindListener<LostInfomationReq>() {
            @Override
            public void done(List<LostInfomationReq> list, BmobException e) {
                if (e == null) {
                    lostInfomationReqList = list;
                    lostAndFoundAdapter.setData(list);
                    lostAndFoundAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}

RecyclerView實現Item點選事件處理

RecyclerView並沒有像ListView那樣提供了OnItemClick,OnItemLongClick等事件回撥介面,所以,我們需要自己去實現。

定義回撥事件介面

  public interface ItemClickListener {
        void onEditOrDeleteClick(int position, int code);
    }

 宣告該介面,並提供setter方法

    //設定長按事件
    public void setLongClickListener(ItemClickListener clickListener) {
        this.mItemClickListener = clickListener;
    }

實現介面

implements View.OnClickListener, LostAndFoundAdapter.ItemClickListener

實現編輯和刪除方法

 @Override
    public void onEditOrDeleteClick(int position, int code) {
        if (code == LostAndFoundAdapter.EDIT_CODE) {
            Intent intent = new Intent(getActivity(), Lost_fondActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("editData", lostInfomationReqList.get(position));
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUEST_CODE);
        } else if (code == LostAndFoundAdapter.DELETE_CODE) {
            deleteItemData(position);
        }

    }

    private void deleteItemData(final int position) {
        if (lostInfomationReqList.size() != 0) {
            LostInfomationReq lostInfomationReq = new LostInfomationReq();
            lostInfomationReq.setObjectId(lostInfomationReqList.get(position).getObjectId());
            lostInfomationReq.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        lostInfomationReqList.remove(position);
                        lostAndFoundAdapter.setData(lostInfomationReqList);
                        lostAndFoundAdapter.notifyDataSetChanged();
                    } else {
                        showToast("刪除資料失敗");
                    }
                }
            });
        }
    }

通過引數傳遞資料判斷 點選按鈕

 //點選編輯按鈕
                contentview.findViewById(R.id.edit_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //回撥給主介面,進行資料操作
                        mItemClickListener.onEditOrDeleteClick(pos, EDIT_CODE);
                        //銷燬彈出框
                        popupWindow.dismiss();
                    }
                });

                //點選刪除按鈕
                contentview.findViewById(R.id.delete_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //回撥給主介面,進行資料操作
                        mItemClickListener.onEditOrDeleteClick(pos, DELETE_CODE);
                        //銷燬彈出框
                        popupWindow.dismiss();
            }
        });

這個和前幾篇一樣,將資料獲取和資料插入。寫部落格的好處,就是梳理思路,理解過程。

失物招領 我來二改了 只有自己釋出的可以長按編輯修改/刪除  也可以新發佈一個新的

實現物品的釋出、呈現、修改和刪除,使用者撿到或丟失物品,開啟手機軟體,填寫物品的招領資訊(標題、描述和聯絡方式);所有使用者可以檢視到失物和招領的資訊列表,如果使用者自己釋出的訊息,長按彈出懸浮窗,可進行編輯和刪除。

基於Bmob後端雲,新增失物/招領資訊到伺服器中。查詢失物招領所有資料,在列表中顯示所有使用者釋出的失物/招領資訊。編輯資料,會將該資料內容直接顯示到新增失物招領介面,提交後進行資料更新。刪除資料,刪除已釋出的失物/招領資訊。

效果圖:

 

public class LostAndFoundAdapter extends RecyclerView.Adapter<LostAndFoundAdapter.LostAndFoundHolder> {
    private Context mContext;
    private List<LostInformation> mLostInformationList;
    private ItemClickListener mItemClickListener;
    public final static int EDIT_CODE = 998;
    public final static int DELETE_CODE = 997;

    public LostAndFoundAdapter(Context context) {
        mContext = context;
    }

    public void setLostInformationList(List<LostInformation> lostInformationList) {
        mLostInformationList = lostInformationList;
    }

    @NonNull
    @Override
    public LostAndFoundHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_lost, parent, false);
        LostAndFoundHolder lostAndFoundHolder = new LostAndFoundHolder(view);
        return lostAndFoundHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull LostAndFoundHolder holder, int position) {
        if (!mLostInformationList.isEmpty()) {
            LostInformation lostInformation = mLostInformationList.get(position);
            holder.title.setText(lostInformation.getTitle());
            holder.desc.setText(lostInformation.getDesc());
            holder.telephone.setText(lostInformation.getPhoneNum());
            holder.time.setText(lostInformation.getCreatedAt());
            holder.llItem.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
                    if (myUser.getUsername().equals(lostInformation.getUsername())){
                        showWindow(holder, position);
                        return true;
                    }
                    return false;
                }
            });
        }

    }

    private void showWindow(LostAndFoundHolder holder, int position) {
        //載入佈局檔案
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_window_view, null);
        final PopupWindow popupWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        //設定焦點
        popupWindow.setFocusable(true);
        //觸控框外
        popupWindow.setOutsideTouchable(true);
        //點選空白處的時候讓PopupWindow消失
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        //設定偏移量
        popupWindow.showAsDropDown(holder.time, 300, -100);
        //點選編輯按鈕
        contentView.findViewById(R.id.edit_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回撥給主介面,進行資料操作
                mItemClickListener.onEditOrDeleteClick(position, EDIT_CODE);
                //銷燬彈出框
                popupWindow.dismiss();
            }
        });

        //點選刪除按鈕
        contentView.findViewById(R.id.delete_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //回撥給主介面,進行資料操作
                mItemClickListener.onEditOrDeleteClick(position, DELETE_CODE);
                //銷燬彈出框
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public int getItemCount() {
        return mLostInformationList.size() == 0 ? 0 : mLostInformationList.size();
    }

    //設定長按事件
    public void setLongClickListener(ItemClickListener clickListener) {
        this.mItemClickListener = clickListener;
    }

    public interface ItemClickListener {
        void onEditOrDeleteClick(int position, int code);
    }

    public class LostAndFoundHolder extends RecyclerView.ViewHolder {
        private TextView title;
        private TextView desc;
        private TextView time;
        private TextView telephone;
        private LinearLayout llItem;

        public LostAndFoundHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.lost_title);
            desc = (TextView) itemView.findViewById(R.id.lost_desc);
            time = (TextView) itemView.findViewById(R.id.lost_time);
            telephone = (TextView) itemView.findViewById(R.id.lost_telephone);
            llItem = (LinearLayout) itemView.findViewById(R.id.ll_item);
        }
    }

}
public class LostFoundFragment extends BaseFragment implements LostAndFoundAdapter.ItemClickListener {
    @BindView(R.id.recyclerview_lost)
    RecyclerView recyclerViewLost;
    LostAndFoundAdapter lostAndFoundAdapter;
    List<LostInformation> mLostInformationList;

    public static Fragment getInstance() {
        Fragment fragment = new LostFoundFragment();
        return fragment;
    }

    @Override
    protected int contentViewID() {
        return R.layout.fragment_lost_found;
    }

    @Override
    protected void initialize() {
        EventBus.getDefault().register(this);
        lostAndFoundAdapter = new LostAndFoundAdapter(getContext());
        lostAndFoundAdapter.setLongClickListener(this);
        recyclerViewLost.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        queryData();
    }

    private void queryData() {
        BmobQuery<LostInformation> lostInformationBmobQuery = new BmobQuery<>();
        lostInformationBmobQuery.order("-updatedAt");//排序
        lostInformationBmobQuery.findObjects(new FindListener<LostInformation>() {
            @Override
            public void done(List<LostInformation> object, BmobException e) {
                if (e == null) {
                    mLostInformationList = object;
                    lostAndFoundAdapter.setLostInformationList(mLostInformationList);
                    recyclerViewLost.setAdapter(lostAndFoundAdapter);
                } else {
                    ToastUtils.showShort(getContext(), getString(R.string.tip_query_lost));
                }
            }
        });
    }

    @Override
    public void onEditOrDeleteClick(int position, int code) {
        if (code == LostAndFoundAdapter.EDIT_CODE) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("editData", mLostInformationList.get(position));
            startActivity(EditLostActivity.class, bundle);
        }
        if (code == LostAndFoundAdapter.DELETE_CODE) {
            deleteItemData(position);
        }

    }


    private void deleteItemData(int position) {
        if (!mLostInformationList.isEmpty()) {
            LostInformation lostInformation = new LostInformation();
            lostInformation.setObjectId(mLostInformationList.get(position).getObjectId());
            lostInformation.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        mLostInformationList.remove(position);
                        lostAndFoundAdapter.setLostInformationList(mLostInformationList);
                        lostAndFoundAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showShort(getContext(), getString(R.string.delete_failure));
                    }
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        switch (messageEvent.getMessage()) {
            case ConstantConfig.ADD_LOST_PUSH:
            case ConstantConfig.UPDATE_LOST_PUSH:
                refreshData();
                break;
            default:

        }
    }


    private void refreshData() {
        BmobQuery<LostInformation> lostInformationBmobQuery = new BmobQuery<>();
        lostInformationBmobQuery.order("-updatedAt");//排序
        lostInformationBmobQuery.findObjects(new FindListener<LostInformation>() {
            @Override
            public void done(List<LostInformation> object, BmobException e) {
                if (e == null) {
                    mLostInformationList = object;
                    lostAndFoundAdapter.setLostInformationList(mLostInformationList);
                    lostAndFoundAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showShort(getContext(), getString(R.string.tip_query_lost));
                }
            }
        });
    }

    @OnClick(R.id.btn_add_lost)
    public void OnClick(View view){
        startActivity(EditLostActivity.class);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
public class EditLostActivity extends BaseActivity {
    @BindView(R.id.lost_username)
    TextView lostUsername;
    @BindView(R.id.lost_et_title)
    TextInputEditText etLostTitle;
    @BindView(R.id.lost_et_contact)
    TextInputEditText etLostContact;
    @BindView(R.id.lost_et_desc)
    EditText etLostDesc;
    private boolean isEditLost = false;
    LostInformation lostInformation;

    @Override
    protected int contentViewID() {
        return R.layout.activity_edit_lost;
    }

    @Override
    protected void initialize() {
        setTopTitle(getString(R.string.add_lost), true);
        setLeftBtnFinish();
        MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
        lostUsername.setText(myUser.getUsername());
        Intent intent = getIntent();
        lostInformation = (LostInformation) intent.getSerializableExtra("editData");
        if (lostInformation != null) {
            isEditLost = true;
            setLostText(lostInformation);
        }
    }

    private void setLostText(LostInformation lostInformation) {
        lostUsername.setText(lostInformation.getUsername());
        etLostTitle.setText(lostInformation.getTitle());
        etLostContact.setText(lostInformation.getPhoneNum());
        etLostDesc.setText(lostInformation.getDesc());
    }

    @OnClick(R.id.btn_lost)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_lost:
                if (isEditLost == true) {
                    updateLostInfo();
                } else {
                    addLostInfo();
                }
                break;
            default:
        }
    }

    private void addLostInfo() {
        MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
        LostInformation newLostInformation = new LostInformation();
        newLostInformation.setUsername(myUser.getUsername());
        newLostInformation.setTitle(etLostTitle.getText().toString());
        newLostInformation.setPhoneNum(etLostContact.getText().toString());
        newLostInformation.setDesc(etLostDesc.getText().toString());
        newLostInformation.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    ToastUtils.showShort(EditLostActivity.this, getString(R.string.lost_add_success));
                    EventBus.getDefault().post(new MessageEvent(ConstantConfig.ADD_LOST_PUSH));
                } else {
                    ToastUtils.showShort(EditLostActivity.this, getString(R.string.lost_add_failure));
                }
            }
        });
    }

    private void updateLostInfo() {
        MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
        LostInformation newLostInformation = new LostInformation();
        newLostInformation.setUsername(myUser.getUsername());
        newLostInformation.setTitle(etLostTitle.getText().toString());
        newLostInformation.setPhoneNum(etLostContact.getText().toString());
        newLostInformation.setDesc(etLostDesc.getText().toString());
        newLostInformation.update(lostInformation.getObjectId(),new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    ToastUtils.showShort(EditLostActivity.this, getString(R.string.lost_update_success));
                    EventBus.getDefault().post(new MessageEvent(ConstantConfig.UPDATE_LOST_PUSH));
                } else {
                    ToastUtils.showShort(EditLostActivity.this, getString(R.string.lost_update_failure));
                }
            }
        });
    }
}