我正在尝试第一次创建AsyncTask,但是运气不太好。
我的AsyncTask需要从服务器获取一些信息,然后将新的布局添加到主布局中以显示这些信息。
一切似乎都比较清楚,但是错误消息“MainActivity不是封闭类”让我感到困扰。
似乎没有其他人遇到这个问题,所以我认为我可能错过了非常明显的东西,但我不知道是什么。
此外,我不确定我是否使用了正确的方式来获取上下文,因为我的应用程序无法编译,所以我无法测试它。
非常感谢您的帮助。
以下是我的代码:
public class BackgroundWorker extends AsyncTask<Context, String, ArrayList<Card>> {
Context ApplicationContext;
@Override
protected ArrayList<Card> doInBackground(Context... contexts) {
this.ApplicationContext = contexts[0];//Is it this right way to get the context?
SomeClass someClass = new SomeClass();
return someClass.getCards();
}
/**
* Updates the GUI before the operation started
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
/**
* Updates the GUI after operation has been completed
*/
protected void onPostExecute(ArrayList<Card> cards) {
super.onPostExecute(cards);
int counter = 0;
// Amount of "cards" can be different each time
for (Card card : cards) {
//Create new view
LayoutInflater inflater = (LayoutInflater) ApplicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewSwitcher view = (ViewSwitcher)inflater.inflate(R.layout.card_layout, null);
ImageButton imageButton = (ImageButton)view.findViewById(R.id.card_button_edit_nickname);
/**
* A lot of irrelevant operations here
*/
// I'm getting the error message below
LinearLayout insertPoint = (LinearLayout)MainActivity.this.findViewById(R.id.main);
insertPoint.addView(view, counter++, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
}