错误onclick按钮iside(cardview,recyclerview)

时间:2016-09-16 13:23:42

标签: java android android-studio nullpointerexception android-recyclerview

我想在Button内创建一个CardView以显示第二个Activity,我在适配器中添加了一个onClick侦听器,但是当我运行应用程序时,它会保留一遍又一遍地崩溃。

ps:logcat显示错误

MainActivity.onCreate(MainActivity.java:43) 
specifically the error start in 
`buttoncalling.setOnClickListener(new View.OnClickListener()`

我的logcat:

E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start 
  activity ComponentInfo{com.example.apollo.bbpp/
              com.example.apollo.bbpp.MainActivity}: java.lang.NullPointerException
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2099)
  at android.app.ActivityThread.access(ActivityThread.java:138)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:4929)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
  at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
  at com.example.apollo.bbpp.MainActivity.onCreate(MainActivity.java:43)
  at android.app.Activity.performCreate(Activity.java:5254)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2099) 
  at android.app.ActivityThread.access(ActivityThread.java:138) 
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) 
  at android.os.Handler.dispatchMessage(Handler.java:99) 
  at android.os.Looper.loop(Looper.java:137) 
  at android.app.ActivityThread.main(ActivityThread.java:4929) 
  at java.lang.reflect.Method.invokeNative(Native Method) 
  at java.lang.reflect.Method.invoke(Method.java:511) 
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798) 
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565) 
  at dalvik.system.NativeStart.main(Native Method) 

MainActivity java:

public class MainActivity extends AppCompatActivity {

private RecyclerView recyclerView;

private ItemAdapter itemAdapter;
private Button buttoncalling ;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    buttoncalling.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this,Main2Activity.class);
            startActivity(intent);
        }
    });




        final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
    collapsingToolbarLayout.setTitle("Service/DPNG");


    ArrayList<Celebrity> itemList = new ArrayList<>();

    fillDummyData(itemList);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    itemAdapter = new ItemAdapter(itemList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(itemAdapter);




}

private void fillDummyData(ArrayList<Celebrity> celebList) {
    Celebrity celeb1 = new Celebrity();
    celeb1.setName("Johny.D");
    celeb1.setFamousMovie("Pirates  ");
    celeb1.setProfilePhotoLocation("@drawable/contact1");
    celebList.add(celeb1);

    Celebrity celeb2 = new Celebrity();
    celeb2.setName("Arnold");
    celeb2.setFamousMovie("The Terminator");
    celeb2.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTI3MDc4NzUyMV5BMl5BanBnXkFtZTcwMTQyMTc5MQ@@._V1._SY209_CR13,0,140,209_.jpg");
    celebList.add(celeb2);

    Celebrity celeb3 = new Celebrity();
    celeb3.setName("Emma.W");
    celeb3.setFamousMovie("Harry Potter ");
    celeb3.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTQ3ODE2NTMxMV5BMl5BanBnXkFtZTgwOTIzOTQzMjE@._V1._SY209_CR14,0,140,209_.jpg");
    celebList.add(celeb3);

    Celebrity celeb4 = new Celebrity();
    celeb4.setName("Daniel");
    celeb4.setFamousMovie("Harry Potter ");
    celeb4.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTg4NTExODc3Nl5BMl5BanBnXkFtZTgwODUyMDEzMDE@._V1._SY209_CR8,0,140,209_.jpg");
    celebList.add(celeb4);

    Celebrity celeb5 = new Celebrity();
    celeb5.setName("Leonardo");
    celeb5.setFamousMovie("Inception");
    celeb5.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMjI0MTg3MzI0M15BMl5BanBnXkFtZTcwMzQyODU2Mw@@._V1._SY209_CR7,0,140,209_.jpg");
    celebList.add(celeb5);

    Celebrity celeb6 = new Celebrity();
    celeb6.setName("TomCr");
    celeb6.setFamousMovie("Top Gun");
    celeb6.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTk1MjM3NTU5M15BMl5BanBnXkFtZTcwMTMyMjAyMg@@._V1._SY209_CR9,0,140,209_.jpg");
    celebList.add(celeb6);

    Celebrity celeb7 = new Celebrity();
    celeb7.setName("Charles.C");
    celeb7.setFamousMovie("Modern Times");
    celeb7.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BNDcwMDc0ODAzOF5BMl5BanBnXkFtZTgwNTY2OTI1MDE@._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb7);

    Celebrity celeb8 = new Celebrity();
    celeb8.setName("Morgan.F");
    celeb8.setFamousMovie("The Shawshank ");
    celeb8.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTc0MDMyMzI2OF5BMl5BanBnXkFtZTcwMzM2OTk1MQ@@._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb8);

    Celebrity celeb9 = new Celebrity();
    celeb9.setName("Tom.Ha");
    celeb9.setFamousMovie("The Da Vinci Code");
    celeb9.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTQ2MjMwNDA3Nl5BMl5BanBnXkFtZTcwMTA2NDY3NQ@@._V1._SY209_CR2,0,140,209_.jpg");
    celebList.add(celeb9);

    Celebrity celeb10 = new Celebrity();
    celeb10.setName("Hugh ");
    celeb10.setFamousMovie("The Prestige");
    celeb10.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BNDExMzIzNjk3Nl5BMl5BanBnXkFtZTcwOTE4NDU5OA@@._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb10);

    Celebrity celeb11 = new Celebrity();
    celeb11.setName("Matt ");
    celeb11.setFamousMovie("The Bourne Identity");
    celeb11.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTM0NzYzNDgxMl5BMl5BanBnXkFtZTcwMDg2MTMyMw@@._V1._SY209_CR8,0,140,209_.jpg");
    celebList.add(celeb11);

    Celebrity celeb12 = new Celebrity();
    celeb12.setName("Sylvester ");
    celeb12.setFamousMovie("Rocky");
    celeb12.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTQwMTk3NDU2OV5BMl5BanBnXkFtZTcwNTA3MTI0Mw@@._V1._SY209_CR5,0,140,209_.jpg");
    celebList.add(celeb12);

    Celebrity celeb13 = new Celebrity();
    celeb13.setName("Will ");
    celeb13.setFamousMovie("Men in Black");
    celeb13.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BNTczMzk1MjU1MV5BMl5BanBnXkFtZTcwNDk2MzAyMg@@._V1._SY209_CR2,0,140,209_.jpg");
    celebList.add(celeb13);

    Celebrity celeb14 = new Celebrity();
    celeb14.setName("Steven ");
    celeb14.setFamousMovie("Saving Private ");
    celeb14.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTY1NjAzNzE1MV5BMl5BanBnXkFtZTYwNTk0ODc0._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb14);

    Celebrity celeb15 = new Celebrity();
    celeb15.setName("Al ");
    celeb15.setFamousMovie("The Godfather");
    celeb15.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTQzMzg1ODAyNl5BMl5BanBnXkFtZTYwMjAxODQ1._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb15);

    Celebrity celeb16 = new Celebrity();
    celeb16.setName("Robert");
    celeb16.setFamousMovie("The Avengers");
    celeb16.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BNzg1MTUyNDYxOF5BMl5BanBnXkFtZTgwNTQ4MTE2MjE@._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb16);

    Celebrity celeb17 = new Celebrity();
    celeb17.setName("Nat");
    celeb17.setFamousMovie("V for Vendetta");
    celeb17.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTQ3ODE3Mjg1NV5BMl5BanBnXkFtZTcwNzA4ODcxNA@@._V1._SY209_CR8,0,140,209_.jpg");
    celebList.add(celeb17);

    Celebrity celeb18 = new Celebrity();
    celeb18.setName("Dwayne");
    celeb18.setFamousMovie("WWE Raw");
    celeb18.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTkyNDQ3NzAxM15BMl5BanBnXkFtZTgwODIwMTQ0NTE@._V1._SX140_CR0,0,140,209_.jpg");
    celebList.add(celeb18);

    Celebrity celeb19 = new Celebrity();
    celeb19.setName("Jackie ");
    celeb19.setFamousMovie("Jackie Chan ");
    celeb19.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTk4MDM0MDUzM15BMl5BanBnXkFtZTcwOTI4MzU1Mw@@._V1._SY209_CR5,0,140,209_.jpg");
    celebList.add(celeb19);

    Celebrity celeb20 = new Celebrity();
    celeb20.setName("Scarlet");
    celeb20.setFamousMovie("Lost in ");
    celeb20.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTM3OTUwMDYwNl5BMl5BanBnXkFtZTcwNTUyNzc3Nw@@._V1._SY209_CR16,0,140,209_.jpg");
    celebList.add(celeb20);


}



}

项目布局xml:

<RelativeLayout
    android:longClickable="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="7dp">


    <ImageView

        android:id="@+id/profileImage"
        android:layout_width="70dp"
        android:layout_height="50dp"
        app:civ_border_color="#7f89e9"
        android:layout_marginLeft="5dp"
        android:background="@drawable/contact1"
        android:layout_alignTop="@+id/txtCelebName"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_marginTop="8dp"
        android:id="@+id/txtCelebName"
        android:textSize="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/profileImage"
        android:text="Large Text"
        android:layout_marginLeft="18dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_marginLeft="18dp"
        android:textSize="13dp"
        android:id="@+id/txtCelebMovie"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtCelebName"
        android:layout_toRightOf="@+id/profileImage"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:id="@+id/textView"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="27dp"
        android:layout_below="@+id/profileImage"
        android:text="hello" />

    <TextView
        android:layout_marginLeft="10dp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="hola "
        android:id="@+id/textView2"
        android:layout_below="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_marginLeft="10dp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="bonsoir"
        android:id="@+id/textView3"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_marginLeft="5dp"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="hahahahaha"
        android:id="@+id/textView4"
        android:layout_below="@+id/profileImage" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="hohohohohoho"
        android:id="@+id/textView5"
        android:layout_alignLeft="@+id/textView4"
        android:layout_alignStart="@+id/textView4"
        android:layout_below="@+id/textView2"
        android:layout_marginBottom="5dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button1"
        android:layout_alignBottom="@+id/textView4"
        android:layout_toRightOf="@+id/txtCelebName"
        android:layout_toEndOf="@+id/txtCelebName" />


</RelativeLayout>

项目适配器:

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {

private List<Celebrity> celebrityList;

public ItemAdapter(List<Celebrity> celebrityList) {
    this.celebrityList = celebrityList;
}

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

    return new ItemHolder(itemView);
}

@Override
public void onBindViewHolder(ItemHolder holder, int position) {
    Celebrity item = celebrityList.get(position);
    holder.txtCelebName.setText(item.getName());
    holder.txtCelebMovie.setText(item.getFamousMovie());
    holder.buttoncalling.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

        }
    });
}

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

public class ItemHolder extends RecyclerView.ViewHolder {


    private  Button buttoncalling;
    public TextView txtCelebName, txtCelebMovie;
    public ImageView profileImage;

    public ItemHolder(View view) {
        super(view);
        txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
        txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
        profileImage = (ImageView) view.findViewById(R.id.profileImage);
        buttoncalling  = (Button) view.findViewById(R.id.buttonfordialog);

        }
    }
}

5 个答案:

答案 0 :(得分:1)

调用MainActivity的onCreate时,您的按钮buttonCalling未初始化。由于列表中的每个项目都有buttonCalling,因此在初始化之后必须将点击侦听器附加到它,这在您调用ItemHolder的构造函数时会发生。这是一种方法。

在MainActivity中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this,Main2Activity.class);
            startActivity(intent);
        }
    };




    final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
    collapsingToolbarLayout.setTitle("Service/DPNG");


    ArrayList<Celebrity> itemList = new ArrayList<>();

    fillDummyData(itemList);

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    itemAdapter = new ItemAdapter(itemList, btnListener);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(itemAdapter);
}

在你的ItemAdapter中:

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {

private List<Celebrity> celebrityList;
private final View.OnClickListener btnListener;

public ItemAdapter(List<Celebrity> celebrityList, View.OnClickListener btnListener) {
    this.celebrityList = celebrityList;
    this.btnListener = btnListener;
}

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

    return new ItemHolder(itemView, btnListener);
}

@Override
public void onBindViewHolder(ItemHolder holder, int position) {
    Celebrity item = celebrityList.get(position);
    holder.txtCelebName.setText(item.getName());
    holder.txtCelebMovie.setText(item.getFamousMovie());
}

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

public class ItemHolder extends RecyclerView.ViewHolder {


    private  Button buttoncalling;
    public TextView txtCelebName, txtCelebMovie;
    public ImageView profileImage;

    public ItemHolder(View view, View.OnClickListener btnListener) {
        super(view);
        txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
        txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
        profileImage = (ImageView) view.findViewById(R.id.profileImage);
        buttoncalling  = (Button) view.findViewById(R.id.buttonfordialog);
        buttoncalling.setOnClickListener(btnListener);
    }
}

这应该有用。

答案 1 :(得分:0)

buttoncalling =(Button)findViewById(R.id.buttonfordialog)就是这里缺少的,在尝试联系视图之前,你需要在onCreate()方法中做第一件事。

答案 2 :(得分:0)

添加

buttoncalling = (Button)findViewById(R.id.button1);

onCreate 中点击听众之前

。当您运行代码时, buttoncalling 的值为null,因为您尚未初始化它。

答案 3 :(得分:0)

在ItemAdapter

中添加新构造函数
class ItemAdapter{
List itemList;
MainActivity mainActivity;
public void ItemAdapter(List itemList,Context mContext){
      this.itemList = itemList;
      this.mainActivity = (MainActivity)mContext;
}

holder.buttoncalling.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
           Intent intent = new Intent(mainActivity,Main2Activity.class);
            startActivity(intent);
        }
    });

}

MainActivity中的此代码

itemAdapter = new ItemAdapter(itemList,getApplicationContext());

答案 4 :(得分:0)

在onCreate()的MainActivity中,你调用了buttoncalling.setOnClickListener(),但我无法在代码中看到你初始化它。你应该在

之前调用它来初始化它

buttoncalling = (Button)findViewById (R.id.your_button_id)