我目前正在开发一款应用,我想添加一个按钮来切换某个ImageView的可见性。事先,我的UI上有3个GraphView,当切换可见性时,ImageView将重叠下面的两个图形。但是,当我运行该应用时,该应用已经停止了#39; btndiag按钮导致错误
public class MainActivity extends Activity {
private static final String TAG = "TUP-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private ConnectedThread mConnectedThread;
private boolean mIsUserInitiatedDisconnect = false;
// All controls here
private TextView mTxtReceive;
private Button mBtnDisconnect;
private Button mBtnStart;
private GraphView1 graphView1;
private GraphView2 graphView2;
private GraphView3 graphView3;
private StringBuilder recDataString = new StringBuilder();
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
private Button btnDiag;
private ImageView imgDiag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
graphView1 = (GraphView1) findViewById(R.id.graph_view1);
graphView2 = (GraphView2) findViewById(R.id.graph_view2);
graphView3 = (GraphView3) findViewById(R.id.graph_view3);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.d(TAG, "Ready");
mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
mBtnStart = (Button) findViewById(R.id.btnStart);
btnDiag = (Button)findViewById(R.id.btDiag);
mTxtReceive = (TextView)findViewById(R.id.textView);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnDisconnect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mIsUserInitiatedDisconnect = true;
new DisConnectBT().execute();
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mConnectedThread.write("B");
}
});
mBtnStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mConnectedThread.write("A");
}
});
btnDiag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btnDiag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
imgDiag.setVisibility(View.VISIBLE);
}
});
}
});
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
@Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[512];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
mTxtReceive.post(new Runnable() {
@Override
public void run() {
String[] items = strInput.split("\\*");
for (String item : items )
{
if(item.length() == 12){
try{
//get sensor value from string between indices 1-5;
final int value = Integer.parseInt(item.substring(1, 3));
ImageView imageView = (ImageView) findViewById(R.id.edg_image);
if ( value <= 77) {
imageView.setImageResource(R.drawable.left);
}
else if ( value <= 80 && value >=78) {
imageView.setImageResource(R.drawable.center);
}
else if ( value >= 81 ){
imageView.setImageResource(R.drawable.right);
}
System.out.println("acc = " + value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
//get sensor value from string between indices 1-5;
final int value = Integer.parseInt(item.substring(3, 6));
System.out.println("ecg = "+ value);
graphView1.plotProcedure1(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
final int value = Integer.parseInt(item.substring(6, 9));
System.out.println("eda = "+ value);
graphView2.plotProcedure2(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
try{
final int value = Integer.parseInt(item.substring(9, 12));
System.out.println("emg = "+ value);
graphView3.plotProcedure3(value);
}catch(NumberFormatException ex){ // handle your exception
System.out.println("Not an integer");
}
}
}
}
});
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
@Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
};
@Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
@Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket mBTSocket) {
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpOut = mBTSocket.getOutputStream();
} catch (IOException e) { }
mmOutStream = tmpOut;
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
logcat错误
01-04 07:04:08.467 22700-22700/com.tup.tup E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tup.tup, PID: 22700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tup.tup/com.tup.tup.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2273)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.tup.tup.MainActivity.onCreate(MainActivity.java:82)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2188)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2273)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1236)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)