0

I'm trying to code a AsyncTask, but AndroidStudio give me warn:

this Aynctask class should be static or leaks might occur

I found in stack 3 solution here: click :

  1. asyncTasc static

  2. weakReference

  3. asyncListener

This topic is old, so for sure I ask: these solution are still 'on time' ?
Which of these solutions is professional and used in real projects?

My code:

@Override
public void onClick(View view) {

    String loginFromUser = etLogin.getText().toString();
    String passwordFromUser = etPassword.getText().toString();
    GetUsers getUsers = new GetUsers();
    getUsers.execute(loginFromUser, passwordFromUser);

}

.

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

    @Override
    protected Void doInBackground(String... strings) {

        String login = strings[0];
        String password = strings[1];

        Log.w("Credentials: ", "" + login + password);

        return null;
    }
}
companyn2
  • 85
  • 1
  • 9

1 Answers1

0

Any solution that doesn't keep the implicit reference held by the non-static inner class around is totally acceptable. In the example you provide, you can simply change

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

to

private static class GetUsers extends AsyncTask<String, Void, Void>{

If at some point you need to reference members of the outer class, then create a WeakReference to the outer instance as a member of the inner class, like this:

private static class GetUsers extends AsyncTask<String, Void, Void> {
    private final WeakReference<OuterClass> outer;

    GetUsers(OuterClass outer) {
        this.outer = new WeakReference<>(outer);
    }

    @Override
    protected Void doInBackground(String... strings) {
        OuterClass outer = this.outer.get();
        // Return early if the outer reference is null
        if (outer == null) {
            return null;
        }
        // Your logic...
        return null;
    }
}
Dave
  • 4,282
  • 2
  • 19
  • 24