我想获得改装响应列表并在OnResponse函数之外使用它,但是我试着这样做我总是得到一个null对象。 这是我的源代码
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ActivitiesResponse> call = apiService.getUserActivities(id);
call.enqueue(new Callback<ActivitiesResponse>() {
// If success
@Override
public void onResponse(Call<ActivitiesResponse>call, Response<ActivitiesResponse> response) {
list = response.body().getActivities();// I'm getting a not null response
}
// If failed
@Override
public void onFailure(Call<ActivitiesResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
//When I try to use the list here I'm getting a null object
答案 0 :(得分:4)
请求是异步的,因此当您尝试返回值时,请求可能尚未完成,因此您无法在请求之外使用它。如果要从请求中返回值,请使用回调接口。
将代码更改为方法并传递回调参数
实施例
public void onResume(){
super.onResume();
doRequest(new ApiCallback(){
@Override
public void onSuccess(ArrayList<YOURTYPE> result){
//do stuff here with the list from the request
}
});
}
onResume()中的示例用法,基本上您可以在任何地方执行此操作:
{
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn)
{
die('Failed to connect to server: ' . mysql_error());
exit;
}
$db_selected = mysql_select_db($dbname);
if(!$db_selected)
{
$db_selected = " CREATE DATABASE $dbname ";
}
}
请告诉我这是否符合您的需求
答案 1 :(得分:0)
因为onResponse()以异步方式运行。你无法得到它的价值。
您应该在onResponse()内调用使用list
值的方法。
例如。
call.enqueue(new Callback<ActivitiesResponse>() {
// If success
@Override
public void onResponse(Call<ActivitiesResponse>call, Response<ActivitiesResponse> response) {
list = response.body().getActivities();// I'm getting a not null response
yourMethod();
}
// If failed
@Override
public void onFailure(Call<ActivitiesResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
private void yourMethod() {
// list is used somewhere here
}