簡體   English   中英

如何獲取模塊中沒有應用程序類的非活動類的上下文

[英]How to get context of a non activity class with no Application Class in a module

我正在嘗試獲取要在我的應用程序模塊中的 sharedprefs 中使用的上下文。 該模塊沒有擴展任何 Activity 類,也沒有擴展應用程序類。 下面是代碼:

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();
        }
    });
}
}

我嘗試了不同的解決方案,但無濟於事。 getApplicationContext, getActivity, this 或 MyApplication.getContext() 他們都沒有工作(都拋出錯誤)

正如我在評論中評論的那樣,您可以這樣做:

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;
}

然后你可以使用:

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

但我強烈建議你看看Dagger 2來解決這個問題。

選項 1:通過構造函數傳遞上下文

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;
    }
}

選項 2:定義您自己的應用程序類

AndroidManifest.xml

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

我的應用程序

public class MyApplication extends Application {

    private static MyApplication mInstance;

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

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

然后調用 MyApplication.getAppContext()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM