我想从我的 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/