我正在尝试构建一个填充列表视图的异步任务。当我尝试使用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();
}
}
答案 0 :(得分:1)
将转换更改为
ListView lv = (ListView) ((Activity) c).findViewById(R.id.tastelist);
本案例中的上下文应该是您的活动
答案 1 :(得分:0)
调用findViewById和activity(在本例中是上下文)和View(我相信你试图这样做)之间存在差异。如果您为了启动活动而夸大的视图是您想要获取的视图的父视图,您可能希望尝试强制转换为您的活动,而不是视图。否则,尝试创建ViewGroup类型的实例变量,并使用setter传入父视图。
答案 2 :(得分:0)
上下文必须是您的活动,因此将其投射到您的活动中,而不是像您那样投射到视图...
如果您有List活动,您只需这样做:
ListView lv=((ListActivity) context).getListView();