neel
neel

Reputation: 9061

Error on setOnClickListener Android

I am creating setOnClickListener for a button. But it is creating problem.
When I am commenting the setOnClickListener part, code is working smoothly.
Here is my code :

public class Sales extends ActionBarActivity {

    Button btnBuy;
    Button btnSell;

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }


        btnBuy = (Button) findViewById(R.id.btn_buy);
        btnSell = (Button) findViewById(R.id.btn_sell);

        btnBuy.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Sales.this, Buy.class);
                startActivity(intent);      
                finish();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.sales, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_sales,
                    container, false);
            return rootView;
        }
    }

}  

My activity_sales.xml is :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tcshackathon.Sales"
    tools:ignore="MergeRootFrame" />  

And my fragment_sales.xml is :

<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tcshackathon.Sales$PlaceholderFragment" >



    <Button android:id="@+id/btn_buy"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Buy Something"
                android:layout_marginTop="30dip"
                android:layout_gravity="center_horizontal"
                />

    <Button android:id="@+id/btn_sell"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/btn_logout"
                android:text="Sell Something"
                android:layout_marginTop="30dip"
                android:layout_gravity="center_horizontal"
                />

</LinearLayout>  

StackTrace :

03-14 17:59:26.135: E/AndroidRuntime(15741): FATAL EXCEPTION: main
03-14 17:59:26.135: E/AndroidRuntime(15741): Process: com.example.tcshackathon, PID: 15741
03-14 17:59:26.135: E/AndroidRuntime(15741): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tcshackathon/com.example.tcshackathon.Buy}: java.lang.NullPointerException
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.os.Looper.loop(Looper.java:136)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.main(ActivityThread.java:5102)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at java.lang.reflect.Method.invokeNative(Native Method)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at java.lang.reflect.Method.invoke(Method.java:515)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at dalvik.system.NativeStart.main(Native Method)
03-14 17:59:26.135: E/AndroidRuntime(15741): Caused by: java.lang.NullPointerException
03-14 17:59:26.135: E/AndroidRuntime(15741):    at com.example.tcshackathon.Buy.onCreate(Buy.java:93)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.Activity.performCreate(Activity.java:5248)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
03-14 17:59:26.135: E/AndroidRuntime(15741):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
03-14 17:59:26.135: E/AndroidRuntime(15741):    ... 11 more

I am getting Java.lang.NullPointerException.

Can someone tell me why it happening?

Upvotes: 0

Views: 2106

Answers (4)

Raghunandan
Raghunandan

Reputation: 133560

In your comment you said that btn_buy belongs to fragment_sales.xml. So you need to initialize the button in onCreateView of Fragment

Button btnBuy,btnSell;
@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_sales,
                container, false);
        btnBuy = (Button)rootView.findViewById(R.id.btn_buy);
        btnSell = (Button)rootView.findViewById(R.id.btn_sell); 
        btnBuy.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), Buy.class);
            startActivity(intent);      
            finish();
        }
        }); 
        return rootView;
 }

The buttons do not belong to activity_sales.xml. So your initialization fails leading to NullPointerException.

Edit:

Since you ahve updated your post there is NPE @ line 93 Buy.java. Fix it. The code posted now is fine.

Upvotes: 7

Sanu
Sanu

Reputation: 455

Just refer this link

http://www.vogella.com/tutorials/AndroidActionBar/article.html

You can use onOptionsItemSelected() method for buttonclick action.

Another method you can follow is : directly use

 android:onClick="@string/buy_click"

in your XML.and in Class use

  public void buy_click(View v){

/...do your work here../ }

I dont know whether it is a good way of programming or not .

Upvotes: 0

user2644903
user2644903

Reputation:

not sure but please try

 btnBuy.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Sales.this, Buy.class);
            startActivity(intent);      
            finish();
        }
    });

Replace view.onclicklistener to onclicklistener

Upvotes: 1

JesusS
JesusS

Reputation: 1665

btnBuy = (Button) findViewById(R.id.btn_buy);

btn_buy does not belong to activity_sales.xml, so btnBuy value is null after findViewById()

Upvotes: 1

Related Questions