Recycler视图不显示数据

时间:2018-04-14 19:44:53

标签: android android-recyclerview

您好我有以下recycler adapter

package com.example.app.adapters;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import com.example.app.interfaces.iTicketsFilterListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.app.R;
import com.example.app.Utils;
import com.example.app.models.TicketModel;

import java.util.ArrayList;

public class ReservedTicketsArrayAdapter extends RecyclerView.Adapter<ReservedTicketsArrayAdapter.ViewHolder> implements Filterable {
    public ArrayList<TicketModel> mTickets;
    private TicketModel mTicket;
    public String selectedDate;
    Context mContext;
    Typeface Anton;

    private int altColour;

    private ValueFilter mValueFilter;
    private ArrayList<TicketModel> mStringFilterList;
    private iTicketsFilterListener mFilterListener;
    private ViewHolder mHolder;

    public ReservedTicketsArrayAdapter(String selectedDate, @NonNull Context context, @NonNull ArrayList<TicketModel> tickets) {
        mContext = context;
        mTickets = new ArrayList(tickets);
        mStringFilterList = new ArrayList(tickets);
        this.selectedDate = selectedDate;
        Anton = Typeface.createFromAsset(context.getAssets(), "fonts/Anton.ttf");
    }

    public ReservedTicketsArrayAdapter(String selectedDate, @NonNull Context context, @NonNull ArrayList<TicketModel> tickets, boolean twoPane) {
        mContext = context;
        mTickets = new ArrayList(tickets);
        mStringFilterList = new ArrayList(tickets);
        this.selectedDate = selectedDate;
        Anton = Typeface.createFromAsset(context.getAssets(), "fonts/Anton.ttf");
    }

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class ViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout rlContainer;
        TextView tvId;
        CheckBox chkTicket;
        TextView tvCode;
        TextView tvFullname;
        TextView tvPhone;
        TextView tvDestination;
        TextView tvClass;
        TextView tvFare;
        TextView tvSeatNo;
        TextView tvDepartureDate;
        TextView tvCreatedAt;

        // each data item is just a string in this case
        public ViewHolder(View view) {
            super(view);

            rlContainer = (RelativeLayout) view.findViewById(R.id.row_reserved_tickets_ll_container);
            tvId = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_id);
            chkTicket = (CheckBox) view.findViewById(R.id.row_reserved_tickets_chk_ticket);
            tvCode = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_code);
            tvFullname = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_customer);
            tvPhone = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_phone);
            tvDestination = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_to);
            tvClass = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_class);
            tvFare = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_fare);
            tvSeatNo = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_seat_no);
            tvDepartureDate = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_departure_date);
            tvCreatedAt = (TextView) view.findViewById(R.id.row_reserved_tickets_tv_created_at);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_reserved_tickets, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        mHolder = holder;
        mTicket = mTickets.get(position);

        if (altColour == 0) {
            holder.rlContainer.setBackgroundColor(Color.parseColor("#FFFFFF"));
            altColour = 1;
        } else {
            holder.rlContainer.setBackgroundColor(Color.parseColor("#EFEFEF"));
            altColour = 0;
        }

        holder.chkTicket.setTag(String.valueOf(position));

        holder.tvId.setText(String.valueOf(mTicket.getId()));

        if (mTicket.isSelected()) {
            holder.chkTicket.setChecked(true);
        } else {
            holder.chkTicket.setChecked(false);
        }

        holder.chkTicket.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = Integer.parseInt(buttonView.getTag().toString());  // Here we get the position that we have set for the checkbox using setTag.
                mTickets.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
            }

        });

        holder.chkTicket.setFocusable(false);
        holder.chkTicket.setClickable(false);
        holder.tvCode.setText(mTicket.getTicketCode());
        holder.tvFullname.setText(mTicket.getFullname());
        holder.tvPhone.setText(mTicket.getPhone());
        holder.tvDestination.setText(mTicket.getTo());
        holder.tvClass.setText(mTicket.getClass_());
        holder.tvFare.setText("$ "+mTicket.getFare());
        holder.tvSeatNo.setText(String.valueOf(mTicket.getSeatNo()));
        holder.tvSeatNo.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
        holder.tvSeatNo.setTextColor(ContextCompat.getColor(mContext, android.R.color.white));
        holder.tvDepartureDate.setText(Utils.formatDate(mTicket.getDepartureDate(), "yyyy-MM-dd hh:mm:ss", "hh:mm a"));
        holder.tvCreatedAt.setText(mTicket.getCreated_at());
    }

    @Override
    public int getItemCount() {
        if (mTickets == null) {
            return 0;
        }

        return mTickets.size();
    }

    @Override
    public Filter getFilter() {
        if(mValueFilter == null) {

            mValueFilter = new ValueFilter();
        }

        return mValueFilter;
    }

    public void remove(TicketModel ticket) {
        mTickets.remove(ticket);
    }


    private class ValueFilter extends Filter {

        //Invoked in a worker thread to filter the data according to the constraint.
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            ArrayList<TicketModel> filterList = new ArrayList<>();

            if(constraint != null && constraint.length() > 0){
                for(int i=0; i< mStringFilterList.size(); i++)
                {
                    if((mStringFilterList.get(i).getTicketCode()).contains(constraint.toString().toUpperCase())
                            || (mStringFilterList.get(i).getFullname()).contains(constraint.toString())
                            || (mStringFilterList.get(i).getPhone()).contains(constraint.toString()) ) {
                        TicketModel ticket = new TicketModel(
                                mStringFilterList.get(i).getId(),
                                mStringFilterList.get(i).getFullname(),
                                mStringFilterList.get(i).getPhone(),
                                mStringFilterList.get(i).getInvoiceCode(),
                                mStringFilterList.get(i).getTicketCode(),
                                mStringFilterList.get(i).getClass_(),
                                mStringFilterList.get(i).getDescription(),
                                mStringFilterList.get(i).getFrom(),
                                mStringFilterList.get(i).getTo(),
                                mStringFilterList.get(i).getFare(),
                                mStringFilterList.get(i).getSeatNo(),
                                mStringFilterList.get(i).getBusNo(),
                                mStringFilterList.get(i).getDepartureDate(),
                                mStringFilterList.get(i).getPrintedAt(),
                                mStringFilterList.get(i).getCreated_at()
                        );

                        filterList.add(ticket);
                    }
                }

                results.count = filterList.size();
                results.values = filterList;
            } else{
                results.count = mStringFilterList.size();
                results.values = mStringFilterList;
            }
            return results;
        }


        //Invoked in the UI thread to publish the filtering results in the user interface.
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            mTickets.clear();
            mTickets.addAll((ArrayList<TicketModel>) results.values);

            if (mFilterListener != null) {
                mFilterListener.filteringFinished(mTickets);
            }

            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                //notifyDataSetInvalidated();
            }
        }
    }

    public void setFilterListener(iTicketsFilterListener filterFinishedListener)
    {
        mFilterListener = filterFinishedListener;
    }

    private View.OnClickListener lvTicketsOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mTicket != null) {
                if (mTicket.getBusNo().equals("")) {
                    if (mHolder.chkTicket.isChecked()) {
                        mHolder.chkTicket.setChecked(false);
                        mTicket.setSelected(true);
                        remove(mTicket);
                    } else {
                        mHolder.chkTicket.setChecked(true);
                        mTicket.setSelected(false);
                        //mSelectedTickets.add(mTickets.get(position - 1));
                    }
                } else {
                    Toast.makeText(mContext, "Not allowed: Schedule has not been assigned to a bus!", Toast.LENGTH_LONG).show();
                }
            }
        }
    };

}

我的fragment类中的代码获取数据并将其加载到视图中:

private void loadTicketsIntoView() {
    if (mRoute != null) {
        sflTickets.setRefreshing(false);
        Utils.showProgress(getContext(), lvTickets, pbTickets, true);
        tvMessage.setVisibility(View.GONE);

    Response.Listener<JSONArray> onSuccessListener = new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            // Get schedule data
            mTickets = new ArrayList<>();
            mTicketsJson = response;

            for (int c = 0; c < response.length(); c++) {
                JSONObject schedule = null;
                try {
                    schedule = response.getJSONObject(c);

                    mTickets.add(new TicketModel(
                            schedule.getInt("id"),
                            schedule.optString("fullname"),
                            schedule.optString("phone"),
                            schedule.getString("invoice_code"),
                            schedule.getString("ticket_code"),
                            schedule.getString("class"),
                            schedule.getString("description"),
                            schedule.getString("from"),
                            schedule.getString("to"),
                            schedule.getDouble("fare"),
                            schedule.getInt("seat_no"),
                            schedule.optString("bus_no"),
                            schedule.getString("departure_date"),
                            schedule.optString("printed_at"),
                            schedule.getString("created_at")
                    ));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            // Initialising and loading data into adapter
            mTicketsAdapter = new ReservedTicketsArrayAdapter(mSelectedDate, getContext(), mTickets, mTwoPane);
            lvTickets.setAdapter(mTicketsAdapter);

            if (mTickets.size() < 1) {
                tvMessage.setVisibility(View.VISIBLE);
            } else {
                tvMessage.setVisibility(View.GONE);
            }

            // Hide progress icon
            Utils.showProgress(getContext(), lvTickets, pbTickets, false);
        }
    };

    Response.ErrorListener onErrorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Utils.showProgress(getContext(), lvTickets, pbTickets, false);
            Utils.showNetworkResponse(getContext(), error);
        }
    };

    mTicketsRequest.get(mRoute.getId(), mSelectedDate, onSuccessListener, onErrorListener);
}

}

这是我的片段布局:

<RelativeLayout
    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"
    android:background="@android:color/white"
    tools:context="com.example.app.activities.ReservedTicketsFragment">

    <EditText
        android:id="@+id/fragment_reserved_tickets_et_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="5dp"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:textSize="24sp"
        android:textStyle="bold"
        android:inputType="date"
        android:padding="10dp" />

    <ProgressBar
        android:id="@+id/fragment_reserved_tickets_pv_tickets"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_margin="5dp"
        android:layout_centerInParent="true"
        android:visibility="gone" />

    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_reserved_tickets_srl_tickets"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/fragment_reserved_tickets_et_date"
        android:layout_marginTop="25dp">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/fragment_reserved_tickets_lv_tickets"
            android:background="@color/colorPrimary"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.v4.widget.SwipeRefreshLayout>

    <TextView
        android:id="@+id/fragment_reserved_tickets_tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:elevation="5dp"
        android:padding="15dp"
        android:background="#CCFFFFFF"
        android:textColor="@color/colorPrimaryText"
        android:text="Choose a Route To Display Available Schedules"/>


</RelativeLayout>

现在我的问题是,当我运行应用程序时,此活动上没有任何显示,我已经确认正在返回数据,日志中没有显示任何错误,RecyclerView只是空白。

2 个答案:

答案 0 :(得分:1)

您尚未为回收站视图设置布局管理器。在设置适配器之前,在loadTicketsIntoView()中进行此更改:

LinearLayoutManager linear = new LinearLayoutManager(getActivity());
linear.setOrientation(LinearLayoutManager.VERTICAL);// If you want a vertical recycler view
lvTickets.setLayoutManager(linear);
mTicketsAdapter = new ReservedTicketsArrayAdapter(mSelectedDate, getContext(), mTickets, mTwoPane);
lvTickets.setAdapter(mTicketsAdapter);

希望这能解决您的问题!

答案 1 :(得分:0)

您已设置recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()))