Reputation: 33
var retrofitResponse: RetrofitResponse<APIResponse<User>>? = null
withContext(Dispatchers.IO) {
retrofitResponse = try {
val response = BindRetrofitWithService.getServiceInstance(
needCustomTimeOut = Config.isChinaBuild(appContext)
).registerUser(body, data)
RetrofitResponse(true, response)
} catch (e: Exception) {
RetrofitResponse(false, e.getAPIError())
}
}
return retrofitResponse!!
fun getServiceInstance(needCustomTimeOut: Boolean = false): APIServices {
if (GeneralUtils.isNetworkAvailable()) {
return getRetrofit(needCustomTimeOut).create(APIServices::class.java)
} else {
throw NoNetworkException()
}
}
fun getRetrofit(needCustomTimeOut: Boolean = false): Retrofit {
return getRetrofitObject(
null, if (needCustomTimeOut) {
CHINA_FILE_UPLOAD_CONNECT_TIME_OUT
} else {
CONNECT_TIME_OUT
}else {
WRITE_TIME_OUT
}
)
}
/**
* Custom Retrofit instance creation
*/
private fun getRetrofitObject(
headers: HashMap<String, String>?,
connectionTimeOut: Long,
readTimeOut: Long,
writeTimeOut: Long
): Retrofit {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val okHttpClient = OkHttpClient.Builder()
//okHttpClient.addInterceptor(MockInterceptor())
okHttpClient.addInterceptor { chain ->
//if(GeneralUtils.isNetworkAvailable()){
val original = chain.request()
val requestBuilder = original.newBuilder()
if (headers != null && headers.size > 0) {
for ((key, value) in headers) {
requestBuilder.addHeader(key, value)
}
}
val request = requestBuilder.build()
return@addInterceptor chain.proceed(request)
/*}else{
throw NoNetworkException()
}*/
}
okHttpClient.addInterceptor(loggingInterceptor)
okHttpClient.connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
okHttpClient.readTimeout(readTimeOut, TimeUnit.SECONDS)
okHttpClient.writeTimeout(writeTimeOut, TimeUnit.SECONDS)
return Retrofit.Builder()
.baseUrl(Config.getRetrofitBaseUrl(UCHContext.getAppContext()))
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.client(okHttpClient.build())
.build()
}
user model class
@SerializedName(DBConstants.COL_USER_PROFILE_NOTE)
@ColumnInfo(name = DBConstants.COL_USER_PROFILE_NOTE)
@Nullable
public String note = null;
@SerializedName(DBConstants.COL_USER_PROFILE_TITLE)
@ColumnInfo(name = DBConstants.COL_USER_PROFILE_TITLE_VAL)
@Nullable
public String titled = null;
@SerializedName(DBConstants.COL_USER_PROFILE_ADDRESSES)
@ColumnInfo(name = DBConstants.COL_USER_PROFILE_ADDRESSES)
@Nullable
public JsonObject addresses= new JsonObject();
Note : here sometimes "addresses":null come this scenario following error come #com.google.gson.JsonSyntaxException: Expected a com.google.gson.JsonObject but was com.google.gson.JsonNull; at path $.data.addresses #responseCode= 1208, responseCodeMessage= Api Failure, userMessage= Something went wrong, please try again. how solve this issue ? i tried custom or default Gson class also no use
Upvotes: 0
Views: 64