-1

I am trying to get the context to use in sharedprefs in a module of my app. The module doesn't have any Activity class extended nor does the Application Class. Below is the code:

public class GetMovieCreditsUseCase extends BaseUseCase {
public static String director = "";
public static boolean loaded = false;


public interface GetMovieCreditsUseCaseCallback extends BaseUseCaseCallback {
    void onImagesUrlsLoaded(List<ImageEntity> backdrops, List<ImageEntity> posters);
}

private String apiKey;
private int movieID;

public GetMovieCreditsUseCase(String apiKey, int movieID, GetMovieCreditsUseCaseCallback callback) {
    super(callback);
    this.movieID = movieID;
    this.apiKey = apiKey;
}


@Override
public void onRun() throws Throwable {
    API.http().movieDirectors(apiKey, movieID, new Callback<GetMovieCreditsResponse>() {
        @Override
        public void success(GetMovieCreditsResponse getMovieCreditsResponse, Response response) {
            ((GetMovieCreditsUseCaseCallback) callback).onImagesUrlsLoaded(getMovieCreditsResponse.getBackdrops(), getMovieCreditsResponse.getPosters());

            String json = new Gson().toJson(getMovieCreditsResponse);
            loaded = false;
            JSONObject jsonObj = null;
            try {
                jsonObj = new JSONObject(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            JSONArray c = null;
            try {
                c = jsonObj.getJSONArray("crew");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < c.length(); i++) {
                JSONObject obj = null;
                try {
                    obj = c.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String A = null;
                String B = null;
                try {

                    A = obj.getString("name");
                    B = obj.getString("job");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (B.equals("Director")) {
                    Log.d("Director", "Director is " + A);
                    director = A;
                    loaded = true;

//getSharedPreferences throws error as cannotResolveMethod
                        SharedPreferences prefs = getSharedPreferences("director", Context.MODE_PRIVATE);

                    prefs.registerOnSharedPreferenceChangeListener(
                            new SharedPreferences.OnSharedPreferenceChangeListener() {
                                public void onSharedPreferenceChanged(
                                        SharedPreferences prefs, String key) {
                                    System.out.println(key);
                                }
                            });



                    break;
                }
                System.out.println(A);
            }

            Log.d("Directing", json);


        }

        @Override
        public void failure(RetrofitError error) {
            if (error.getKind() == RetrofitError.Kind.NETWORK) {
                errorReason = NETWORK_ERROR;
            } else {
                errorReason = error.getResponse().getReason();
            }
            onCancel();
        }
    });
}
}

I tried different solutions but to no avail. getApplicationContext, getActivity, this or MyApplication.getContext() none of them worked(all throwing error)

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Darshan Gowda
  • 4,956
  • 3
  • 19
  • 27

2 Answers2

0

As I commented in comments, you can do this :

private String apiKey;
private int movieID;
private Context mContext;

public GetMovieCreditsUseCase(String apiKey, int movieID, GetMovieCreditsUseCaseCallback callback, Context context) {
    super(callback);
    this.movieID = movieID;
    this.apiKey = apiKey;
    this.mContext = context;
}

Then you can use :

SharedPreferences prefs = this.mContext.getSharedPreferences("director", Context.MODE_PRIVATE);

But I strongly recommend to you take a look on Dagger 2 to resolve this issues.

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

Option 1: Pass context through constructor

public class GetMovieCreditsUseCase extends BaseUseCase {
    private Context mContext;
    public GetMovieCreditsUseCase(Context context, String apiKey, int movieID,GetMovieCreditsUseCaseCallback callback) {
        super(callback);
        this.mContext = context;
        this.movieID = movieID;
        this.apiKey = apiKey;
    }
}

Option 2: Define your own Application class

AndroidManifest.xml

<application
        android:name=".application.MyApplication"
        ....

MyApplication.java

public class MyApplication extends Application {

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static Context getAppContext() {
        return mInstance.getApplicationContext();
    }
}

Then call MyApplication.getAppContext()

Liar
  • 1,235
  • 1
  • 9
  • 19
  • Option 1 can't be used as it is not resolved. That is, this.mContext never shows up. Also it says 'there is no default constructor available' Option 2 throws error while running – Darshan Gowda Jan 15 '19 at 12:31