当用户点击recyclerview时,数据显示两次

时间:2018-06-16 17:54:31

标签: android-recyclerview listadapter

我正在尝试显示将从DB检索的数据。从数据库加载数据工作正常,但在用户从数据库中搜索第二个数据后点击它时,recyclelerview中的数据将被触发两次。

我的片段类显示recyclerview

public class UserGroupUserListFragment extends Fragment {
private final static String TAG_USER_GROUP_LIST_FRAGMENT = "UserGroupListFragment";
private final static String TAG_USER_GROUP_USER_LIST_FRAGMENT = "UserGroupUserListFragment";

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private final Response.ErrorListener onPostsSearchUserGroupUserError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, error.toString());
    }
};
private View view;
private RecyclerView recyclerView = null;
private UserGroupUser1ListAdapter listAdapter = null;
private boolean shouldAdd = false;
private final Response.Listener<String> onPostsSearchUserGroupUserLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        List<UserBean> list = ConnectionUtil.getInstance().getResponseList(ConsDef.MODULE_TITLE_USER_GROUP_USER, response);
        if (list != null) {
            if (!list.isEmpty()) {
                addGroupUser(list);
            } else {
                NotificationUtil.getInstance().showNoInfo(ConsDef.NO_USER, getContext());
            }
        } else {
            NotificationUtil.getInstance().showExceptionNotification(getContext());
        }
    }
};

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public UserGroupUserListFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment UserGroupUserListFragment.
 */
// TODO: Rename and change types and number of parameters
public static UserGroupUserListFragment newInstance(String param1, String param2) {
    UserGroupUserListFragment fragment = new UserGroupUserListFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.user_group_user_list_fragment, container, false);

    init();

    return view;
}

private void init()
{
    updateUI();
}

private void updateUI() {
    Handler mHandler = new Handler();

    try {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                final Button addBtn = view.findViewById(R.id.searchUserGroupUserBtn);
                addBtn.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        popupSearchDialog(v);
                    }
                });

                searchUserGroupUser(((UserGroupBean) MemoryUtil.getInstance().getObjectInMemory()).getUserGroupID());
            }
        });
    } catch (Exception ex) {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, ex.toString());
    }
}

private void popupSearchDialog(View view)
{
    try
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
        alertDialog.setTitle(R.string.search_group_user);
        alertDialog.setMessage(R.string.user_assigned_to_group);

        final EditText input = new EditText(getContext());
        alertDialog.setView(input);

        alertDialog.setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                String value = input.getText().toString();
                if(value.length() > 0)
                {
                    searchFilterUserGroupUser(value);
                }
                else
                {
                    NotificationUtil.getInstance().showFillInData(ConsDef.FILL_USERNAME, getContext());
                }
            }
        });
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog dialog = alertDialog.create();
        dialog.show();
    }
    catch (Exception ex)
    {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, ex.toString());
        ex.printStackTrace();
    }
}

private void searchFilterUserGroupUser(String username)
{
    try {
        String connectionString = ConnectionUtil.getInstance().getWebConnectionWithParam(ConsDef.MODULE_TITLE_USER_GROUP_USER, ConsDef.SERVICE_METHOD_NAME_SEARCH_FILTER_USER_GROUP_USER, username);

        StringRequest request = new StringRequest(Request.Method.GET, connectionString, onPostsSearchUserGroupUserLoaded, onPostsSearchUserGroupUserError);
        Log.i(ConsDef.TAG_DEBUG_SEARCH_USER_GROUP_USER, request.toString());

        VolleyConnection.getInstance().addRequest(getContext(), request, ConsDef.SEARCH_EVENT_CODE, ConsDef.SEARCH_USER_GROUP);
    } catch (Exception ex) {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, ex.toString());
    }
}
private void searchUserGroupUser(int userGroupID) {
    try {
        String connectionString = ConnectionUtil.getInstance().getWebConnectionWithParam(ConsDef.MODULE_TITLE_USER_GROUP_USER, ConsDef.SERVICE_METHOD_NAME_SEARCH_USER_GROUP_USER, String.valueOf(userGroupID));

        StringRequest request = new StringRequest(Request.Method.GET, connectionString, onPostsSearchUserGroupUserLoaded, onPostsSearchUserGroupUserError);
        Log.i(ConsDef.TAG_DEBUG_SEARCH_USER_GROUP_USER, request.toString());

        VolleyConnection.getInstance().addRequest(getContext(), request, ConsDef.SEARCH_EVENT_CODE, ConsDef.SEARCH_USER_GROUP);
    } catch (Exception ex) {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, ex.toString());
    }
}

private void addGroupUser(List<UserBean> list) {
    try {
        if(listAdapter != null
                && recyclerView != null)
        {
            int oldListSize = listAdapter.getItemCount();
            listAdapter.clear();
            listAdapter.notifyItemRangeChanged(0, oldListSize);

            recyclerView.removeView(view);
            recyclerView.setAdapter(null);
            recyclerView.setLayoutManager(null);
            recyclerView.setItemAnimator(null);
            recyclerView.removeItemDecoration(null);
            recyclerView.setHasFixedSize(false);
            recyclerView.removeOnItemTouchListener(null);

            listAdapter.getList().addAll(list);
            listAdapter.notifyDataSetChanged();
        }
        else
        {
            recyclerView = (RecyclerView) view.findViewById(R.id.userGroupUserRecyclerView);

            listAdapter = new UserGroupUser1ListAdapter(list);
            listAdapter.notifyDataSetChanged();
        }

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this.getContext(), LinearLayoutManager.VERTICAL));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(listAdapter);

        recyclerView.addOnItemTouchListener(new RecyclerUserGroupUserTouchListener(this.getContext(), recyclerView, new RecyclerUserGroupUserTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
                UserBean userBean = (UserBean) list.get(position);
                userBean.setIsUpdate(true);

                System.out.println("position : " + position);
                System.out.println("userID : " + userBean.getUserID());
                System.out.println("email : " + userBean.getEmail());

                selectGroupUser(list, position);
            }

            @Override
            public void onLongClick(View view, int position) {

            }
        }));
    } catch (Exception ex) {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, ex.toString());
        ex.printStackTrace();
    }
}

private void selectGroupUser(List<UserBean> list, int position)
{
    UserGroupUserBean userGroupUserBean = null;

    try
    {

        UserBean userBean = (UserBean) list.get(position);
        userBean.setIsUpdate(true);

        /*
        System.out.println("userID : " + userBean.getUserID());
        System.out.println("username : " + userBean.getUsername());
        System.out.println("position : " + position);
        */

        if(userBean.getShouldBeAssignedToGroup()){
            UserGroupBean userGroupBean = (UserGroupBean) MemoryUtil.getInstance().getObjectInMemory();

            userGroupUserBean = new UserGroupUserBean();
            userGroupUserBean.setUserGroupID(userGroupBean.getUserGroupID());
            userGroupUserBean.setUserID(userBean.getUserID());
            userGroupUserBean.setUsername(userBean.getUsername());
            userGroupUserBean.setPasswd(userBean.getPasswd());
            userGroupUserBean.setName(userBean.getName());
            userGroupUserBean.setContactNumber(userBean.getContactNumber());
            userGroupUserBean.setEmail(userBean.getEmail());
            userGroupUserBean.setIsUpdate(true);

            MemoryUtil.getInstance().setObjectInMemory(userGroupUserBean);
        }
        else
        {
            MemoryUtil.getInstance().setObjectInMemory(userBean);
        }

        getFragmentManager().beginTransaction().replace(R.id.content_frame, new UserGroupUserRegistrationFragment()).addToBackStack(TAG_USER_GROUP_USER_LIST_FRAGMENT).commit();
    }
    catch (Exception ex)
    {
        Log.e(ConsDef.TAG_ERROR_SEARCH_USER_GROUP_USER, ex.toString());
        ex.printStackTrace();
    }
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;

    getFragmentManager().beginTransaction().replace(R.id.content_frame, new UserGroupListFragment()).addToBackStack(TAG_USER_GROUP_LIST_FRAGMENT).commit();
}`

我的ListAdapter

public class UserGroupUser1ListAdapter extends RecyclerView.Adapter<UserGroupUser1ListAdapter.MyUserGroupUserHolder> {

private List<UserBean> list;

public UserGroupUser1ListAdapter(List<UserBean> list) {
    this.list = list;
}

@Override
public MyUserGroupUserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_group_user_list_row, parent, false);

    return new MyUserGroupUserHolder(itemView);
}

@Override
public void onBindViewHolder(MyUserGroupUserHolder holder, int position) {
    UserBean userBean = null;
    StringBuilder stringBuilder = null;

    try
    {
        userBean = this.list.get(position);

        stringBuilder = new StringBuilder();
        stringBuilder.append(userBean.getName());
        stringBuilder.append("\n");
        stringBuilder.append(userBean.getContactNumber());
        stringBuilder.append("\n");
        stringBuilder.append(userBean.getEmail());
        stringBuilder.append("\n");
        stringBuilder.append(userBean.getRoleBean().getRoleName());

        holder.username.setText(userBean.getUsername());
        holder.userInfo.setText(stringBuilder.toString());
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

@Override
public int getItemCount() {
    return this.list.size();
}

public void clear() {
    this.list.clear();
}

public List<UserBean> getList() {
    return this.list;
}

public void restoreUserGroupUser(UserBean userBean, int position) {
    this.list.add(position, userBean);
    // notify item added by position
    notifyItemInserted(position);
}

public class MyUserGroupUserHolder extends RecyclerView.ViewHolder {
    public TextView username, userInfo;

    public MyUserGroupUserHolder(View view) {
        super(view);
        username = (TextView) view.findViewById(R.id.userGroupUserUsernameRow);
        userInfo = (TextView) view.findViewById(R.id.userGroupUserInfoRow);
    }
}

}

user_group_user_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="@dimen/row_padding_vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/row_padding_vertical">

<TextView
    android:id="@+id/userGroupUserUsernameRow"
    android:layout_width="150sp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:textColor="@color/user_group_username"
    android:textSize="16sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/userGroupUserInfoRow"
    android:layout_width="200sp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20sp"
    android:layout_toEndOf="@id/userGroupUserUsernameRow"
    android:textColor="@color/user_group_user_info"
    android:textSize="16sp"
    android:textStyle="bold"/>
</RelativeLayout>

user_group_user_list_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".userEvent.UserGroupUserListFragment">>

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/propertyBlankText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toStartOf="@+id/addNewPropertyBtn"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        android:visibility="invisible" />

    <Button
        android:id="@+id/searchUserGroupUserBtn"
        android:layout_width="25dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="?android:attr/selectableItemBackground"
        android:drawableLeft="@drawable/action_search"/>
</RelativeLayout>

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

0 个答案:

没有答案