1

I've been trying to create a function in my app that consist in a bluetooth RFID scanner, it's paired to my device and I have it working and all.

I can receive the text and log it in the console, when I compile the activity, everything goes fine, the stick reads the code, and then appends the text into an EditText, but if I go back and enter the activity again, I can see the code in the log, but the text doesn't go to the Edittext.

I tried a lot of different approaches, but nothing seems to work :/

here's the code I have:

 /**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bluetooth);


    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> bondedSet = mBluetoothAdapter.getBondedDevices();


    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();

    }

    if (!mBluetoothAdapter.isEnabled()) {
        Toast.makeText(this, "Please enable your BT and re-run this program.", Toast.LENGTH_LONG).show();
        finish();
    }
    if (mBluetoothAdapter.isEnabled()) {
        if(bondedSet.size() == 1){
            for(BluetoothDevice device : bondedSet){
                address = device.getAddress();
                Log.d("bt:", address);
            }
        }
    }
    String address = "00:A0:96:2A:0A:1B";
    out = (EditText) findViewById(R.id.output);

    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    Log.d(TAG, device.getName() + " connected");
    myConnection = new ConnectThread(device);
    myConnection.start();

}
private class ConnectThread extends Thread {
    private final BluetoothSocket mySocket;
    Message msg;

    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;

        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.d(TAG, "CONNECTION IN THREAD DIDNT WORK");
        }
        mySocket = tmp;
    }

    Handler uiThreadHandler = new Handler() {
        public void handleMessage(Message msg) {
            out = (EditText) findViewById(R.id.output);
            Object o = msg.obj;
            out.append(o.toString().trim());
            Log.d("handler", o.toString());
        }
    };

    public void run() {
        out = (EditText) findViewById(R.id.output);

        Log.d(TAG, "STARTING TO CONNECT THE SOCKET");
        setName("My Connection Thread");
        InputStream inStream = null;
        boolean run = false;
        mBluetoothAdapter.cancelDiscovery();

        try {
            mySocket.connect();
            run = true;
        } catch (IOException e) {
            Log.d(TAG, this.getName() + ": CONN DIDNT WORK, Try closing socket");
            try {
                mySocket.close();
                Log.d(TAG, this.getName() + ": CLOSED SOCKET");
            } catch (IOException e1) {
                Log.d(TAG, this.getName() + ": COULD CLOSE SOCKET", e1);
                this.destroy();
            }
            run = false;
        }

        synchronized (BluetoothActivity.this) {
            myConnection = null;
        }

        byte[] buffer = new byte[1024];
        int bytes;
        // handle Connection
        try {
            inStream = mySocket.getInputStream();
            while (run) {
                try {
                    bytes = inStream.read(buffer);
                    readMessage = new String(buffer, 0, bytes);
                    msg = uiThreadHandler.obtainMessage();
                    msg.obj = readMessage;
                    uiThreadHandler.sendMessage(msg);
                    Log.d(TAG, "Received: " + readMessage);
                } catch (IOException e3) {
                    Log.d(TAG, "disconnected");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
SoulRayder
  • 5,072
  • 6
  • 47
  • 93
marcoFSN
  • 125
  • 9
  • `but if I go back and enter the activity again, I can see the code in the log, but the text doesn't go to the Edittext.`: Do you mean the `handleMessage`, so the `Log.d` part is shown but `.append()` is not? – nKn Feb 11 '14 at 11:55
  • that's right.... i'm stuck in that part, since the i can's edit the edittext from the thread directly, i have to use the handleMessage, when i come back, i still see the Log.d showing the message, but not in the edittext, can you help please? i've been trying a lot and nothing fixes the situation.. thanks – marcoFSN Feb 11 '14 at 13:11
  • So after you restart your `Activity`, your `Log.d()` line appears. What's the content of that `Object` once restarted your `Activity`? – nKn Feb 11 '14 at 13:41
  • the content is what it recieves from the bluetooth stick, once i send data over bluetooth, it show the message on the log console, no on the editText view – marcoFSN Feb 11 '14 at 13:47
  • I mean, when you use `Log.d()` on that part that is missfunctioning, do you see the **correct** value once you restart your `Activity`? – nKn Feb 11 '14 at 13:58
  • yes, the values are correct, the function is working and i'm recieving the data i wish to show on the screen, the problem here is, the text does not show on the textview..when i first run the app, everythiong works, if i get out of the activity and come back again, it does not show anymore, only on the log console – marcoFSN Feb 11 '14 at 14:04

2 Answers2

0

My guess is that this has something to do with the Thread itself. When you start your Activity for the first time, you also call .start() on the Thread, that would work fine.

The problem is when you leave your Activity and open it up again. In that case, one of onStop() or onPause() is called (depending on situation), and onRestart() or onResume() will be called afterwards respectively.

The trick comes now: Meanwhile all that process, your Thread is still running. As you show your code, it has not been stopped/paused, and keeps running all the time. So basically my tip is that there's something you do within your onCreate() method of your Activity that should also be done in your onPause() and onStop() events, and my another tip it's somewhere within your ConnectThread(BluetoothDevice device) method.

To know how to procceed, I'd firstly define both onStop() and onPause() methods within your Activity and see which is fired, log every attribute to see its value/state, and that way you'll be able to debug what is failing.

There's a diagram of the Activity lifecycle.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • i did create the methods, it goes to onResume, but still, no progress, i think the thread should be stop, and started back again, i have a clean activity and it works fine, but in the activity i need it working the problem persists. – marcoFSN Feb 11 '14 at 15:28
  • I'm also of the opinion your thread should be stopped too in the `onPause()` and `onStop()` methods, and be restarted in the `onRestart()` and `onResume()` methods. Have you tested whether it works? – nKn Feb 11 '14 at 16:17
  • nop, i use the interrup method and it blows up xD i'm starting to think i shoud buy a farm and start growing potatoes, probably easier.... – marcoFSN Feb 11 '14 at 16:24
  • Technically is **very** strange that two consecutive lines, without any blocking mechanism such as `synchronized` don't execute secuentially. There must be something strange in there that results in what you're experiencing. Have a detailed look at your code, review all `synchronized` blocks to see whether there could be some that could be blocking your execution. Even if necessary, use the debugger step-by-step tool to see where it's the bottleneck. – nKn Feb 11 '14 at 16:33
0

Problem was solved, the code works, and the TextView get the inputstream, the problem was when i left the activity, the thread continued to work, so far, no problem at all, after TONS of hours spent on this, i turn the TextView a static var and it worked :)

If anyone reads this, i hope it helps.

marcoFSN
  • 125
  • 9