CardView没有出现在RecyclerView上

时间:2017-08-01 11:42:40

标签: android mysql android-fragments

我对Android开发相对较新,我创建了一个从数据库(MySQL)中获取数据的应用程序,并且(应该)显示在android中片段中加载的卡片上。我的所有java类都没有显示任何错误,但是当我启动应用程序时,卡不会在RecyclerView中膨胀。

以下是我试图无效的一些解决方案:
CardView not shown in RecyclerView
Android MySQL Tutorial to Perform Basic CRUD Operation How to implement RecyclerView with CardView rows in a Fragment with TabLayout

任何帮助将不胜感激。 片段包含我正在使用的类:

public class bloodBanks extends Fragment {
    private RecyclerView recylerView;
    private MyAdapter adapter;
    private List<MyData>data_List;
    private OnFragmentInteractionListener mListener;

       public bloodBanks() {
        // 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 bloodBanks.
     */
    // TODO: Rename and change types and number of parameters
    public static bloodBanks newInstance(String param1, String param2) {
        bloodBanks fragment = new bloodBanks();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_blood_banks, container, false);
        //perform(v);
        recylerView=(RecyclerView) v.findViewById(R.id.recyle);
        recylerView.setHasFixedSize(true);
        data_List = new ArrayList<>();

        adapter=new MyAdapter(getActivity(),data_List);
        recylerView.setAdapter(adapter);

        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recylerView.setLayoutManager(llm);

        load_data_from_server(0);
        return v;
    }

    private void load_data_from_server(final int id) {
        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... params) {

                OkHttpClient client= new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://192.168.137.1:81/card.php?id="+id)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0;i<array.length();i++){
                        JSONObject object=array.getJSONObject(i);
                        MyData data=new MyData(object.getInt("id"),object.getString("hospName"),object.getString("contact"));
                        data_List.add(data);
                    }

                } catch(IOException e){
                    e.printStackTrace();
                }catch (JSONException e){
                    System.out.println("No More Hospitals");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);
    }


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

}

我的适配器类:

public  class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{

    private Context context;
    private List<MyData> my_data;

    public MyAdapter(Context context, List<MyData> my_data) {
        this.context = context;
        this.my_data = my_data;
    }

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

        return new ViewHolder(itemView);
    }

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

        holder.hospName.setText(my_data.get(position).getHospName());
        holder.contact.setText(my_data.get(position).getContact());
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public TextView hospName;
        public TextView contact;

        public ViewHolder(View itemView){
            super(itemView);
            hospName=(TextView) itemView.findViewById(R.id.hosp);
            contact=(TextView) itemView.findViewById(R.id.contact);
        }
    }

}

数据定义:

public class MyData {

    private int id;
    private String hospName,contact;

    public MyData(int id, String hospName, String contact) {
        this.id = id;
        this.hospName = hospName;
        this.contact = contact;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getHospName() {
        return hospName;
    }

    public void setHospName(String hospName) {
        this.hospName = hospName;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }
}

Cards.xml

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

    <android.support.v7.widget.CardView
        android:id="@+id/cdBanks"
        android:layout_width="329dp"
        android:layout_height="137dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.022"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent">

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

            <ImageView
                android:id="@+id/hospPhoto"
                android:layout_width="148dp"
                android:layout_height="wrap_content"
                android:src="@drawable/contacts_icon" />

            <TextView
                android:id="@+id/hosp"
                android:layout_width="195dp"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/hospPhoto"
                android:textSize="26sp"
                tools:layout_editor_absoluteX="256dp"
                tools:layout_editor_absoluteY="16dp" />

            <TextView
                android:id="@+id/contact"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/hosp"
                android:layout_toRightOf="@+id/hospPhoto" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/contact"
                android:layout_toRightOf="@+id/hospPhoto"
                android:text="Blood Units: " />
        </RelativeLayout>


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

</LinearLayout>

fragment_blood_banks.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:context="layout.bloodBanks">


        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            card_view:cardUSeCompatPadding="true"
            card_view:cardElevation="5dp"
            card_view:cardCornerRadius="5dp"
            android:scrollbars="vertical"
            android:layout_marginRight="6dp"
            android:layout_marginLeft="6dp"
            android:layout_marginTop="6dp"

            />



</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:0)

在适配器的xml中将整个布局放在CardView ....

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

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="10dp"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="10dp"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:background="@color/color"
    android:id="@+id/cv1"
    card_view:cardElevation="3.5dp"
    card_view:cardBackgroundColor="#fff"
    card_view:cardCornerRadius="3dp"
    android:foreground="?android:attr/selectableItemBackground"
    xmlns:android="http://schemas.android.com/apk/res/android">


    <put your whole layout here....>

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

   </LinearLayout>