setOnClickListener Android出错

时间:2014-03-14 12:00:10

标签: java android

我正在为按钮创建setOnClickListener。但它正在制造问题 当我在评论setOnClickListener部分时,代码运行顺畅 这是我的代码:

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

}  

我的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" />  

我的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

我收到Java.lang.NullPointerException。

有人可以告诉我它为什么会发生吗?

4 个答案:

答案 0 :(得分:7)

在评论中,您说btn_buy属于fragment_sales.xml。因此,您需要在onCreateView

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

按钮不属于activity_sales.xml。因此,初始化失败导致NullPointerException

编辑:

由于您已更新帖子,因此有NPE @ line 93 Buy.java。修理它。现在发布的代码很好。

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

不确定但请尝试

 btnBuy.setOnClickListener(new OnClickListener() {

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

将view.onclicklistener替换为onclicklistener

答案 3 :(得分:0)

请参阅此链接

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

您可以使用onOptionsItemSelected()方法进行buttonclick操作。

您可以遵循的另一种方法是:直接使用

 android:onClick="@string/buy_click"

在您的XML中和在类中使用

  public void buy_click(View v){

/ ...在这里做你的工作.. /    }

我不知道这是否是一种好的编程方式。