在Android中使用AsyncTask在ExpandableListView中获取数据的解决方法如下:
public class MyAsyncTask extends AsyncTask> {
private Context mContext;
private ExpandableListView mExpandableListView;
public MyAsyncTask(Context context, ExpandableListView expandableListView) {
mContext = context;
mExpandableListView = expandableListView;
}
@Override
protected List doInBackground(Void... voids) {
// 执行耗时的操作,比如从网络或数据库中获取数据
List data = getDataFromServer();
return data;
}
@Override
protected void onPostExecute(List data) {
// 耗时操作完成后,在主线程中更新UI
if (data != null) {
// 更新ExpandableListView的数据
MyExpandableListAdapter adapter = new MyExpandableListAdapter(mContext, data);
mExpandableListView.setAdapter(adapter);
} else {
// 处理获取数据失败的情况
Toast.makeText(mContext, "获取数据失败", Toast.LENGTH_SHORT).show();
}
}
private List getDataFromServer() {
// 从服务器获取数据的逻辑
// ...
}
}
public class MainActivity extends AppCompatActivity {
private ExpandableListView mExpandableListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mExpandableListView = findViewById(R.id.expandableListView);
// 实例化AsyncTask并执行任务
MyAsyncTask task = new MyAsyncTask(MainActivity.this, mExpandableListView);
task.execute();
}
}
注意:上述示例中的MyExpandableListAdapter是自定义的ExpandableListAdapter,你需要根据自己的需求来实现。