I use the retrofit library for the Android network operation. I have two domain addresses. I store the addresses with SharedPreferences. How can I use different endpoints.
for example:
www.mehmet.com/api/list
ww.deniz.com/api/list
www......
www.....
Code:
public class ptsApi {
public static String BASE_URL = "";
private static ptsApi instance;
private ptsService ptsService;
private ptsApi(Context c) {
SharedPreferences sharedpreferences = c.getSharedPreferences("loginPref", Context.MODE_PRIVATE);
String BASE_URL = sharedpreferences.getString("api","").toString();
final Gson gson =
new GsonBuilder().
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ptsService = retrofit.create(ptsService.class);
}
public static ptsApi getInstance(Context c) {
if (instance == null) {
instance = new ptsApi(c);
}
return instance;
}
public Observable<SearchModel> getSearch(@NonNull String plate) {
return ptsService.searchData(plate);
}
You can try this.
public class ptsApi {
enum TYPE {
MEHMENT, DENIZ
}
private static ptsApi instance;
private ptsService ptsService;
private ptsApi(Context c, TYPE type) {
final String BASE_URL = getEndpoint(type);
final Gson gson =
new GsonBuilder().
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ptsService = retrofit.create(ptsService.class);
}
public static ptsApi getInstance(Context c, TYPE type) {
if (instance == null) {
instance = new ptsApi(c, type);
}
return instance;
}
public Observable<SearchModel> getSearch(@NonNull String plate) {
return ptsService.searchData(plate);
}
public String getEndpoint(TYPE type) {
SharedPreferences sharedpreferences = c.getSharedPreferences("loginPref", Context.MODE_PRIVATE);
switch (type) {
case MEHMENT:
return sharedpreferences.getString("mehmentApi","").toString();
case DENIZ:
return sharedpreferences.getString("denizApi","").toString();
default:
return "your default";
}
}
}
or you can create some method like
public static ptsApi getMehmetInstance(Context c) {
if (instance == null) {
instance = new ptsApi(c, MEHMENT);
}
return instance;
}
public static ptsApi getDenizInstance(Context c) {
if (instance == null) {
instance = new ptsApi(c, DENIZ);
}
return instance;
}