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

前端之家收集整理的这篇文章主要介绍了java – MainActivity.this不是一个封闭的类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;
        for(Card card : cards)// Amount of "cards" can be different each time
        {
            //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可能是对的,您正在尝试从另一个属于自己的文件(BackgroundWorker)的类中访问它自己的文件内的类(MainActivity).没有办法做到这一点 – 一个课堂应该如何神奇地知道对方的实例?你可以做什么:

>移动AsyncTask,因此它是MainActivity中的一个inner
将你的Activity传给AsyncTask(通过它的构造函数),然后使用activityVariable.findViewById(); (我在下面的例子中使用了mActivity)或者,你的ApplicationContext(使用正确的命名约定,A需要是小写)实际上是一个MainActivity的一个实例,你很好去做,所以ApplicationContext.findViewById();

使用构造函数示例:

public class BackgroundWorker extends AsyncTask<Context,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

没事.

原文链接:https://www.f2er.com/java/125346.html

猜你在找的Java相关文章