在零对象引用上的Recycler视图setLayoutManager

时间:2017-01-25 06:23:27

标签: android android-recyclerview

在我的Android应用中,我想将数据显示到RecyclerView布局中。这里我指定了一些代码请参考。因为我不知道背后的原因是什么。请帮我。提前谢谢。

fragment.xml之

<android.support.v7.widget.CardView   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:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:background="@color/colorWhite"
    app:cardElevation="8dp"
    card_view:cardCornerRadius="2dp"
    card_view:cardUseCompatPadding="true">

    <RelativeLayout
        android:id="@+id/footerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:padding="10dp">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/txtListTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="HMS Scrap"
            android:textColor="@color/colorWhite" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/txtListName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txtListTitle"
            android:layout_marginTop="10dp"
            android:text="HMS Scrap"
            android:textColor="@color/colorWhite" />

    </RelativeLayout>

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

在这里,我指定public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ListViewHolder> { private Context mContext; private List<ListModal> listTitle; public ListAdapter(Context mContext, List<ListModal> listTitle) { this.mContext = mContext; this.listTitle = listTitle; } @Override public ListAdapter.ListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.raw_list, parent, false); return new ListAdapter.ListViewHolder(itemView); } @Override public void onBindViewHolder(ListAdapter.ListViewHolder holder, int position) { ListModal objListModal = listTitle.get(position); holder.txtListTitle.setText(objListModal.getList_name()); holder.txtListTitle.setText(objListModal.getList_title()); @Override public int getItemCount() { return 0; } public class ListViewHolder extends RecyclerView.ViewHolder { TextView txtListTitle, txtListName; CardView cvList; public ListViewHolder(View itemView) { super(itemView); txtListTitle = (TextView) itemView.findViewById(R.id.txtListTitle); txtListName = (TextView) itemView.findViewById(R.id.txtListName); cvList = (CardView) itemView.findViewById(R.id.cardView); } } } 的原始文件。

raw.xml

RecyclerView rvDisplay;
private ListAdapter adapter;
private List<ListModal> lstmodal;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_create_list, container, false);

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

    lstmodal = new ArrayList<>();

    final LinearLayoutManager layoutManager = new  LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    rvDisplay.setLayoutManager(layoutManager);
    makeJsonArrayRequest();
    return view;
}

private void makeJsonArrayRequest() {
    String cancel_req_tag = "list";

    JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT,
            new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
             Log.d("OnResponse", response.toString());

             try {
                 // Parsing json array response
                 // loop through each json object
                 for (int i = 0; i < response.length(); i++) {

                     JSONObject jsonObject = response.getJSONObject(i);
                     ListModal objListModal = new ListModal();
                     if (!jsonObject.isNull("list_name")) {
                         objListModal.list_name = jsonObject.getString("list_name"); //here we can fetch webservice field
                     }
                     if (!jsonObject.isNull("list_title")) {
                         objListModal.list_title = jsonObject.getString("list_title"); //here we can fetch webservice field
                     }

                     lstmodal.add(i, objListModal);
                 }

                 adapter = new ListAdapter(getActivity(), lstmodal);
                 rvDisplay.setItemAnimator(new DefaultItemAnimator());
                 rvDisplay.setAdapter(adapter);

             } catch (JSONException e) {
                 e.printStackTrace();
                 Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
             }

         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
             VolleyLog.d("VolleyError", "Error: " + error.getMessage());
             Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
         }
     });
}

现在,我发布适配器文件代码

adapter.java

<form id='form' name='form' method='post' action=''>
        <div><label id="resultString"></label></div>
        <fieldset>
            <legend>Login</legend>
            Username: <input type="text" id="username" name="username"><br><br>
            Password: <input type="password" id="password" name="password"><br><br>
            <input type="button" value="Login">
        </fieldset>
    </form>

现在Fragment.java

$(document).ready(function() {

  $('#form').validate({
    rules: {
      username: {
        required: true
      },
      password: {
        required: true
      }

    },
    highlight: function(element) {
      $(element).closest('.form-control').removeClass('success').addClass('error');
    },
    success: function(element) {

      $(element).closest('.form-control').removeClass('error').addClass('success');
    }
  });
});

这里我尝试了这段代码我收到此错误请参阅工作日志

enter image description here

5 个答案:

答案 0 :(得分:1)

当您使用另一种布局而不是您正在使用的布局时,通常会导致空对象。我有同样的问题。尝试夸大活动主目录,而不是fragmentcreatelist ...

答案 1 :(得分:0)

在您的第一个代码块中,您说布局文件名为fragment.xml但是在片段代码中您调用了inflater.inflate(R.layout.fragment_create_list, ...)

确保使用与片段相同的布局文件进行充气。

答案 2 :(得分:0)

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

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

    lstmodal = new ArrayList<>();

    final LinearLayoutManager layoutManager = new  LinearLayoutManager(getActivity());
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    rvDisplay.setLayoutManager(layoutManager);
    makeJsonArrayRequest();
}

答案 3 :(得分:0)

我认为您错过了:

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);

希望这会有所帮助!

答案 4 :(得分:0)

通过传递上下文创建LinearLayoutManager。不是活动。

LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());