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));
}
}
}
謝謝您的回覆。 BackgroundWorker和MainActivity是兩個不同文件中的兩個不同的類。我如何將活動和上下文傳遞給AsyncTask?我使用intellij IDEA btw :) –
@ VladSpreys查看我更新的答案。 –
完美!謝謝:) –