我第一次尝试创建 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));
}
}
}
最佳答案
Eclipse 可能是正确的,并且您正试图从另一个位于其自己的文件 (后台工作人员
)。没有办法做到这一点 - 一个类应该如何神奇地了解另一个实例?你可以做什么:
- 移动 AsyncTask,使其成为 inner
MainActivity
中的类
- 将您的 Activity 传递给 AsyncTask(通过其构造函数),然后使用
activityVariable.findViewById();
进行访问(我在下面的示例中使用mActivity
)或者,您的ApplicationContext
(使用正确的命名约定,A
需要小写)实际上是MainActivity
的一个实例,您可以开始了,所以执行ApplicationContext.findViewById();
使用构造函数示例:
public class BackgroundWorker extends AsyncTask<Context, String, ArrayList<Card>>
{
Context ApplicationContext;
Activity mActivity;
public BackgroundWorker (Activity activity)
{
super();
mActivity = activity;
}
//rest of code...
至于
I'm not sure if I used the right way to get the context
没关系。
关于java - MainActivity.this 不是封闭类 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14116415/