android - 无法从我的异步任务访问我的 ListView

标签 android android-listview android-asynctask

我正在尝试构建一个填充 ListView 的异步任务。当我尝试使用 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);

本例中的上下文应该是您的 Activity

关于android - 无法从我的异步任务访问我的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17331620/

相关文章:

Android - 梯度怪异

android - 当点击 editText 时显示 android 键盘

android - 在 ListView 中的每一行周围放置一个边框

java - 引起的java.lang.UnsupportedOperationException : addView(View,layoutParams)在AdapterView中不受支持

android - android中的listview复选框问题

Android Http 请求 - 如何禁用缓存

android - 滚动在 Google+ Android 应用程序中如何工作?

java - Android http 响应出现堆栈溢出错误

android - 如何在android中多次获取同一个异步类调用的状态?

java - 如何将整数数组从 AsyncTask 获取到同一 Activity 中的另一个方法?