-2

I am relatively new (ish) to Java..

I am writing an Android app, and now I am going back over my code and tidying up and adhering my coding structure to a more best practice style.

I am building methods and classes as I see fit to avoid the numerous amounts of duplicate code that I have produced. I have found myself trying to create a class (e.g. HeavyStuff.java) that contains several AsyncTask methods inside it (e.g. MyTask1 and MyTask2). When calling the class from an activity, I'd like to execute MyTask1 at some point, and at some point elsewhere I'd like to execute MyTask2. I am trying to use the following respectively:

HeavyStuff.MyTask1 myTask1 = new HeavyStuff.MyTask1();
myTask1.execute();

And

HeavyStuff.MyTask2 myTask2 = new HeavyStuff.MyTask2();
myTask2.execute();

The problem is, I get an error saying that "HeavyTest is not an enclosing class". My class looks like this:

package com.wizzkidd.myapp;

import android.os.AsyncTask;

public class HeavyStuff {

    public class MyTask1 extends AsyncTask<String, String, String> {
        //...
        //...
    }

    public class MyTask2 extends AsyncTask<String, String, String> {
        //...
        //...
    }
}

The class can also be seen here in full: http://hastebin.com/yahihokupu

What am I missing that is required to make the class an "enclosing class".

-----EDIT-----

I've looked at the answer that was given as a possible duplicate to my question and it does not work. The answer given recommends using static for my inner class, but this doesn't work for me.

I have however found that I can do this:

HeavyStuff.MyTask1 myTask1 = new HeavyStuff().new MyTask1();
myTask1.execute();

It works, but what are the implications (if any) when doing it like this? Is it bad practice?

WizzKidd
  • 196
  • 8
  • 2
    Possible duplicate of [Is not an enclosing class Java](http://stackoverflow.com/questions/20252727/is-not-an-enclosing-class-java) – earthw0rmjim Nov 09 '16 at 10:35

2 Answers2

0

I understand that you put both MyTask1 and MyTask2 into the same class because they are similar, however in general this is not ideal.

If you plan on creating new instances of MyTask1 and also new instances of MyTask2 throughout your code base, then they should be in their own completely separate classes (i.e. MyTask1.java containing only class MyTask1).

You can still keep them "together" by putting them within the same java package, for example:

package.heavystuff

.

Rob
  • 305
  • 1
  • 8
0

I have found an answer to my question. I originally posted what I believe is a solution as an edit, but to clarify, this is my working answer:

HeavyStuff.MyTask1 myTask1 = new HeavyStuff().new MyTask1();
myTask1.execute();
WizzKidd
  • 196
  • 8