gpt4 book ai didi

java - 将多个值传递给 AsyncTask 类

转载 作者:行者123 更新时间:2023-12-01 22:35:19 25 4
gpt4 key购买 nike

我在尝试将 String 和对象传递给 AsyncTask 类时遇到一些问题。因此,当我单击按钮时,它应该将 String 和 EventReview 对象传递到 AsyncTask 类中:

viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
//Get the values returned from AsyncTask and pass it to another activity
}
}).execute(String.valueOf(eventIDTV.getText()));
}
});

在我的 AsyncTask 类中,我将 String 作为参数:

public static class GetEventDetailAsyncTask extends AsyncTask<String, Integer, Double> {
EventController eventCtrl = new EventController();
Context context;

public interface OnRoutineFinished { // interface
void onFinish();
}

private OnRoutineFinished mCallbacks;

public GetEventDetailAsyncTask(OnRoutineFinished callback) {
mCallbacks = callback;
}

public GetEventDetailAsyncTask() {
} // empty constructor to maintain compatibility

public GetEventDetailAsyncTask(Context context){
this.context = context;
}

@Override
protected Double doInBackground(String... params) {
try {
eventCommentModel = eventCtrl.getEventCommentByID(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(Double result) {
if (mCallbacks != null)
mCallbacks.onFinish(); // call interface on finish

}

protected void onProgressUpdate(Integer... progress) {
}
}

所以我想知道是否有任何可能的方法将 String 和 EventReview 对象传递给execute(),然后当 doInBackground() 时,每个方法执行每个方法。有什么指南吗?

提前致谢。

最佳答案

您可以在 asynctask 的 Object[] 中传递 String 和自定义类的对象。

Object[] obj = new Object[2];
obj[0] = "my data";
obj[1] = myEventReviewObj;
new GetEventDetailAsyncTask().execute(obj);

异步任务:

public static class GetEventDetailAsyncTask extends AsyncTask<Object, Integer, Double> {


@Override
protected Double doInBackground(Object... params) {
String paramStr = "";
EventReview eventReview = null;
if(params[0] instanceof String && params[1] instanceof EventReview) {
paramStr = (String) params[0];
eventReview = (EventReview) params[1];
}
else {
eventReview = params[0];
paramStr = params[1];
}

try {
//perform operation using String and Object as per your need
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

希望这有帮助。

关于java - 将多个值传递给 AsyncTask 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958293/

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