2013-01-02 39 views
10

我想第一次創建一個AsyncTask,但我沒有太多的運氣。MainActivity.this不是封閉類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)); 
     } 
    } 
} 

回答

19

Eclipse的可能是正確的,而你試圖訪問一個類(MainActivity)是它裏面的另一個類是在它自己的文件(自己文件BackgroundWorker)。沒有辦法做到這一點 - 一個班級如何神奇地瞭解對方的情況?你可以做什麼:

  • 。移動的AsyncTask所以它是一個innerMainActivity
  • 冒充你的活動到的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... 

至於

我不知道如果我用正確的方式來獲得上下文

這是好的。

+0

謝謝您的回覆。 BackgroundWorker和MainActivity是兩個不同文件中的兩個不同的類。我如何將活動和上下文傳遞給AsyncTask?我使用intellij IDEA btw :) –

+0

@ VladSpreys查看我更新的答案。 –

+0

完美!謝謝:) –