项目列表未显示在RecyclerView中

huangapple go评论77阅读模式
英文:

List of items aren't showing up in the RecyclerView

问题

以下是翻译好的内容:

我正在自学安卓应用开发(以及Java)。在弄清楚为什么我的列表项没有显示出来时遇到了麻烦。弹出窗口运行得很好,所以我没有包含它的代码。

我尝试通过添加Log.d()消息来查看GroceryItemAdapter是否正常工作,但它没有显示出来。我猜想是我制作的适配器有问题?

更新:
修复了一行代码,但现在我遇到了这个问题(稍后会更新,要研究一下是什么原因或者进行调试):

AutoCrab的答案帮助解决了空对象问题,我还发现在将整数传递给setText()之前需要将其转换为字符串。

java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法 'android.view.View android.widget.TextView.findViewById(int)'
    at com.example.myapplication.GroceryListAdapter$ViewHolder.<init>
package com.example.myapplication;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

//负责将模型中的数据显示到RecyclerView中的行中
public class GroceryListAdapter extends RecyclerView.Adapter<GroceryListAdapter.ViewHolder>{
    private List<GroceryList> lists = new ArrayList<>();

    public GroceryListAdapter(List<GroceryList> lists) {
        this.lists = lists;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View groceryListView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grocery_list_entry, parent, false);
        Log.d("MEJD", "我在这里吗?");
        ViewHolder viewHolder = new ViewHolder(groceryListView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        GroceryList groceryListItem = lists.get(position);

        TextView textView = holder.listTitle;
        textView.setText(groceryListItem.getListName());
        Log.d("MEJD", "我在这里");
        TextView numItemsView = holder.numItems;
        numItemsView.setText(String.valueOf(groceryListItem.getNumItems()));
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        public TextView listTitle;
        public TextView numItems;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            listTitle = itemView.findViewById(R.id.groceryListName);
            numItems = itemView.findViewById(R.id.numItemsList);
        }
    }
}

GroceryList类:

package com.example.myapplication;

import java.util.List;

public class GroceryList {
    private String listName;
    private int numItems;

    public GroceryList(String listName, int numItems) {
        this.listName = listName;
        this.numItems = numItems;
    }

    public String getListName() {
        return listName;
    }

    public void setListName(String listName) {
        this.listName = listName;
    }

    public int getNumItems() {
        return numItems;
    }

    public void setNumItems(int numItems) {
        this.numItems = numItems;
    }
}

GroceryListAdapter适配器:

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class GroceryListAdapter extends RecyclerView.Adapter<GroceryListAdapter.ViewHolder> {
    private List<GroceryList> lists = new ArrayList<>();

    public GroceryListAdapter(List<GroceryList> lists) {
        this.lists = lists;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View groceryListView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grocery_list_entry, parent, false);
        Log.d("MEJD", "我在这里吗?");
        ViewHolder viewHolder = new ViewHolder(groceryListView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        GroceryList groceryListItem = lists.get(position);

        TextView textView = holder.listTitle;
        textView.setText(groceryListItem.getListName());
        Log.d("MEJD", "我在这里");
        TextView numItemsView = holder.numItems;
        numItemsView.setText(String.valueOf(groceryListItem.getNumItems()));
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {
        public TextView listTitle;
        public TextView numItems;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            listTitle = itemView.findViewById(R.id.groceryListName);
            numItems = itemView.findViewById(R.id.numItemsList);
        }
    }
}

MainActivity的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/homeToolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#27D3C2"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintTop_toTopOf="parent"
        app:title="Add Grocery List"
        app:titleMarginStart="130dp" />

    <ImageButton
        android:id="@+id/addButton"
        android:layout_width="61dp"
        android:layout_height="56dp"
        android:layout_alignBottom="@+id/homeToolbar"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="322dp"
        android:layout_marginTop="0dp"
        android:layout_marginEnd="29dp"
        android:layout_marginBottom="0dp"
        android:backgroundTint="#00FFFFFF"
        android:clickable="true"
        android:contentDescription="@+string/add list button"
        app:layout_constraintEnd_toEndOf="@+id/homeToolbar"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/homeToolbar"
        app:layout_constraintTop_toTopOf="@+id/homeToolbar"
        app:srcCompat="@drawable/add_icon"
        android:focusable="true" />

    <android

<details>
<summary>英文:</summary>

I am teaching myself android app development(and Java). Having trouble figuring out why the items of my list are not showing up. The pop up works fine, so I didn&#39;t include the code for it. 

I tried to see if the `GroceryItemAdapter` is working by adding a `Log.d()` message and it doesn&#39;t show up. I&#39;m guessing it&#39;s the Adapter I made?

**Update:**
Fixed a line, but now I&#39;m getting this(will update this later, going to research what&#39;s the cause or debug it):

AutoCrab&#39;s answer helped solve the null object issue, I also figured out I needed to convert my integer into a string before passing it to `setText()`. 

    java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.view.View android.widget.TextView.findViewById(int)&#39; on a null object reference
            at com.example.myapplication.GroceryListAdapter$ViewHolder.&lt;init&gt;



    
    package com.example.myapplication;
    
    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    //responsible for displaying data from the model into a row in the recycler view
    public class GroceryListAdapter extends RecyclerView.Adapter&lt;GroceryListAdapter.ViewHolder&gt;{
        private List&lt;GroceryList&gt; lists = new ArrayList&lt;&gt;();
        public GroceryListAdapter(List&lt;GroceryList&gt; lists) {
            this.lists = lists;
        }
        
   
        //onCreateViewHolder is responsible for creating each view
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //create a new view and wrap it inside a new viewholder
            //use layout inflator to inflate a view
            View groceryListView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grocery_list_entry,parent,false);
            Log.d(&quot;MEJD&quot;, &quot;Iamhere?&quot;);
            //wrap it inside a ViewHolder and return it
            ViewHolder viewHolder = new ViewHolder(groceryListView);
            return viewHolder;
        }
    
        //onBindViewHolder is responsible for taking data at a particular position and
        //putting it into a viewholder
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            //get data model by position
            GroceryList groceryListItem = lists.get(position);
    
            //set the item views based on the data models
            TextView textView = holder.listTitle;
            textView.setText(groceryListItem.getListName());
            Log.d(&quot;MEJD&quot;, &quot;Iamhere&quot;);
            TextView numItemsView = holder.numItems;
            numItemsView.setText(groceryListItem.getNumItems());
    
       }
    
        //get number of items in the data
        @Override
        public int getItemCount() {
            lists.size();
        }
    
        class ViewHolder extends RecyclerView.ViewHolder{
            //member variables
            public TextView listTitle;
            public TextView numItems;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
    
                listTitle.findViewById(R.id.groceryListName);
                numItems.findViewById(R.id.numItemsList);
            }
        }
    }

GroceryList Class: 

        package com.example.myapplication;
        
        import java.util.List;
        
        public class GroceryList {
            //class to hold the info of each list item
           private String listName;
           private int numItems;
           //will need to refactor later.....
        
            public GroceryList(String listName, int numItems) {
                this.listName = listName;
                this.numItems = numItems;
        
            }
            public String getListName() {
                return listName;
            }
        
            public void setListName(String listName) {
                this.listName = listName;
            }
        
            public int getNumItems() {
                return numItems;
            }
        
            public void setNumItems(int numItems) {
                this.numItems = numItems;
            }
        
        
        }
    
GroceryList Adapter: 

    
    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    //responsible for displaying data from the model into a row in the recycler view
    public class GroceryListAdapter extends RecyclerView.Adapter&lt;GroceryListAdapter.ViewHolder&gt;{
        private List&lt;GroceryList&gt; lists = new ArrayList&lt;&gt;();
        public GroceryListAdapter(List&lt;GroceryList&gt; lists) {
            this.lists = lists;
        }
        //create a constructor
    
    
        //onCreateViewHolder is responsible for creating each view
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //create a new view and wrap it inside a new viewholder
            //use layout inflator to inflate a view
            View groceryListView = LayoutInflater.from(parent.getContext()).inflate(R.layout.grocery_list_entry,parent,false);
            Log.d(&quot;MEJD&quot;, &quot;Iamhere?&quot;);
            //wrap it inside a ViewHolder and return it
            ViewHolder viewHolder = new ViewHolder(groceryListView);
            return viewHolder;
        }
    
        //onBindViewHolder is responsible for taking data at a particular position and
        //putting it into a viewholder
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            //get data model by position
            GroceryList groceryListItem = lists.get(position);
    
            //set the item views based on the data models
            TextView textView = holder.listTitle;
            textView.setText(groceryListItem.getListName());
            Log.d(&quot;MEJD&quot;, &quot;Iamhere&quot;);
            TextView numItemsView = holder.numItems;
            numItemsView.setText(groceryListItem.getNumItems());
    
       }
    
        //get number of items in the data
        @Override
        public int getItemCount() {
            return 0;
        }
    
        class ViewHolder extends RecyclerView.ViewHolder{
            //member variables
            public TextView listTitle;
            public TextView numItems;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
    
                listTitle.findViewById(R.id.groceryListName);
                numItems.findViewById(R.id.numItemsList);
            }
        }
    }


XML file for MainActivity: 

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;.MainActivity&quot;&gt;
    
        &lt;androidx.appcompat.widget.Toolbar
            android:id=&quot;@+id/homeToolbar&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:background=&quot;#27D3C2&quot;
            android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot;
            app:layout_constraintTop_toTopOf=&quot;parent&quot;
            app:title=&quot;Add Grocery List&quot;
            app:titleMarginStart=&quot;130dp&quot; /&gt;
    
        &lt;ImageButton
            android:id=&quot;@+id/addButton&quot;
            android:layout_width=&quot;61dp&quot;
            android:layout_height=&quot;56dp&quot;
            android:layout_alignBottom=&quot;@+id/homeToolbar&quot;
            android:layout_alignParentStart=&quot;true&quot;
            android:layout_alignParentTop=&quot;true&quot;
            android:layout_alignParentEnd=&quot;true&quot;
            android:layout_marginStart=&quot;322dp&quot;
            android:layout_marginTop=&quot;0dp&quot;
            android:layout_marginEnd=&quot;29dp&quot;
            android:layout_marginBottom=&quot;0dp&quot;
            android:backgroundTint=&quot;#00FFFFFF&quot;
            android:clickable=&quot;true&quot;
            android:contentDescription=&quot;@+string/add list button&quot;
            app:layout_constraintEnd_toEndOf=&quot;@+id/homeToolbar&quot;
            app:layout_constraintHorizontal_bias=&quot;1.0&quot;
            app:layout_constraintStart_toStartOf=&quot;@+id/homeToolbar&quot;
            app:layout_constraintTop_toTopOf=&quot;@+id/homeToolbar&quot;
            app:srcCompat=&quot;@drawable/add_icon&quot;
            android:focusable=&quot;true&quot; /&gt;
    
        &lt;androidx.recyclerview.widget.RecyclerView
            android:id=&quot;@+id/rvView&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_below=&quot;@+id/homeToolbar&quot;
            android:layout_alignParentStart=&quot;true&quot;
            android:layout_alignParentEnd=&quot;true&quot;
            android:layout_alignParentBottom=&quot;true&quot;
            android:layout_marginStart=&quot;0dp&quot;
            android:layout_marginTop=&quot;0dp&quot;
            android:layout_marginEnd=&quot;0dp&quot;
            android:layout_marginBottom=&quot;1dp&quot; /&gt;
    &lt;/RelativeLayout&gt;


XML for the listItem I want to use:

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
        xmlns:tools=&quot;http://schemas.android.com/tools&quot;
        android:id=&quot;@+id/relativeLayout&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;&gt;

    &lt;androidx.constraintlayout.widget.Guideline
        android:id=&quot;@+id/guideline2&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;vertical&quot;
        app:layout_constraintGuide_begin=&quot;15dp&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    &lt;androidx.constraintlayout.widget.Guideline
        android:id=&quot;@+id/guideline4&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;vertical&quot;
        app:layout_constraintGuide_begin=&quot;35dp&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/numItemsList&quot;
        android:layout_width=&quot;28dp&quot;
        android:layout_height=&quot;23dp&quot;
        android:layout_marginEnd=&quot;34dp&quot;
        android:paddingTop=&quot;0dp&quot;
        android:paddingBottom=&quot;0dp&quot;
        android:text=&quot;@string/numberItems&quot;
        android:textSize=&quot;12sp&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;1.0&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;
        app:layout_constraintVertical_bias=&quot;0.0&quot; /&gt;

    &lt;androidx.constraintlayout.widget.Guideline
        android:id=&quot;@+id/guideline5&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;vertical&quot;
        app:layout_constraintGuide_end=&quot;15dp&quot; /&gt;

    &lt;androidx.constraintlayout.widget.Guideline
        android:id=&quot;@+id/guideline6&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;vertical&quot;
        app:layout_constraintGuide_end=&quot;35dp&quot; /&gt;

    &lt;TextView
        android:id=&quot;@+id/groceryListName&quot;
        android:layout_width=&quot;270dp&quot;
        android:layout_height=&quot;22dp&quot;
        android:layout_marginStart=&quot;35dp&quot;
        android:layout_marginEnd=&quot;44dp&quot;
        android:text=&quot;@string/groceryListName&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toStartOf=&quot;@+id/numItemsList&quot;
        app:layout_constraintHorizontal_bias=&quot;1.0&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;
    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;






</details>


# 答案1
**得分**: 0

也许是这样的:

```java
    // 获取数据中的项目数量
    @Override
    public int getItemCount() {
        return 0;
    }

编辑

    // 获取数据中的项目数量
    @Override
    public int getItemCount() {
        return lists.size();
    }
英文:

Maybe this:

//get number of items in the data
@Override
public int getItemCount() {
return 0;
}

edit

//get number of items in the data
@Override
public int getItemCount() {
return lists.size();
}

答案2

得分: 0

Add itemCount

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

Change ViewHolder class

class ViewHolder extends RecyclerView.ViewHolder{
//member variables
public TextView listTitle;
public TextView numItems;
public ViewHolder(@NonNull View itemView) {
super(itemView);
listTitle = itemView.findViewById(R.id.groceryListName);
numItems = itemView.findViewById(R.id.numItemsList);
}
}
英文:

Add itemCount

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

Change ViewHolder class

class ViewHolder extends RecyclerView.ViewHolder{
//member variables
public TextView listTitle;
public TextView numItems;
public ViewHolder(@NonNull View itemView) {
super(itemView);
listTitle = itemView.findViewById(R.id.groceryListName);
numItems = itemView.findViewById(R.id.numItemsList);
}
}

huangapple
  • 本文由 发表于 2020年9月16日 09:50:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63912023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定