[英]Return an ArrayList and String asyncTask
我如何从一个aSyncTask类返回一个ArrayList对象和一个String。
aSyncTask使用jsoup来检索表中的3个元素,这些元素放入一个新的Employee类中,然后作为一个arraylist返回给MainActivity,但是我希望它还返回该特定表的String。
主要活动
public void onButtonClick()
new GetEmployee() {
@Override
protected void onPostExecute(ArrayList<Employee> list) {
Intent intent = new Intent(getApplicationContext(), EmployeeActivity.class);
intent.putParcelableArrayListExtra("empClass", list);
//i want to also pass the title of the Employee table aswell as the list,
//after running the aSyncTask
startActivity(intent);
}
}.execute();
getEmployee的
public Employee empObj;
@Override
protected ArrayList<Employee> doInBackground(String... params)
{
ArrayList<Employee> emp = new ArrayList<Employee>();
String title;
try {
//get employee details from table using JSoup
//get employee table title using JSoup
empObj = new Emp(...);
emp.add(empObj);
return emp;
} catch (IOException e) {
e.printStackTrace();
}
return emp;
我如何从这里返回一个String以及一个Employee的ArrayList
您可以创建自己的类来响应
例如
class AsynckResult{
public List<Employee> list;
public String someString;
//ctor and methods
}
只需在你的AsyncTask中修复你的泛型
class YouAsyncTask extends AsyncTask<Void, Void, AsynckResult>
你的实现现在看起来像这样
@Override
protected AsynckResult doInBackground(String... params)
{
AsynckResult result = new AsynckResult();
ArrayList<Employee> emp = new ArrayList<Employee>();
String title;
try {
//get employee details from table using JSoup
//get employee table title using JSoup
empObj = new Emp(...);
emp.add(empObj);
result.list = emp;
result.someString = title;
return result;
} catch (IOException e) {
e.printStackTrace();
}
return result;
但如果它有效,我会返回null
另一种方法可以如下...在GetEmployee类中添加以下行:
abstract class GetEmployee{
// your declaration
String title; //my return string
@Override
protected ArrayList<Employee> doInBackground(String... params){
ArrayList<Employee> emp = new ArrayList<Employee>();
String title;
try {
//get employee details from table using JSoup
//get employee table title using JSoup
empObj = new Emp(...);
bus.add(empObj);
title="myTitle" //fetch some title value here...2
return emp;
} catch (IOException e) {
e.printStackTrace();
}
return emp;
}
@Override
protected void onPostExecute(ArrayList<Employee> list) {
myPostExecute(list,title);
}
public abstract void myPostExecute(ArrayList<Employee> emp,String title);
}
现在在您的MainActivity中:
public void onButtonClick()
new GetEmployee() {
@Override
protected void myPostExecute(ArrayList<Employee> list,String title) {
Intent intent = new Intent(getApplicationContext(), EmployeeActivity.class);
intent.putParcelableArrayListExtra("busClass", list);
intent.putString("title",title);//this is your title
startActivity(intent);
}
}.execute();
然后使用Map作为结果
Map<String,Object> data=new HashMap<String, Object>();
data.put("employees",ArrayList<Employee>);
data.put("title", title);
然后在doInBackground中返回Map。
希望这会对你有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.