Android OnclickListener()不在选项卡上工作

Android OnclickListener()不在选项卡上工作,android,android-fragments,bluetooth,Android,Android Fragments,Bluetooth,我正在进行基于蓝牙的项目。我正在使用标签来包含不同的页面。当包含按钮onclick listener时,应用程序崩溃。我引用了sdk中的蓝牙聊天。在Setupchat()中,我试图识别按钮并分配onclicklisteners。但应用程序在onclicklistner上崩溃了。我检查了logcat,它显示空指针异常。这是logcat输出 08-11 16:25:08.003: E/AndroidRuntime(16481): FATAL EXCEPTION: main 08-11 16:25:0

我正在进行基于蓝牙的项目。我正在使用标签来包含不同的页面。当包含按钮onclick listener时,应用程序崩溃。我引用了sdk中的蓝牙聊天。在Setupchat()中,我试图识别按钮并分配onclicklisteners。但应用程序在onclicklistner上崩溃了。我检查了logcat,它显示空指针异常。这是logcat输出

08-11 16:25:08.003: E/AndroidRuntime(16481): FATAL EXCEPTION: main
08-11 16:25:08.003: E/AndroidRuntime(16481): Process: com.dispenser, PID: 16481
08-11 16:25:08.003: E/AndroidRuntime(16481): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dispenser/com.dispenser.MainActivity}: java.lang.NullPointerException
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.os.Looper.loop(Looper.java:136)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.ActivityThread.main(ActivityThread.java:5086)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at java.lang.reflect.Method.invokeNative(Native Method)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at java.lang.reflect.Method.invoke(Method.java:515)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at dalvik.system.NativeStart.main(Native Method)
08-11 16:25:08.003: E/AndroidRuntime(16481): Caused by: java.lang.NullPointerException
08-11 16:25:08.003: E/AndroidRuntime(16481):    at com.dispenser.MainActivity.setupChat(MainActivity.java:223)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at com.dispenser.MainActivity.onStart(MainActivity.java:195)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1194)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.Activity.performStart(Activity.java:5258)
08-11 16:25:08.003: E/AndroidRuntime(16481):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2171)
08-11 16:25:08.003: E/AndroidRuntime(16481):    ... 11 more
我知道这nullpointerexception何时出现如果我使用按钮时未标识按钮,则nullpointerexception将引发。但我真的不知道这是什么。请帮帮我

这是195号线和223号线

    package com.dispenser;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dispenser.adapter.TabsPagerAdapter;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnClickListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mTabAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Diagnostic", "Set" ,"Settings"};

    // Debugging
        private static final String TAG = "Main";
        private static final boolean D = true;
        // Message types sent from the BluetoothChatService Handler
        public static final int MESSAGE_STATE_CHANGE = 1;
        public static final int MESSAGE_READ = 2;
        public static final int MESSAGE_WRITE = 3;
        public static final int MESSAGE_DEVICE_NAME = 4;
        public static final int MESSAGE_TOAST = 5;
        // Key names received from the BluetoothChatService Handler
        public static final String DEVICE_NAME = "device_name";
        public static final String TOAST = "toast";
        // Intent request codes
        private static final int REQUEST_CONNECT_DEVICE = 1;
        private static final int REQUEST_ENABLE_BT = 2;
        // Layout Views
        //private TextView mTitle;
        private EditText mPS1,mPS2,mPS3,mFT,mFW,valve1,valve2,sPS1,sPS2,sPS3;


        private Button mSendButtonOn,mEnable,mDisable,mSet;
        private Button mSendButtonOff;

        // Name of the connected device
        private String mConnectedDeviceName;

        // String buffer for outgoing messages
        private StringBuffer mOutStringBuffer;
        // Local Bluetooth adapter
        private BluetoothAdapter mBluetoothAdapter;
        // Member object for the chat services
        private ChatService mChatService;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        if (D) {
            Log.e(TAG, "+++ ON CREATE +++");
        }

        // Set up the window layout
        //requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_main);

    //  getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
    //                            R.layout.custom_title);

        // Set up the custom title
    //  mTitle = (TextView) findViewById(R.id.title_left_text);
    //  mTitle.setText(R.string.app_name);
    //  mTitle = (TextView) findViewById(R.id.title_right_text);


        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available",
                           Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        // Initialization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mTabAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mTabAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (D) {
            Log.e(TAG, "++ ON START ++");
        }

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the chat session
        } else {
            if (mChatService == null) {
                setupChat();
            }
        }
    }

    private void setupChat() {
        mSet=(Button) findViewById(R.id.setBtn);

        Log.d(TAG, "setupChat()");

        // Diagnostic
        mPS1=(EditText) findViewById(R.id.ps1);
        mPS2=(EditText) findViewById(R.id.ps2);
        mPS3=(EditText) findViewById(R.id.ps3);

        mFT=(EditText) findViewById(R.id.ft);

        mFW=(EditText) findViewById(R.id.fw);

        valve1=(EditText) findViewById(R.id.valve1);
        valve2=(EditText) findViewById(R.id.valve2);

        //Set
        sPS1=(EditText) findViewById(R.id.pressure1);
        sPS2=(EditText) findViewById(R.id.pressure2);
        sPS3=(EditText) findViewById(R.id.pressure3);



    //  mSet.setOnClickListener(MainActivity.this);

        // Preference 


    //  mSendButtonOff.setOnClickListener(MainActivity.this);

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new ChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if (D) {
            Log.e(TAG, "+ ON RESUME +");
        }

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity
        // returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't
            // started already
            if (mChatService.getState() == ChatService.STATE_NONE) {
                // Start the Bluetooth chat services
                mChatService.start();
            }
        }
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if (D) {
            Log.e(TAG, "- ON PAUSE -");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) {
            mChatService.stop();
        }
        if (D) {
            Log.e(TAG, "--- ON DESTROY ---");
        }
    }

    private void ensureDiscoverable() {
        if (D) {
            Log.d(TAG, "ensure discoverable");
        }
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(
                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     *
     * @param message
     *            A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != ChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
            .show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {

            // XXX !!!
            message = message + "\r\n"; // terminate for pc bluetooth spp server

            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            // mOutEditText.setText(mOutStringBuffer);
        }
    }

    // The Handler that gets information back from the BluetoothChatService
        private final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    if (D) {
                        Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                    }
                    switch (msg.arg1) {
                    case ChatService.STATE_CONNECTED:
                        Toast.makeText(getBaseContext(), R.string.title_connected_to+" " +mConnectedDeviceName, Toast.LENGTH_LONG).show();
                    //  mTitle.append();
                    //  mConversationArrayAdapter.clear();
                        break;
                    case ChatService.STATE_CONNECTING:
                        Toast.makeText(getBaseContext(), R.string.title_connecting, Toast.LENGTH_LONG).show();
                        break;
                    case ChatService.STATE_LISTEN:
                    case ChatService.STATE_NONE:
                        Toast.makeText(getBaseContext(), R.string.title_not_connected, Toast.LENGTH_LONG).show();
                        //mTitle.setText();
                        break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                //  mConversationArrayAdapter.add("Me:  " + writeMessage);
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    final String readMessage = new String(readBuf, 0, 50);
//                  mConversationArrayAdapter.add(mConnectedDeviceName + ":  "
//                          + readMessage);
                    Runnable done = new Runnable()
                    {
                        public void run()
                        {
                            String[] b=readMessage.split(",");
                            for(int i=0;i<b.length;i++){
                            //  Toast.makeText(getBaseContext(), b[i], Toast.LENGTH_SHORT).show();
                                if(b[i].contains("PS1")){
                                    String[] c=b[i].split("=");
                                    if(c.length==2){
                                        mPS1.setText(c[1]);
                                    }
                                }
                                else if(b[i].contains("PS2")){
                                    String[] c=b[i].split("=");
                                    if(c.length==2){
                                        mPS2.setText(c[1]);
                                    }
                                }
                                else if(b[i].contains("PS3")){
                                    String[] c=b[i].split("=");
                                    if(c.length==2){
                                        mPS3.setText(c[1]);
                                    }
                                }
                                else if(b[i].contains("LPM")){
                                    String[] c=b[i].split("=");
                                    if(c.length==2){
                                        mFW.setText(c[1]);
                                    }
                                }
                                else{

                                }

                            //  mPS1.append(b[i]);

                            }
                        }
                    };
                    done.run();
                    break;

                case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    Toast.makeText(getApplicationContext(),
                                   "Connected to " + mConnectedDeviceName,
                                   Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(),
                                   msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                    .show();
                    break;
                }
            }   
        };

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (D) {
                Log.d(TAG, "onActivityResult " + resultCode);
            }
            switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    String address = data.getExtras().getString(
                                         DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // Get the BLuetoothDevice object
                    BluetoothDevice device = mBluetoothAdapter
                                             .getRemoteDevice(address);
                    // Attempt to connect to the device
                    mChatService.connect(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupChat();
                } else {
                    // User did not enable Bluetooth or an error occured
                    Log.d(TAG, "BT not enabled");
                    Toast.makeText(this, R.string.bt_not_enabled_leaving,
                                   Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.setBtn:
                if(sPS1.getText().length()!=0){
                    float pressure1=Float.parseFloat(sPS1.getText().toString());
                    if(pressure1>0.0F && pressure1<20.0F)
                    sendMessage("PS1="+pressure1);
                }
                else{
                    sPS1.setError("Enter PS1");
                }
                if(sPS2.getText().length()!=0){
                    float pressure2=Float.parseFloat(sPS2.getText().toString());
                    if(pressure2>0.0F && pressure2<20.0F)
                    sendMessage("PS2="+pressure2);
                }
                else{
                    sPS2.setError("Enter PS2");
                }
                if(sPS3.getText().length()!=0){
                    float pressure3=Float.parseFloat(sPS3.getText().toString());
                    if(pressure3>0.0F && pressure3<20.0F)
                    sendMessage("PS3="+pressure3);
                }
                else{
                    sPS3.setError("Enter PS3");
                }

                break;

            default:
                break;
            }
        }
}
package.com分配器;
导入android.annotation.SuppressLint;
导入android.app.ActionBar;
导入android.app.ActionBar.Tab;
导入android.app.Activity;
导入android.app.FragmentTransaction;
导入android.bluetooth.BluetoothAdapter;
导入android.bluetooth.bluetooth设备;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.Message;
导入android.support.v4.app.FragmentActivity;
导入android.support.v4.view.ViewPager;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuInflater;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.Toast;
导入com.dispenser.adapter.TabsPagerAdapter;
公共类MainActivity扩展FragmentActivity实现ActionBar.TablListener、OnClickListener{
私人视页机视页机;
私人TabsPagerAdapter mTabAdapter;
私人ActionBar ActionBar;
//标签标题
私有字符串[]选项卡={“诊断”、“设置”、“设置”};
//调试
私有静态最终字符串TAG=“Main”;
私有静态最终布尔值D=true;
//从BluetoothChatService处理程序发送的消息类型
公共静态最终int消息_STATE_CHANGE=1;
公共静态最终int消息_READ=2;
公共静态最终int消息_WRITE=3;
公共静态最终int消息\u设备\u名称=4;
公共静态最终int消息_TOAST=5;
//从BluetoothChatService处理程序接收的密钥名称
公共静态最终字符串DEVICE\u NAME=“DEVICE\u NAME”;
公共静态最终字符串TOAST=“TOAST”;
//意图请求代码
专用静态最终int请求\u连接\u设备=1;
私有静态最终整数请求_ENABLE_BT=2;
//布局视图
//私有文本视图mTitle;
私有编辑文本mPS1、mPS2、mPS3、mFT、mFW、valve1、valve2、sPS1、sPS2、sPS3;
私有按钮mSendButtonOn、可菜单、可计量、mSet;
私人按钮mSendButtonOff;
//连接的设备的名称
私有字符串mConnectedDeviceName;
//传出消息的字符串缓冲区
私有字符串缓冲区mOutStringBuffer;
//本地蓝牙适配器
私人蓝牙适配器mBluetoothAdapter;
//聊天室服务的成员对象
私人聊天室服务;
@SuppressLint(“新API”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
如果(D){
Log.e(标记“+++”ON CREATE+++”;
}
//设置窗口布局
//requestWindowFeature(Window.FEATURE\u自定义\u标题);
setContentView(R.layout.activity_main);
//getWindow().setFeatureInt(Window.FEATURE\u自定义\u标题,
//R.布局、自定义标题);
//设置自定义标题
//mTitle=(TextView)findViewById(R.id.title\u left\u text);
//mTitle.setText(R.string.app_name);
//mTitle=(TextView)findViewById(R.id.title\u right\u text);
//获取本地蓝牙适配器
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//如果适配器为空,则不支持蓝牙
if(mBluetoothAdapter==null){
Toast.makeText(此“蓝牙不可用”,
Toast.LENGTH_LONG).show();
完成();
返回;
}
//初始化
viewPager=(viewPager)findViewById(R.id.pager);
actionBar=getActionBar();
mTabAdapter=新选项卡SPAGERADAPTER(getSupportFragmentManager());
viewPager.setAdapter(mTabAdapter);
actionBar.setHomeButtonEnabled(假);
actionBar.setNavigationMode(actionBar.NAVIGATION\u MODE\u选项卡);
//添加选项卡
用于(字符串选项卡\名称:选项卡){
actionBar.addTab(actionBar.newTab().setText(选项卡名称)
.setTabListener(本));
}
/**
*滑动viewpager时,选择相应的选项卡
* */
viewPager.setOnPageChangeListener(新的viewPager.OnPageChangeListener(){
@凌驾
已选择页面上的公共无效(内部位置){
//关于更改页面
//选择“受尊重”选项卡
actionBar.setSelectedNavigationItem(位置);
}
@凌驾
已滚动页面上的公共void(int arg0、float arg1、int arg2){
}
@凌驾
公共无效onPageScrollStateChanged(int arg0){
}
});
}
@凌驾
已重新选择公共无效页签(页签,碎片事务){
}
@凌驾
已选择的公共事务(选项卡,碎片事务ft){
//在选定的选项卡上
//显示受尊重的片段视图
setCurrentItem(tab.getPosition());
}
@凌驾
已选择公共空页(选项卡,碎片事务ft){
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
MenuInflater充气机=getMenuInflater();
充气机。充气(右菜单。主菜单,菜单);
返回
Button button = (Button) findViewById(R.id.button_identity);