我正在尝试在Android Studio中开发应用。我陷入了这种境地。 我使用AsyncHttp客户端从MySQL数据库中获取表名列表。我在UI活动中调用以下函数来填充Spinner中的值。但是我无法返回值。该值在内部类中以及返回类型为void的重写方法内部检索。请查看代码以进一步了解。
public void fetchAvailableLocations ()
{
AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
String _URL = ""; // Enter URL here
byte[] retreivedBytes;
httpClient.post(_URL, requestParams, responseHandler, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
retrievedBytes = bytes; //This is where I'm stuck
}
@Override
public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
//make toasts
}
});
}
一个解决方案我想到的是在UI活动中创建一个静态字段,创建一个以字节为参数的回调函数,并将静态字段分配给bytes参数然后调用它来自onSuceed方法。但这条路线看起来很难看。有更简单的方法吗?
我对Android编程有点新意,所以请帮忙。
答案 0 :(得分:1)
而不是扩展使用继承:
public class fetchAvailableLocationsClass implements AsyncHttpResponseHandler {
public void fetchAvailableLocations() {
AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
String _URL = ""; // Enter URL here
byte[] retreivedBytes;
httpClient.post(_URL, requestParams, responseHandler, this);
@Override
public void onSuccess ( int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes)
{
retrievedBytes = bytes; //This is where I'm stuck
}
@Override
public void onFailure ( int i, cz.msebera.android.httpclient.Header[] headers,
byte[] bytes, Throwable throwable){
//make toasts
}
}
}