2013-06-26 58 views
1

我嘗試構建一個填充列表視圖的異步任務。當我嘗試,並與設置我的ListView與findViewBYId:無法訪問我的異步任務

ListView lv = (ListView) ((View) c).findViewById(R.id.tastelist); 

我得到這個錯誤:

Cannot cast from Context to View 

我的整個異步任務類:

public class GetTasteJSON extends AsyncTask 
<String, Void, String> { 

    Context c; 

    public GetTasteJSON(Context context) 
    { 
     c = context; 
    } 

    @Override 
    protected String doInBackground(String... arg0) { 
     // TODO Auto-generated method stub 
     return readJSONFeed(arg0[0]); 
    } 

    protected void onPostExecute(String result){ 

     //decode json here 
     try{ 

      JSONObject json = new JSONObject(result); 

      //acces listview 
      ListView lv = (ListView) ((View) c).findViewById(R.id.tastelist); 

      //make array list for beer 
      final List<BeerData> beerList = new ArrayList<BeerData>(); 

     } 
     catch(Exception e){ 

     } 

    } 

    public String readJSONFeed(String URL) { 
     StringBuilder stringBuilder = new StringBuilder(); 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(URL); 
     try { 
      HttpResponse response = httpClient.execute(httpGet); 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 
      if (statusCode == 200) { 
       HttpEntity entity = response.getEntity(); 
       InputStream inputStream = entity.getContent(); 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(inputStream)); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        stringBuilder.append(line); 
       } 
       inputStream.close(); 
      } else { 
       Log.d("JSON", "Failed to download file"); 
      } 
     } catch (Exception e) { 
      Log.d("readJSONFeed", e.getLocalizedMessage()); 
     }   
     return stringBuilder.toString(); 
    } 

} 
+0

錯誤出現在表示'((View)c).findViewById(R.id.tasteList)'的行中。您的圓括號表示將上下文c轉換爲視圖。也許嘗試'((ListView)c.findViewById(R.id.tasteList))' – bbill

+0

是的,當我只是爲了c.finViewById eclipse告訴我把它轉換到一個視圖... – Mike

+0

對。我編輯了我的評論。我認爲Eclipse會在錯誤的位置添加演員。您應該只需要ListView強制轉換的附加括號。 – bbill

回答

1

更改鑄造

ListView lv = (ListView) ((Activity) c).findViewById(R.id.tastelist); 

t中的上下文他的情況應該是你的活動

0

調用findViewById from和activity(在這種情況下是上下文)和View(我相信你正在嘗試做)之間有區別。如果您已經充氣以啓動活動的視圖是您希望獲得的視圖的父視圖,那麼您可能想嘗試投射到您的活動,而不是視圖。否則,嘗試創建一個ViewGroup類型的實例變量,並使用setter傳入父視圖。

+0

我不認爲他誇大了他的佈局。他只是因爲Eclipse的建議而將它鑄造成View。 – Enrichman

+0

是的,我認爲你是對的(我在回答問題時沒有看到評論)。我同意演員對演員的解決方案。也許可以通過一個Activity實例變量而不是一個Context實例變量來避免強制轉換(我不知道代碼的其餘部分就說這個) – Scott

0

上下文必須是你的活動,以便將它轉換爲你的活動,而不是一個視圖像你這樣......

如果你有一個列表的活動,你只需要做這樣的:

ListView lv=((ListActivity) context).getListView();