2013-06-26 106 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();