Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using AsyncTask this way: "new AsyncTask(){" is giving me errors

Im following an android tutorial on GCM which uses a function called "doInBackground" and they have this function defined like this:

private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected String doInBackground(Void... params) {
            //do stuff
        }
        @Override
        protected void onPostExecute(String msg) {
            //do stuff
        }
    }.execute(null, null, null);
}

but when I coppy and paste their own code into eclipse, it complains and says that that I have not implemented doInBackground. This is because it is expecting doInBackground to have an input parameter of "Object" and its not recognizing the one that is defined because its input parameter is a void. Now if I was declaring async task as a class, I would put <Void, Void, String> in front of it, and that would tell the compiler that I want my doInBackground to have VOid as input. but when I put <Void, Void, String> in front of "new AsyncTask()" as such:

    private void registerInBackground() {
    new AsyncTask() <Void, Void, String>{

I get compiler error:

Syntax error on tokens, delete these tokens
like image 805
Siavash Avatar asked Sep 09 '13 20:09

Siavash


2 Answers

You should have the () after the parameter type spec:

new AsyncTask<Void, Void, String>() { /*Your code(e.g. doInBackground )*/ }.execute();  
like image 123
Scott Stanchfield Avatar answered Oct 08 '22 15:10

Scott Stanchfield


Try this:

new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground( Void... voids ) {
        //Do things...
        return null;
    }
}.execute();
like image 37
James McCracken Avatar answered Oct 08 '22 14:10

James McCracken