android-asyncservice icon indicating copy to clipboard operation
android-asyncservice copied to clipboard

@ApplicationContext doesn't work with fragments.

Open s0nerik opened this issue 9 years ago • 7 comments

Service field annotated with @ApplicationContext is null when injecting service into fragment.

Here's code from fragment:

    @InjectService
    PdfGeneratorService pdfGeneratorService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AsyncService.inject(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AsyncService.unregister(this);
    }

PdfGeneratorService:

@AsyncService
public class PdfGeneratorService {

    @ApplicationContext
    static Context context;

    public File generateClassRecordsTable(List<Student> students) {
        return new ClassTableCreator(context, students, context.getFilesDir()).create();
    }

}

Further investigation lead me to AsyncService.java, and here's the code that supposed to get Application context from object.

    /**
     * If the given object contains an Android context, extract
     * the application context and retain it statically.
     */
    private static void extractContextFromObject(Object object) {
        if (context == null && object instanceof Context) {
            context = ((Context) object).getApplicationContext();
        }
    }

But fragments doesn't have context, so I need to have a way to pass some context while injecting into fragment. Maybe some kind of builder approach for this would be better for this?

s0nerik avatar Jan 15 '15 14:01 s0nerik

As a workaround, have you tried using AsyncService.inject(this) in your Application's onCreate method? It should save the context from there.

JoanZapata avatar Jan 20 '15 10:01 JoanZapata

Thanks, it works. But this way of initialization wasn't clear for me when I ran into this issue. Maybe it would be better to make some initialization method which will take Context or (maybe even better) Application?

s0nerik avatar Jan 20 '15 13:01 s0nerik

Yep, exactly. I thought on the moment that it would work for most cases and then I forgot about it. I'll make one. Thanks for reporting.

JoanZapata avatar Jan 20 '15 14:01 JoanZapata

Thank you for this lib, it's great!

s0nerik avatar Jan 20 '15 14:01 s0nerik

Can you please give an example for that workaround?

htekgulds avatar Mar 03 '15 18:03 htekgulds

public class YourApplication extends Application {
    @Override
    public void onCreate() {
         AsyncService.inject(this);
    }
}

Don't forget to declare this application class in your AndroidManifest.xml.

JoanZapata avatar Mar 04 '15 13:03 JoanZapata

Thanks a lot! Your work is appreciated :)

htekgulds avatar Mar 05 '15 06:03 htekgulds