0

I want to create a Button inside CardView to show a second Activity, I have added an onClick listener in the adapter but when i run the app it keeps crashing over and over.

ps: The logcat shows the error

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

my 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);


}



}

item layout 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>

item adapter :

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);

        }
    }
}
Guss
  • 30,470
  • 17
  • 104
  • 128
C89-HD
  • 47
  • 9

5 Answers5

1

Your button buttonCalling is not initialized by the time MainActivity's onCreate is called. Since there is a buttonCalling in every item in your list, you must attach the click listener to it after it has been initialized, which happens when you call the constructor of ItemHolder. Here's one way to do this.

In 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);
}

And in your 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);
    }
}

This should work.

sindhu_sp
  • 749
  • 5
  • 12
  • there as no crash, but when I click on the button the second activity does not start. the button shows nothing – C89-HD Sep 16 '16 at 16:03
  • Check the edited code: There was a duplicate click listener in `ItemAdapter#onBindViewHolder`, I removed it. – sindhu_sp Sep 16 '16 at 16:45
  • but every button of each cardview open the same activity . how can i make buton of cardview number two Open Activity number2 ... and button of cardview number three Open Activiity number 3 . and thanks – C89-HD Sep 20 '16 at 18:17
0

buttoncalling= (Button)findViewById(R.id.buttonfordialog) is what missing here, you need to do that first thing in the onCreate() method before trying to reach out to the view.

Gilad Eshkoli
  • 1,253
  • 11
  • 27
0

add

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

before your click listenver inside onCreate. When you are running your code the value of buttoncalling is null, because you have not initialized it.

Rahul Sharma
  • 12,515
  • 6
  • 21
  • 30
0

Add a new constructor in 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);
        }
    });

}

this code in MainActivity

itemAdapter = new ItemAdapter(itemList,getApplicationContext());
siddhesh
  • 563
  • 1
  • 9
  • 15
  • I want each button of cardview Open different Activity. give me a solution, please I need it . – C89-HD Sep 20 '16 at 18:29
0

In MainActivity in onCreate () you call buttoncalling.setOnClickListener (),but I can't see in code where you initialize It. You should initialize it calling before

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

Emmanuele
  • 36
  • 6