简体   繁体   中英

Can I use ArrayList in a class which extends Thread?

Is it possible to use an ArrayList within a class that extends Thread ? I have written some code to read from Bluetooth serial which was working, but I've added an ArrayList to keep track of what I'm reading. However I'm getting NullPointException on any line that accesses results . I know that ArrayList is not thread safe (although I may not understand fully what that means) so I may be trying to do impossible things but I thought I would check with the experts as ArrayLists are otherwise very easy to work with.

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private List<String> results;

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        List<String> results = new ArrayList<String>();

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

        init();
    }

    private void init(){
        code = new byte[16];
        checksum = 0;
        tempbyte = 0;
        bytesread = -1;
        if(!results.isEmpty()){
            Log.i(TAG, "Already have found: " + results.size() + " things.");
        }
    }

    public void run(){
       //do things
    }
}

In your constructor, you have created a local ArrayList reference with the same name as instance ArrayList, and initializing that.

List<String> results = new ArrayList<String>();  // This creates a local arraylist

So, your instance ArrayList reference is still null . Change that line to:

results = new ArrayList<String>();

This line

List<String> results = new ArrayList<String>();

is allocating an array list on a local variable results . You probably think it's allocating the class member. Try changing to

results = new ArrayList<String>();

The problem you have is that you are not initializing your instance variable but only a local variable with the same name.

Remove the List before result in your constructor.

this.results = results; //do this in constructor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM