java - 从 RetrofitClient 内的 SharedPreferences 获取 BASE_URL

标签 java android sharedpreferences retrofit2


我想从我的 RetrofitClient 类中的 SharedPreferences 获取 BASE_URL
我的代码是:
RetrofitClient.java:

public class RetrofitClient {
    private static final String BASE_URL = getBaseUrl();

    private String getBaseUrl() {
        SharedPreferences sp1 = getSharedPreferences("Login", MODE_PRIVATE);
        String apiUrl = sp1.getString("apiUrl", null);
        return apiUrl;
    }

    private RetrofitClient() {
        //MyRetrofitClient...
    }
}

我怎样才能让它工作?
MainActivity.java:

Call<LoginResponse> call = RetrofitClient
            .getInstance()
            .getApi()
            .loginUser(username, password, action);

call.enqueue(new Callback<LoginResponse>() {

}

最佳答案

为了传递数据,您需要为该类创建一个构造函数。像这样的东西

public class ApiClient {

Context my_conext;

  public ApiClient (Context context) {

        my_conext= context;
    }

 SharedPreferences sp1 = my_context.getSharedPreferences("Login", MODE_PRIVATE);

}

编辑:来自您更新的代码。

你做错了。

首先不要在初始化时调用函数。像这样使用

 retrofit = new Retrofit.Builder()
                .baseUrl(getBaseUrl(my_context))
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

第二件事。您需要 **Constructor** constructor 与 class 具有相同的名称。仔细看我上面的回答。两者具有相同的名称 ApiClient。所以在你的情况下

public class RetrofitClient {

    Context my_conext;

      public RetrofitClient (Context context) {
            my_conext= context;
        }
    }

从 Activity 中,您正在调用此 RetrofitClient ,这样调用

   RetrofitClient(MainActivity.this).getApi();

关于java - 从 RetrofitClient 内的 SharedPreferences 获取 BASE_URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54782073/

相关文章:

java - Android 最佳实践 - View /Activity

java - 我可以在不发生事件的情况下将数据写入 firebase 吗?

java - 如何在 Android 上的 fragment 中使用共享首选项?

android - kotlin.UninitializedPropertyAccessException:lateinit属性首选项尚未初始化

java - Java FX 中的 "mnemonicParsing"属性是什么

java - 在小程序中显示框架

android - 播放Sound OnClick Android

android - 使用 SharedPreferences.getAll() 调用 keySet()

java - 从共享首选项获取值时出现空指针异常

java - Spring Boot REST - 如何实现需要 Java 对象的搜索?