【问题标题】:I am not able to show integer value with textview in adapter我无法在适配器中使用 textview 显示整数值
【发布时间】:2020-04-05 09:45:21
【问题描述】:

我试图在 textview 中显示整数值,但它不断使我的 android 应用程序崩溃,这是内容

json

    [
   {
      "id":8,
      "name":"Recruitment",
      "banner":"category_CAT1.jpg",
      "description":"Job Recruitment Post.",
      "newss":4
}
]

在适配器中

    public TextView news;

public ViewHolder(View v) {
            super(v);
            news = v.findViewById(R.id.newss);

        }
    }
@Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Category c = categorylist.get(position);
         holder.news.setText(c.getnewss());

            }
        });
    }

在模块中

Integer newss;

    public Integer getnewss() {
        return newss;
    }

    public void setnewss(Integer newss) {
        this.newss = newss;
    }

错误是

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
04-05 14:39:34.575 16109 16109 E   AndroidRuntime                               at com.androbaron.dailynews.adapter.CategoryListAdapter.onBindViewHolder(CategoryListAdapter.java:81)
04-05 14:39:34.575 16109 16109 E   AndroidRuntime                               at com.androbaron.dailynews.adapter.CategoryListAdapter.onBindViewHolder(Unknown Source:8)

这是布局中的文本视图

<RelativeLayout>
<TextView
                        android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
                        android:textColor="@color/secondary_text"
                        android:id="@+id/newss"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="30.0dip"/>

提前谢谢。

从这里编辑

Adapter.java

public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.ViewHolder> implements Filterable {

    private final int mBackground;
    private List<Category> original_items = new ArrayList<>();
    private List<Category> categorylist = new ArrayList<Category>();
    private ItemFilter mFilter = new ItemFilter();
    private final TypedValue mTypedValue = new TypedValue();
    private Context ctx;
    private ImageLoader imgloader = ImageLoader.getInstance();

    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView name;
        public TextView news;
        public ImageView image;
        public CardView lyt_parent;

        public ViewHolder(View v) {
            super(v);
            name = (TextView) v.findViewById(R.id.name);
            image = (ImageView) v.findViewById(R.id.image);
            news = v.findViewById(R.id.newss);
            lyt_parent = (CardView) v.findViewById(R.id.lyt_parent);
        }
    }

    public Filter getFilter() {
        return mFilter;
    }

    public CategoryListAdapter(Context ctx, List<Category> items) {
        this.ctx = ctx;
        original_items = items;
        categorylist = items;
        ctx.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
        mBackground = mTypedValue.resourceId;
    }

    @Override
    public CategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
        v.setBackgroundResource(mBackground);
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Category c = categorylist.get(position);
        holder.name.setText(c.name);
        holder.news.setText("" + c.newss);
        //holder.news.setText(String.valueof(c.getnewss()));
       // holder.news.setText(c.getnewss());
        imgloader.displayImage(Constant.getURLimgCategory(c.banner), holder.image);
        holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ctx, ActivityCategoryDetails.class);
                i.putExtra(ActivityCategoryDetails.EXTRA_OBJCT, c);
                ctx.startActivity(i);
            }
        });
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return categorylist.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String query = constraint.toString().toLowerCase();
            FilterResults results = new FilterResults();
            final List<Category> list = original_items;
            final List<Category> result_list = new ArrayList<>(list.size());
            for (int i = 0; i < list.size(); i++) {
                String str_title = list.get(i).name;
                String str_newss = list.get(i).newss;
                if (str_title.toLowerCase().contains(query) || str_newss.toLowerCase().contains(query)) {
                    result_list.add(list.get(i));
                }
            }
            results.values = result_list;
            results.count = result_list.size();
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            categorylist = (List<Category>) results.values;
            notifyDataSetChanged();
        }

    }
}

布局在这里

<?xml version="1.0" encoding="utf-8"?>
<com.balysv.materialripple.MaterialRippleLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/RippleStyleBlack"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/lyt_parent"
        android:layout_width="match_parent"
        android:layout_height="90.0dip"
        android:layout_margin="@dimen/spacing_medium"
        app:cardBackgroundColor="@android:color/white"
        app:cardCornerRadius="4.0dip"
        app:cardElevation="2.0dip">

        <LinearLayout
            android:layout_width="80.0dip"
            android:layout_height="fill_parent">

            <ImageView
                android:id="@+id/image"
                android:background="@color/Black"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:scaleType="centerCrop"/>

        </LinearLayout>

        <LinearLayout
            android:gravity="center_vertical"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:paddingLeft="100.0dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true">

                <TextView
                    android:textAppearance="@style/TextAppearance.AppCompat.Title"
                    android:textStyle="normal"
                    android:textColor="@color/primary_text"
                    android:id="@+id/name"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:text="Sample Title"
                    android:layout_weight="1.0"/>

                <RelativeLayout
                    android:gravity="center_vertical"
                    android:orientation="horizontal"
                    android:paddingTop="25.0dip"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <ImageView
                        android:layout_width="@dimen/spacing_mlarge"
                        android:layout_height="@dimen/spacing_mlarge"
                        android:src="@drawable/ab_news_small"
                        android:tint="@android:color/black"/>
                    <TextView
                        android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
                        android:textColor="@color/secondary_text"
                        android:id="@+id/newss"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="30.0dip"/>

                </RelativeLayout>

            </LinearLayout>

        </LinearLayout>

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

</com.balysv.materialripple.MaterialRippleLayout>

适配器及其布局现在都在这里

忽略这个

我试图在 textview 中显示整数值,但它不断使我的 android 应用程序崩溃,这是内容

【问题讨论】:

标签: android android-layout android-recyclerview textview


【解决方案1】:

试试下面的代码:

模型类 Category.java

public class Category {
    int id,newss;
    String name,banner,description;
    public Category(int id, int newss, String name, String banner, String description) {
        this.id = id;
        this.newss = newss;
        this.name = name;
        this.banner = banner;
        this.description = description;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getNewss() {
        return newss;
    }
    public void setNewss(int newss) {
        this.newss = newss;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBanner() {
        return banner;
    }
    public void setBanner(String banner) {
        this.banner = banner;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

适配器类 CategoryListAdapter.java

public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.ViewHolder> implements Filterable {

    private final int mBackground;
    private List<Category> original_items = new ArrayList<>();
    private List<Category> categorylist = new ArrayList<Category>();
    private ItemFilter mFilter = new ItemFilter();
    private final TypedValue mTypedValue = new TypedValue();
    private Context ctx;
    private ImageLoader imgloader=new ImageLoader();
    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView name;
        public TextView news;
        public ImageView image;
        public CardView lyt_parent;

        public ViewHolder(View v) {
            super(v);
            name = (TextView) v.findViewById(R.id.name);
            image = (ImageView) v.findViewById(R.id.image);
            news = v.findViewById(R.id.newss);
            lyt_parent = (CardView) v.findViewById(R.id.lyt_parent);
        }
    }

    public Filter getFilter() {
        return mFilter;
    }

    public CategoryListAdapter(Context ctx, List<Category> items) {
        this.ctx = ctx;
        original_items = items;
        categorylist = items;
        ctx.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
        mBackground = mTypedValue.resourceId;
    }

    @Override
    public CategoryListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false);
        v.setBackgroundResource(mBackground);
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final Category c = categorylist.get(position);
        holder.name.setText(c.getName());
        holder.news.setText(String.valueOf(c.getNewss()));
        imgloader.displayImage(Constant.getURLimgCategory(c.banner), holder.image);
        holder.lyt_parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ctx, ActivityCategoryDetails.class);
                i.putExtra(ActivityCategoryDetails.EXTRA_OBJCT, c);
                ctx.startActivity(i);
            }
        });
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return categorylist.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String query = constraint.toString().toLowerCase();
            FilterResults results = new FilterResults();
            final List<Category> list = original_items;
            final List<Category> result_list = new ArrayList<>(list.size());
            for (int i = 0; i < list.size(); i++) {
                String str_title = list.get(i).getName();
                String str_newss = String.valueOf(list.get(i).getNewss());
                if (str_title.toLowerCase().contains(query) || str_newss.toLowerCase().contains(query)) {
                    result_list.add(list.get(i));
                }
            }
            results.values = result_list;
            results.count = result_list.size();
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            categorylist = (List<Category>) results.values;
            notifyDataSetChanged();
        }

    }
}

活动中的代码

  CategoryListAdapter categoryListAdapter=new CategoryListAdapter(this,categoryArrayList);
  recyclerViewMain.setLayoutManager(new LinearLayoutManager(this));
  recyclerViewMain.setAdapter(categoryListAdapter);

崩溃的主要原因是你的模型类

希望对你有用

【讨论】:

    【解决方案2】:

    有两个问题。

    1.您的 holder.news 为空。

    确保在 onCreateViewHolder 方法中返回正确的视图。

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

    一旦你解决了这个问题,下一个问题就是你将 int 值放入 settext()。

    首先你必须将 int 转换为 String,然后将其放入 Settext()。

     holder.news.setText(String.valueof(c.getnewss()));
    

    【讨论】:

    • 我可以把整数改成字符串吗?
    • 是的,你可以。在答案的最后一行是更改它的代码。 String.valueof(c.getnewss())
    • 查看 v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category, parent, false); v.setBackgroundResource(mBackground); onCreateViewHolder 是正确的
    【解决方案3】:

    看看这个:

    holder.news.setText("" + c.getnewss());
    

    或:

    holder.news.setText(String.valueof(c.getnewss()));
    

    希望对你有用:)

    【讨论】:

    • 都试过了,但都没有成功。
    【解决方案4】:

    将模块中的Integer 新闻更改为int 新闻。然后尝试使用holder.news.setText(String.valueof(c.getnewss()));在显示中设置它 如果您不想更改模块类中的 Integer 数据类型,请使用: Integer.toString(c.getnewss());

    【讨论】:

    • 你改变数据类型了吗?
    • 是的,我更改了数据
    • 尝试使用 Integer.toString(c.getnewss()) 保持数据类型为 int 代码: holder.news.setText(Integer.toString(c.getnewss());
    • 能否请您也编写模块代码以进行澄清。
    • 国际新闻; public int getnewss() { 返回新闻; } public void setnewss(int news) { this.newss = newss; }
    猜你喜欢
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多