1

我正在尝试构建一个填充列表视图的异步任务。当我尝试使用 findViewBYId 设置我的 listView 时:

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();
    }

}
4

3 回答 3

1

将铸件更改为

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

这种情况下的上下文应该是你的 Activity

于 2013-06-26T22:43:37.223 回答
0

从和活动(在这种情况下是上下文)和视图(我相信您正在尝试这样做)调用 findViewById 之间存在区别。如果您为启动活动而膨胀的视图是您想要获得的视图的父级,您可能希望尝试将其转换为您的活动,而不是视图。否则尝试创建一个 ViewGroup 类型的实例变量并使用 setter 传入父视图。

于 2013-06-26T22:45:21.253 回答
0

上下文必须是您的活动,因此将其转换为您的活动,而不是像您所做的那样转换为视图...

如果你有一个列表活动,你只需要这样做:

ListView lv=((ListActivity) context).getListView();
于 2013-06-27T04:41:26.663 回答