碎片未显示Recycler View

时间:2018-01-01 07:34:38

标签: android android-recyclerview fragment

我正在创建一个fragment,用于从服务器加载notifications数据并显示在recyclerview中。数据已从服务器正确加载。但recycler view中未显示fragment

logcat中未显示任何错误。

片段(此片段默认加载导航抽屉(主片段)。):

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link HomeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {
    // 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 SessionManagement session;
    private Context mContext;

    private RequestQueue requestQueue;
    private Gson gson;

    private RecyclerView recyclerViewNotifications;
    private List<Notifications> listNotifications;
    private NotificationsRecyclerAdapter notificationsRecyclerAdapter;

    private String loggedUserId;

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

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {
        // 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 HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        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
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //----------------------------------------------------------------------------------------

        // Session class instance
        session = new SessionManagement(getActivity().getApplicationContext());
        // get user data from session
        HashMap<String, String> user = session.getUserDetails();
        String loggedUserId = user.get(SessionManagement.KEY_USERID);

        //----------------------------------------------------------------------------------------

        mContext = getActivity().getBaseContext();

        recyclerViewNotifications = (RecyclerView) view.findViewById(R.id.recyclerViewNotifications);

        listNotifications = new ArrayList<>();
        notificationsRecyclerAdapter = new NotificationsRecyclerAdapter(listNotifications);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        recyclerViewNotifications.setLayoutManager(mLayoutManager);
        recyclerViewNotifications.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
        recyclerViewNotifications.setItemAnimator(new DefaultItemAnimator());
        recyclerViewNotifications.setHasFixedSize(true);

        // Manually checking internet connection
        //if network not available
        if (!ConnectivityReceiver.isConnected()) {
            Log.d("x", "inside offline work.........View List");
            //Toast.makeText(mContext, "view list", Toast.LENGTH_SHORT).show();
            // launch new intent instead of loading fragment
        } else {
            //if network available
            Log.d("c", "inside online work.........Fetch notifications data");
            //Toast.makeText(getBaseContext(), "fetch enquiries", Toast.LENGTH_SHORT).show();

            requestQueue = null;
            // Get a RequestQueue
            requestQueue = Volley.newRequestQueue(mContext);
            fetchNotifications(loggedUserId);
        }

        //setting itemclick listener
        ItemClickSupport.addTo(recyclerViewNotifications).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                // do it
               /* Notifications noti=(Notifications) recyclerViewNotifications.getMyNotification(position);
                Intent viewIntent=new Intent(mContext, EnquiryViewActivity.class);
                if(enquiry!=null) {
                    Log.d("dash", "get enqid" + enquiry.getId());
                    viewIntent.putExtra("EnquiryId",enquiry.getId());
                    viewIntent.putExtra("UserId",enquiry.getUser_id());
                }
                startActivity(viewIntent);*/
            }
        });

        try {
            recyclerViewNotifications.setAdapter(notificationsRecyclerAdapter);
        }catch (NullPointerException e){
            Log.d("Error :","No notifications exists!");
            //Toast.makeText(mContext,"No business details exists!",Toast.LENGTH_LONG).show();
        }

        listNotifications.clear();

        try {
            fetchNotifications(loggedUserId);
            // listNotifications.addAll();
        }catch (NullPointerException e){
            Log.d("sdfs", "No Data available");
        }

        notificationsRecyclerAdapter.notifyDataSetChanged();


    }



        // 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;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    //-----------------------------------------------------------------------------------------

    private void fetchNotifications(final String LogId) {

        /*// Get a RequestQueue
        // RequestQueue requestQueue = MyVolleySingleton.getInstance(this.getApplicationContext()).getRequestQueue();
        requestQueue = Volley.newRequestQueue(this);*/

            //create gson instance which is used to parse json
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.excludeFieldsWithoutExposeAnnotation();
            //gsonBuilder.setDateFormat("M/d/yy hh:mm a");
            gson = gsonBuilder.create();

            StringRequest sr = new StringRequest(Request.Method.POST, EndPoints.GET_ALL_NOTIFICATIOS_URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    Log.d("d", "getting response.........\n" + response);
                    //Toast.makeText(getApplicationContext(), "Enquiry JSON data :" + response, Toast.LENGTH_LONG).show();

                    List<Notifications> notiList = Arrays.asList(gson.fromJson(response, Notifications[].class));
                   /* for (Notifications noti : notiList) {
                        listNotifications.add(noti);
                    }*/
                    listNotifications.addAll(notiList);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Log.e("MainActivity", error.toString());
                    Toast.makeText(mContext, "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Log.d("d", "inside getparams()...\n");
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("userid", LogId);
                    Log.d("d", "userid to pass:" + LogId + "\n");
                    return params;
                }
            };

            // Add the request to RequestQueue.
            // MyVolleySingleton.getInstance(this).addToRequestQueue(sr);
            requestQueue.add(sr);
            Log.d("d", "Added to queue");
        }

    }

适配器:

public class NotificationsRecyclerAdapter extends RecyclerView.Adapter<NotificationsRecyclerAdapter.NotificationsViewHolder> {

    private List<Notifications> listNotifications;

    public NotificationsRecyclerAdapter(List<Notifications> listNotifications) {
        this.listNotifications = listNotifications;
    }

    public Notifications getMyNotification(int position) {
        Log.d("EnquiryAdapter : ", "position: " + position);
        Log.d("EnquiryAdapter : ", "item : " + listNotifications.get(position).getId());
        return listNotifications.get(position);
    }

    @Override
    public NotificationsRecyclerAdapter.NotificationsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // inflating recycler item view
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_notifications_recycler, parent, false);

        return new NotificationsViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(NotificationsViewHolder holder, int position) {

        Notifications noti=new Notifications();

        Log.d("NotificationsAdapter : ", "type : " + noti.getAction());
        Log.d("NotificationsAdapter : ", "status : " + noti.getCreateddate());

        holder.textViewNotiAction.setText(listNotifications.get(position).getAction());
        holder.textViewNotiDate.setText(listNotifications.get(position).getCreateddate());
    }


    @Override
    public int getItemCount() {
        Log.v(NotificationsRecyclerAdapter.class.getSimpleName(), "" + listNotifications.size());
        return listNotifications.size();
    }


    /**
     * ViewHolder class
     */
    public class NotificationsViewHolder extends RecyclerView.ViewHolder {

        public AppCompatTextView textViewNotiAction;
        public AppCompatTextView textViewNotiDate;

        public NotificationsViewHolder(View view) {
            super(view);

            textViewNotiAction = (AppCompatTextView) view.findViewById(R.id.textViewNotiAction);
            textViewNotiDate = (AppCompatTextView) view.findViewById(R.id.textViewNotiDate);

        }
    }


}

片段布局:

<FrameLayout 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.anjana.decorightkitchen.fragment.HomeFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

        </ScrollView>
    </LinearLayout>
</FrameLayout>

项目布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/textViewNotiAction"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Notification"
                android:textStyle="bold"
                android:textColor="@color/colorAccentBlue" />

            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/textViewNotiDate"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="end"
                android:layout_weight="1"
                android:text="date"
                android:textColor="@color/colorHintText" />

        </LinearLayout>

    </LinearLayout>

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

2 个答案:

答案 0 :(得分:0)

从服务获取列表后,必须将更新的listNotifications发送到适配器,然后设置适配器。

@Override
public void onResponse(String response) {

Log.d("d", "getting response.........\n" + response);

List<Notifications> notiList = Arrays.asList(gson.fromJson(response, Notifications[].class));

listNotifications.addAll(notiList);
notificationsRecyclerAdapter = new NotificationsRecyclerAdapter(listNotifications);
recyclerViewNotifications.setAdapter(notificationsRecyclerAdapter);
}

<强>更新

  1. 不要将RecylerView放入ScrollView(因为RecylerView有滚动),直到你想在同一页面中有两个滚动视图(例如2个recylerview),然后使用** NestedScrollView **进行嵌套滚动。

  2. 从底部提供一些余量

      <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerViewNotifications"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:layout_marginBottom="20dp" />
    
  3. 希望这会对你有所帮助。

答案 1 :(得分:0)

您使用空列表设置适配器,因此它不会显示 您必须定义适配器并在获得响应后使用值设置它:

    @Override
        public void onResponse(String response) {

                        Log.d("d", "getting response.........\n" + response);
                        //Toast.makeText(getApplicationContext(), "Enquiry JSON data :" + response, Toast.LENGTH_LONG).show();

                        List<Notifications> notiList = Arrays.asList(gson.fromJson(response, Notifications[].class));
                       /* for (Notifications noti : notiList) {
                            listNotifications.add(noti);
                        }*/
                        listNotifications.addAll(notiList);
                        notificationsRecyclerAdapter = new 
                                    NotificationsRecyclerAdapter(listNotifications);
recyclerViewNotifications.setAdapter(notificationsRecyclerAdapter);    
                    }

@Override
                public void onResponse(String response) {

                    Log.d("d", "getting response.........\n" + response);
                    //Toast.makeText(getApplicationContext(), "Enquiry JSON data :" + response, Toast.LENGTH_LONG).show();

                    List<Notifications> notiList = Arrays.asList(gson.fromJson(response, Notifications[].class));
                   /* for (Notifications noti : notiList) {
                        listNotifications.add(noti);
                    }*/
                    listNotifications.addAll(notiList);
                   notificationsRecyclerAdapter.notifyItemRangeInserted(0,listNotifications.size());
                }

两种方式都相同但不确定它是否应该在代码中具有固定大小

recyclerViewNotifications.setHasFixedSize(true);

我想它应该在您的新列表设置后添加,希望它可以帮助您