MainActivity.this不是一个封闭的类AsyncTask

Vla*_*eys 10 java android android-asynctask

我正在尝试第一次创建一个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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

A--*_*--C 20

Eclipse的可能是正确的,而你试图访问一个类(MainActivity),它里面的自己的文件,从另一个类是在它自己的文件(BackgroundWorker).没有办法做到这一点 - 一个班级如何神奇地了解对方的实例?你可以做什么:

  • 移动AsyncTask,使其成为内部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...
Run Code Online (Sandbox Code Playgroud)

至于

我不确定我是否使用正确的方法来获取上下文

没事.