Skip to content

@ApplicationContext doesn't work with fragments. #2

@s0nerik

Description

@s0nerik

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions