-1

As far as I know, I can't hold reference to the activity's context inside a Loader.

Is there a safe way to get resources inside Loader's loadInBackground() method?

azizbekian
  • 60,783
  • 13
  • 169
  • 249
AppiDevo
  • 3,195
  • 3
  • 33
  • 51
  • Can't your sort it after the results are delivered to listeners (which then display the info)? I mean you cannot do UI updates in loadInBackground anyway. – zaifrun Jun 06 '17 at 11:43
  • @zaifrun Of course I can sort it later, but I wanted to do this in worker thread. – AppiDevo Jun 06 '17 at 11:47

1 Answers1

0

See the docs of the constructor of Loader:

Loader (Context context)

Stores away the application context associated with context. Since Loaders can be used across multiple activities it's dangerous to store the context directly; always use getContext() to retrieve the Loader's Context, don't use the constructor argument directly. The Context returned by getContext() is safe to use across Activity instances.

And the implementation:


    public Loader(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * @return an application context retrieved from the Context passed to the constructor.
     */
    public Context getContext() {
        return mContext;
    }


So, within loadInBackground() you are free to get the resources from the context that Loader class retains, because it's an application context.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • I know that Loader holds application context. But will context.getApplicationContext().getResources().getString(R.string.my_string) return correct value? – AppiDevo Jun 06 '17 at 12:43
  • 1
    Yep, it will. You do not necessarily need an activity context in order to fetch resources. – azizbekian Jun 06 '17 at 12:44
  • Didn't know that. If resources only need to have application context, I wonder why Resources class doesn't have static methods like getString() etc. It would be much simpler if we shouldn't pass context to the class/method every time we only want to get proper resource. – AppiDevo Jun 06 '17 at 13:10
  • I'm not sure whether I understood you correctly, but there is such a method: [Resources#getString(int)](https://developer.android.com/reference/android/content/res/Resources.html#getString(int)). Also, you may have a look at [`Resources.getSystem()`](https://stackoverflow.com/q/8633539/1083957) API. – azizbekian Jun 06 '17 at 13:13