简体   繁体   English

Android上的setOnClickListener错误

[英]Error on setOnClickListener Android

I am creating setOnClickListener for a button. 我正在为按钮创建setOnClickListener But it is creating problem. 但这正在制造问题。
When I am commenting the setOnClickListener part, code is working smoothly. 当我评论setOnClickListener部分时,代码工作正常。
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 : 我的activity_sales.xml是:

<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 : 我的fragment_sales.xml是:

<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. 我正在获取Java.lang.NullPointerException。

Can someone tell me why it happening? 有人可以告诉我为什么会这样吗?

In your comment you said that btn_buy belongs to fragment_sales.xml . 在您的评论中,您说btn_buy属于fragment_sales.xml So you need to initialize the button in onCreateView of Fragment 所以你需要在Fragment onCreateView中初始化按钮

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 . 这些按钮不属于activity_sales.xml So your initialization fails leading to NullPointerException . 因此,您的初始化失败导致NullPointerException

Edit: 编辑:

Since you ahve updated your post there is NPE @ line 93 Buy.java . 自从您更新了帖子以来,就有NPE @ 93行Buy.java Fix it. 修理它。 The code posted now is fine. 现在发布的代码很好。

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

btn_buy不属于activity_sales.xml ,因此在findViewById()之后btnBuy值为null

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 将view.onclicklistener替换为onclicklistener

Just refer this link 只需参考此链接

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

You can use onOptionsItemSelected() method for buttonclick action. 您可以将onOptionsItemSelected()方法用于buttonclick操作。

Another method you can follow is : directly use 您可以遵循的另一种方法是:直接使用

 android:onClick="@string/buy_click"

in your XML.and in Class use 在XML和Class中使用

  public void buy_click(View v){

/ ...do your work here.. / } / ...在这里工作。/ }

I dont know whether it is a good way of programming or not . 我不知道这是否是编程的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM