gpt4 book ai didi

java - 使用接口(interface)从异步任务 onpostexecute 获取数据

转载 作者:行者123 更新时间:2023-11-29 04:39:32 25 4
gpt4 key购买 nike

您好,我正在尝试从异步任务类获取数据数组列表到另一个主类:

我一直在关注下面的答案,但我有点迷茫:

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

所以我的类扩展异步任务并调用数据库以获取我的对象数组:

public class GetVideoInfoFromDataBase extends AsyncTask {

// Paginated list of results for song database scan
static PaginatedScanList<AlarmDynamoMappingAdapter> results;

// The DynamoDB object mapper for accessing DynamoDB.
private final DynamoDBMapper mapper;

public interface AlarmsDataBaseAsyncResponse {
void processFinish(PaginatedScanList<AlarmDynamoMappingAdapter> output);
}

public AlarmsDataBaseAsyncResponse delegate = null;

public GetVideoInfoFromDataBase(AlarmsDataBaseAsyncResponse delegate){
mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
this.delegate = delegate;
}

@Override
protected Object doInBackground(Object[] params) {

DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
results = mapper.scan(AlarmDynamoMappingAdapter.class, scanExpression);
return results;
}

@Override
public void onPostExecute(Object obj) {

delegate.processFinish(results);

}
}

没有错误,但我认为我在其中做错了什么导致了我的错误。

所以在我调用结果的主要 Activity 中:

GetVideoInfoFromDataBase asyncTask =new GetVideoInfoFromDataBase(new GetVideoInfoFromDataBase.AlarmsDataBaseAsyncResponse(){


@Override
public void processFinish(PaginatedScanList<AlarmDynamoMappingAdapter> output) {

}
}).execute();

这里有两个问题

  1. 我收到错误:
    “不兼容的类型:AsyncTask 无法转换为 GetVideoInfoFromDataBase”

在我的主要 Activity 中:

`new GetVideoInfoFromDataBase(new GetVideoInfoFromDataBase.AlarmsDataBaseAsyncResponse()`

它要我这样投它:

(GetVideoInfoFromDataBase) new GetVideoInfoFromDataBase(new GetVideoInfoFromDataBase.AlarmsDataBaseAsyncResponse()

这似乎不对,但我想我会检查一下。

  1. 我不确定在覆盖 onprocessfinished 时如何返回结果。

预先感谢您的帮助

最佳答案

首先创建一个接口(interface)

public interface AsyncInterface {
void response(String response);
}

在 asynctask 类中分配它,如下所示:-

Context context;
Private AsyncInterface asyncInterface;

AsyncClassConstructor(Context context){
this.context = context;
this.asyncInterface = (AsyncInterface) context;
}

然后在 asynctask 类的 onPostExecute 方法中:-

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
asyncInterface.response(s);
}

然后在你的 Activity 中实现这个接口(interface):-

class MainActivity extends AppCompatActivity implements AsyncInterface {

然后引入asyncInterface的方法

@Override
public void response(String response) {
//Here you get your response
Log.e(TAG, response);
}

关于java - 使用接口(interface)从异步任务 onpostexecute 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com