java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'Rec-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'Rec

2020-01-19 09:34:18 389 1

我正在尝试实现一个recyclerview持有人以动态添加和删除卡。但是,为什么在尝试将cardview动态添加到recyclerview时却得到null指针异常?

MAINACTIVITY.JAVA此类负责动态创建卡片视图并将卡片添加到recyclerview。


package net.simplifiedlearning.recyclerviewexample;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    public Button buttonScan1;
    private Button dev_but1;
    public WebView wv1;
    private Dialog add_dev;
    private View v1;
    private EditText text2;
    private EditText dev_id1;
    private EditText dev_name1;
    private TextView dev_text1;
    private CardView cardview2;
    private LinearLayout.LayoutParams layoutparams1;
    private ConstraintLayout.LayoutParams layoutparams2;
    private LinearLayout lay1;
    private LinearLayout lay2;
    private LinearLayout lay3;
    private ToggleButton sw1;
    private ToggleButton sw2;
    private ToggleButton sw3;
    private ToggleButton sw4;
    private LinearLayout ahomeLayout;
    private Toolbar toolbar;
    private LinearLayout lay4;
    private LinearLayout lay6;
    private LinearLayout lay5;
    private LinearLayout.LayoutParams layoutparams3;
    private Button sw0;
    public TextView atv;
    String ids[] = new String[100];
    String names[] = new String[100];
    String name_key[] = {"A","B","C","D","F","G","H","I","J"};
    String id_key[] = {"A","B","C","D","F","G","H","I","J"};
    public SharedPreferences mSettings2;
    int mCount,j;
    String name;
    private Context mCtx;
    //a list to store all the products
    List<Product> productList;

    RelativeLayout l1;
    //the recyclerview
    RecyclerView recyclerView;

    Button end;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //View view = getLayoutInflater().inflate(R.layout.layout_products,null);

        end = findViewById(R.id.button2);

        //getting the recyclerview from xml
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);

        end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cards();
            }
        });

        //initializing the productlist
        productList = new ArrayList<>();

        //adding some items to our list
        //productList.add(new Product(1,"sdc","sfs"));
        //creating recyclerview adapter
        ProductAdapter adapter = new ProductAdapter(this, productList);

        //setting adapter to recyclerview
        recyclerView.setAdapter(adapter);
    }

    public void cards()
    {
      /*text2 = v1.findViewById(R.id.dev_name);
        dev_id1 = v1.findViewById(R.id.dev_id);*/

        cardview2 = new CardView(getApplicationContext());
        cardview2.setFocusable(false);
        cardview2.setClickable(false);

        layoutparams1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutparams1.setMargins(19, 83, 19, 0);

        lay1 = new LinearLayout(getApplicationContext());
        lay1.setOrientation(LinearLayout.VERTICAL);

        layoutparams2 = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, 115);
        lay2 = new LinearLayout(getApplicationContext());
        lay2.setLayoutParams(layoutparams2);
        lay2.setOrientation(LinearLayout.HORIZONTAL);

        layoutparams3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        lay6 = new LinearLayout(getApplicationContext());
        lay6.setWeightSum(12);
        lay6.setLayoutParams(layoutparams3);
        lay6.setPadding(10,40,0,0);
        lay6.setOrientation(LinearLayout.HORIZONTAL);

        cardview2.setLayoutParams(layoutparams1);
        cardview2.setCardBackgroundColor(Color.parseColor("#2fffffff"));
        cardview2.setMinimumHeight(330);
        cardview2.setId(mCount);
        cardview2.addView(lay1);

        dev_text1 = new TextView(getApplicationContext());
        dev_text1.setText("sdfasdf");
        dev_text1.setPadding(20, 15,0,0);
        dev_text1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 26);
        dev_text1.setTypeface(null, Typeface.BOLD);
        dev_text1.setTextColor(Color.GRAY);

        sw1 = new ToggleButton(getApplicationContext());
        sw1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        sw1.setTextColor(Color.GRAY);
        sw1.setLayoutParams(new LinearLayout.LayoutParams(210, 145));

        sw2 = new ToggleButton(getApplicationContext());
        sw2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        sw2.setTextColor(Color.GRAY);
        sw2.setLayoutParams(new LinearLayout.LayoutParams(210, 145));

        sw3 = new ToggleButton(getApplicationContext());
        sw3.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        sw3.setTextColor(Color.GRAY);
        sw3.setLayoutParams(new LinearLayout.LayoutParams(210, 145));

        sw4 = new ToggleButton(getApplicationContext());
        sw4.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        sw4.setTextColor(Color.GRAY);
        sw4.setLayoutParams(new LinearLayout.LayoutParams(210, 145));

        sw0 = new Button(getApplicationContext());
        sw0.setText("  X");
        sw0.setTextSize(20);
        sw0.setTypeface(null, Typeface.BOLD);
        sw0.setBackgroundResource(0);
        sw0.setTextColor(Color.GRAY);
        sw0.setPadding(0,0,0,5);
        sw0.setLayoutParams(new LinearLayout.LayoutParams(70, 70));

        lay1.addView(lay2);
        lay1.addView(lay6);
        lay2.addView(dev_text1);
        lay2.addView(sw0);
        lay6.addView(sw1);
        lay6.addView(sw2);
        lay6.addView(sw3);
        lay6.addView(sw4);
        recyclerView.addView(cardview2);
    }
}
产品.JAVA

package net.simplifiedlearning.recyclerviewexample;
public class Product {
    private int id;
    private String title;
    private String shortdesc;

    public Product(int id, String title, String shortdesc) {
        this.id = id;
        this.title = title;
        this.shortdesc = shortdesc;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getShortdesc() {
        return shortdesc;
    }

}
PRODUCTADAPTER.JAVA此类在recyclerview中具有适配器。

package net.simplifiedlearning.recyclerviewexample;

import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.Toolbar;


import java.util.List;

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    //this context we will use to inflate the layout
    private Context mCtx;
    RelativeLayout l1;
    //we are storing all the products in a list
    private List<Product> productList;

    //getting the context and product list with constructor
    public ProductAdapter(Context mCtx, List<Product> productList) {
        this.mCtx = mCtx;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflating and returning our view holder
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.layout_products, null);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ProductViewHolder holder, int position) {
        //getting the product of the specified position
        Product product = productList.get(position);

        //binding the data with the viewholder views
        holder.textViewTitle.setText(product.getTitle());
        holder.textViewShortDesc.setText(product.getShortdesc());

        holder.end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                productList.remove(holder.getAdapterPosition());
                notifyDataSetChanged();
            }
        });
    }

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



    class ProductViewHolder extends RecyclerView.ViewHolder {

        TextView textViewTitle, textViewShortDesc;
        Button end;

        public ProductViewHolder(View itemView) {
            super(itemView);
            l1 = itemView.findViewById(R.id.card);
            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewShortDesc = itemView.findViewById(R.id.textViewShortDesc);
            end = itemView.findViewById(R.id.button);
        }
    }
}
布局_产品.Java

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/card1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">

        <RelativeLayout
            android:id="@+id/card"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="120dp"
                android:layout_height="90dp"
                android:padding="4dp" />

            <TextView
                android:id="@+id/textViewTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@id/imageView"
                android:text="Apple MacBook Air Core i5 5th Gen - (8 GB/128 GB SSD/Mac OS Sierra)"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Small"
                android:textColor="#000000" />

            <TextView
                android:id="@+id/textViewShortDesc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/textViewTitle"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@id/imageView"
                android:text="13.3 Inch, 256 GB"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Small" />

            <TextView
                android:id="@+id/textViewRating"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/textViewShortDesc"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@id/imageView"
                android:background="@color/colorPrimary"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:text="4.7"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Small.Inverse"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/textViewPrice"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/textViewRating"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="5dp"
                android:layout_toRightOf="@id/imageView"
                android:text="INR 56990"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:textStyle="bold" />

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:text="Button" />

        </RelativeLayout>

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

</LinearLayout>
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="net.simplifiedlearning.recyclerviewexample.MainActivity">

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

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="500dp"
        android:text="ADD" />

</RelativeLayout>
取消 提交回答
全部回答(1)
  • Puppet
    2020-01-19 11:40:53

    像这样更改onCreateViewHolder。

    
      @Override
        public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //inflating and returning our view holder
            LayoutInflater inflater = LayoutInflater.from(mCtx);
            View view = inflater.inflate(R.layout.layout_products,parent, false);
            return new ProductViewHolder(view);
        }
    
    0 0
相关问答

1

回答

Java中Exception使用时,有什么要求吗?

2022-04-03 22:39:54 524浏览量 回答数 1

1

回答

Java中的Exception 类的层次是什么?

2022-04-03 22:30:15 549浏览量 回答数 1

1

回答

Java中通过什么来调用成员方法?

2022-04-02 15:28:30 724浏览量 回答数 1

1

回答

java中Exception 类的层次是什么?

2021-11-16 23:21:17 210浏览量 回答数 1

1

回答

java.lang.nullpointerexception怎么解决

2021-10-21 09:21:22 348浏览量 回答数 1

1

回答

#支付宝 java.lang.NullPointerException: alipayPu,怎么办

2020-05-05 16:38:02 704浏览量 回答数 1

1

回答

编译器报错 Java.alng.NullPointerException ,怎么办?

2020-04-25 11:13:30 380浏览量 回答数 1

1

回答

Java类抛出java.lang.NullPointerException [重复]

2020-04-11 16:03:08 1474浏览量 回答数 1

1

回答

java.lang.exception 是什么意思

2018-05-10 20:09:00 7811浏览量 回答数 1

1

回答

java.lang.NullPointerException?

2016-02-01 16:55:58 3258浏览量 回答数 1
+关注
文章
问答
问答排行榜
最热
最新
相关电子书
更多
Javascript中的对象
立即下载
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载