我正在尝试建立一个填充列表视图的异步任务。当我尝试使用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();
    }

}

最佳答案

更改为

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


在这种情况下,上下文应该是您的活动

10-08 05:40