texView.setText( “字符串”);不保留新文本设置

时间:2014-07-12 01:51:50

标签: java android xml bluetooth textview

我正在编写代码来打开我的房间门。但我有一个问题。 TextView.setText不保留新的String我可以看到当系统询问用户时是否更改了String如果允许启用蓝牙textViewBluetooth.setText工作,但是当蓝牙启用时,textViewBluetooth返回到activity_main.xml上设置的原始字符串我甚至没有看到它再次更新,甚至在特殊按钮上设置文字。

我已经调试了我的代码,我可以看到在TextView中调用的setText但仍然没有更新字符串。 我尝试添加一个新的TextView,但我在TextView中都遇到了同样的问题。 我评论bluetoothThread类,但问题仍然存在。

感谢您的时间。

public class MainActivity extends ActionBarActivity {

private static final int REQUEST_ENABLE_BT = 1;
private static final int RESULT_SETTINGS = 1;
private BluetoothAdapter mBTadapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice>pairedDevices;

private BluetoothThread mBluetoothThread = null;

final String deviceAddress = "98:D3:31:20:0B:C9";
String SN = null;

TextView textViewBluetooth;
ImageView imageViewBT;
ImageView imageViewAbrir;
ImageView imageViewCerrar;

boolean NewDevice = false;

ArrayList listNoBondedDevices = new ArrayList();
ArrayAdapter<String> mNewDevicesArrayAdapter;

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

    textViewBluetooth = (TextView) findViewById(R.id.textView01);
    imageViewBT = (ImageView) findViewById(R.id.imageViewBT);
    imageViewAbrir = (ImageView) findViewById(R.id.imageViewAbrir);
    imageViewCerrar = (ImageView) findViewById(R.id.imageViewCerrar);

    mNewDevicesArrayAdapter = new ArrayAdapter<String>
    (this,android.R.layout.simple_list_item_1,listNoBondedDevices);
    registerReceiver(mReceiver,new IntentFilter(BluetoothDevice.ACTION_FOUND));

    mBluetoothThread = new BluetoothThread();
}

@Override
protected void onResume(){
    super.onResume();
    if(mBTadapter.isEnabled()){
        if(!mBluetoothThread.btSocketConnected) {
            setContentView(R.layout.activity_main);
            tryConnectBTdevice(deviceAddress);
        }
    }
    else {
        intentEnableBT();
    }
}

void intentEnableBT(){
    textViewBluetooth.setText("Encendiendo bluetooth");
    Intent intentEnableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intentEnableBT, REQUEST_ENABLE_BT);
}

void tryConnectBTdevice(String address){
    if(address != null && address != "00:00:00:00:00:00") {
        BluetoothDevice mBTdevice = mBTadapter.getRemoteDevice(address);
        if (!mBluetoothThread.btSocketConnected) {
            textViewBluetooth.setText("Conectando a\n" + address.toString());
            mBluetoothThread.connect(mBTdevice);
        }
    }
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    switch (requestCode){
        case REQUEST_ENABLE_BT:
            if(resultCode == Activity.RESULT_OK){
                textViewBluetooth.setText("Bluetooth encendido");
                tryConnectBTdevice(deviceAddress);
            }
            else if(resultCode == Activity.RESULT_CANCELED){
                textViewBluetooth.setText("No se logró encender Bluetooth");
            }
            break;
    }
}
}

我的蓝牙线程:

public class BluetoothThread {
boolean bconnectedthread = false;
boolean bconnectthread = false;
boolean bconnectthreadstart = false;
boolean brun = false;
boolean bconnectedsynchronized = false;
boolean btSocketConnected = false;
private BluetoothAdapter mBluetoothAdapter = null;
private static final UUID MY_UUID = 
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ConnectedThread mConnectedThread;
private ConnectThread mConnectThread;

public void write(byte[] out) {
    ConnectedThread r;
    synchronized (this) {

        r = mConnectedThread;
    }
    r.write(out);

}

private class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;


    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        mmDevice = device;
        bconnectthread = true;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothAdapter.cancelDiscovery();
        brun=true;
        try {
            mmSocket.connect();
            btSocketConnected = true;
        } catch (IOException connectException) {
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
        connected(mmSocket);
    }

    public void cancel() {
        try {
            mmSocket.close();
            btSocketConnected = false;
        } catch (IOException e) { }
    }
}


private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    public Handler mHandler = null;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        bconnectedthread = true;
        Message message;
        Handler mHandler;

        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];  
        int bytes; // bytes returned from read()

        while (true) {
            try {
                bytes = mmInStream.read(buffer);
                //mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                //   .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) {
        }
    }

    public void disconnectDevice() {
        if (mmSocket.isConnected()) {
            try {
                mmSocket.close();
                btSocketConnected = false;
            } catch (IOException e) {
            }
        }
    }
}

public synchronized void disconnect(){
    mConnectedThread.disconnectDevice();
}


public synchronized void connect(BluetoothDevice device)

{
    bconnectthreadstart=true;
    mConnectThread = new ConnectThread(device);
    mConnectThread.start();

}


public synchronized void connected(BluetoothSocket socket) {

    bconnectedsynchronized=true;
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();

}

}

我的activity_main.xml

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.automovil.app.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageViewBT"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:src="@drawable/bluetooth"
    android:onClick="onSyncBT" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView01"
    android:layout_below="@+id/imageViewBT"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="39dp"
    android:textColor="#00026a"
    android:text="Bluetooth"
    android:enabled="true"
    android:editable="false"
    android:clickable="false"
    android:autoText="false"
    android:autoLink="none" />

</RelativeLayout>

对不起我的英语语法:\ 非常感谢你的时间。 亚伯拉罕海梅

1 个答案:

答案 0 :(得分:0)

你在onResume中调用'setContentView'。在onCreate中调用它。

onActivityResult被称为BEFORE onResume,你在这里做自己的多线程,这可能很粗糙。特别是在这种情况下。

从onActivityResult调用tryConnectBTdevice,然后启动一个线程,但99%的时间你可能会在onResume中结束所有这一切,这意味着你的代码再次调用setContentView,再次尝试tryConnectBTdevice。

您从多个线程引用布尔基元来检查状态,这不是很好。应该使用AtomicBoolean,但这可能不是一个大问题。

如果我们一起工作,那么从我这里得到的长篇大论就是吃掉你的IOException。错误控制非常重要。那些被抛出是有原因的。它可能会爆炸,因为你已经连接了,这会让你接到双重呼叫的情况。

简单回答,假设你要忽略我对异常的所有警告。不要在onResume中调用setContentView,也不要在onActivityResult中调用tryConnectBTdevice,因为无论如何你都是从onResume调用它。

如果这是你的房间,那就OK。如果您正在制作产品,我强烈建议重写线程代码。