-1

Within my onCreate method:

add = (Button)findViewById(R.id.add);
add.setOnClickListener(new MyOnClickListener()); //null pointer here

public class MyOnClickListener implements OnClickListener 
{
    @Override
    public void onClick(View v) 
    {
         //send information to database
    }
}

XML File

<Button
    android:id="@+id/add"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/hello"
    android:layout_alignBottom="@+id/hello"
    android:layout_alignRight="@+id/id"
    android:layout_marginRight="72dp"
    android:text="Add" />

I know there are two ways to do it one using the XML attribute and the other way is the one I chose using setOnClickListener. I read another post and it said to clean the project however I am still getting a null pointer exception. What is wrong?

user3529942
  • 23
  • 1
  • 8
  • add is null. chekc if you have the button with id add in the layout you inflate – Raghunandan Aug 11 '14 at 05:22
  • if you are using a placeholder fragment approach, check if the layout with the button is "activity_main" or "fragment_main"(they are layout names by default), if its the latter, you need to find it inside onCreateView and not onCreate – Pararth Aug 11 '14 at 05:26
  • Please check try import OnClickListener for View not for DialogInterface or try to import android.view.View.OnClickListener; instead of import android.content.DialogInterface;. – Haresh Chhelana Aug 11 '14 at 05:27
  • post your logcat please – aether643 Aug 11 '14 at 05:30
  • 1
    add.setOnClickListener(new MyOnClickListener()); //null pointer here it means that add is NULL since add.setOnClickListener(null) is having no problem...add is null u have to check...in my concern the Layout u r inflating with setContentView() is not having add button – Amit Yadav Aug 11 '14 at 05:51
  • so shift your findViewById before the return rootView of onCreateView and when you id your button it should be rootView.findViewById ... added the code meaning solved? – Pararth Aug 11 '14 at 06:32
  • @user2450263 It was in my fragment_main. Thanks!! – user3529942 Aug 11 '14 at 06:49

1 Answers1

0

If you using Eclipse, try to clean project, maybe your R.java auto generated file is broken.

Raphoq
  • 99
  • 7