fatmanming
fatmanming

Reputation: 185

Async Task incompatible types

I've got an AsyncTask that's reading from a socket. The DoInBackground runs while the activity is open. I would like to cancel the DoInBackground when the activity closes but can't assign the variable when starting the AsyncTask. My class is :-

private class receivingData extends AsyncTask<String, Void, String> {

        private volatile boolean exit = false;
        DataInputStream in;

        byte[] fullBuffer = new byte[7];
        byte[] buffer = new byte[100];  // buffer store for the stream
        int bytes; // bytes returned from read()
        int bytesCount = 0;

        @Override
        protected String doInBackground(String... params) {
            try {
                if (socket.isConnected()) {
                    in = new DataInputStream(socket.getInputStream());
                    //Log.d(TAG,"In async receive data run, connected");
                }
            }catch(Exception e){
                Log.d(TAG, "in async receiveData - run exception - " + e.toString());
            }
            while(!exit){
                try {
                    bytes = in.read(buffer);        // Get number of bytes and message in "buffer"
                    System.arraycopy(buffer,0,fullBuffer,bytesCount,bytes);
                    bytesCount = bytesCount + bytes;
                    if(bytesCount >= 7) {
                        hdt.obtainMessage(RECEIVED_MESSAGE, bytesCount, -1, fullBuffer).sendToTarget();     // Send to message queue Handler
                        Log.d("DTA Read - ", "Message sent");
                        bytesCount = 0;
                        Log.d("DTA Read - ", "bytesCount re-set");
                    }
                }catch(Exception e){
                    Log.d(TAG, "Read Error - " + e.toString());
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

I'm declaring a variable and starting the AsyncTask like this.

private DateTimeActivity.receivingData mRecData;

// start async task to receive data
        mRecData = new DateTimeActivity.receivingData().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

This gives me an incompatible type error.

It says -

Required DateTimeActivity.receivingData

Found

android.os.asyncTask    <java.lang.string, java.lang.void, ava.lang.string>

Any help would be appreciated.

Upvotes: 0

Views: 550

Answers (1)

Hugo sama
Hugo sama

Reputation: 909

You need to first assign your variable, and then start the AsyncTask :

    // start async task to receive data
    mRecData = new DateTimeActivity.receivingData();
    mRecData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

Upvotes: 1

Related Questions