前幾天我開始關注Android開發。我試圖從REST API中獲取數據,並且使用AsyncTask類來完成HTTP事務。問題是,我無法爲我的主要活動獲取上下文,以便查找我的ListView並將其內容分配給onPostExecute()。上下文無法解析爲類型
這裏是MainActivity.java:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadMediaList(this).execute();
}
}
這裏是DownloadMediaList.java:
public class DownloadMediaList extends AsyncTask<Void, Void, ArrayList<Media>> {
ListView listView = null;
Context mainContext = null;
public DownloadMediaList(Context main){
this.mainContext = main;
}
@Override
protected void onPreExecute(){
listView = (ListView) mainContext.this.findViewById(R.id.media_list);
}
// Operations that we do on a different thread.
@Override
protected ArrayList<Media> doInBackground(Void... params){
// Set an ArrayList to store the medias.
ArrayList<Media> mediaList = new ArrayList<Media>();
// Call the REST API and get the request info and media list in a JSONObject.
RESTFunctions restRequest = new RESTFunctions();
JSONObject jsonMedia = restRequest.getMediaList();
// Try catch to catch JSON exceptions.
try {
// Store the media list into a JSONArray.
JSONArray mediaArray = jsonMedia.getJSONArray("media");
// Create an instance of media to store every single media later.
Media media = new Media();
// Loop through the JSONArray and add each media to the ArrayList.
for (int i=0; i<mediaArray.length();i++){
media = new Media();
JSONObject singleMedia = mediaArray.getJSONObject(i);
media.setTitle(singleMedia.getString("titre"));
media.setYear(singleMedia.getString("annee"));
media.setLength(singleMedia.getString("duree"));
mediaList.add(media);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the ArrayList.
return mediaList;
}
// Operations we do on the User Interface. Synced with the User Interface.
@Override
protected void onPostExecute(ArrayList<Media> mediaList){
// Set TextViews in ListViews here
}
}
這些類兩個單獨的文件。
此行特別是給我找麻煩:
listView = (ListView) mainContext.this.findViewById(R.id.media_list);
我在做什麼錯?它告訴我Context無法解析爲一個類型,即使我已經導入了android.content.Context。我嘗試了實例化上下文,但我無法做到這一點。
似乎你不需要'mainContext.this'你試過(活動)mainContext?實際上,上下文本身沒有findViewById()方法。 – sandrstar
Whelp,看起來像我讀錯了,並放在上下文而不是活動。但是這不會導致我的活動滲透到另一個班級嗎? – Sefam
我基於自己最後的答案在這裏:http://stackoverflow.com/questions/4979454/the-method-findviewbyidint-is-undefined。在這種情況下,我應該怎麼做? – Sefam