2013-06-26 3 views
1

목록보기를 채우는 비동기 작업을 작성하려고합니다. 내가 시도와 findViewById를 내 목록보기를 설정하는 경우 :내 비동기 작업에서 내 목록보기에 액세스 할 수 없습니다.

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 일식 일 때보기에 캐스트하도록 알려줍니다 ... – Mike

+0

맞아요. 내 의견을 편집했습니다. Eclipse가 잘못된 위치에 캐스트를 추가한다고 생각합니다. 이러한 여분의 괄호는 ListView 캐스트 주위에서만 필요합니다. – bbill

답변

1

변경

에 캐스팅

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

나는이 오류

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

그의 케이스가 귀하의 활동이어야합니다.

0

findViewById와 활동 (이 경우 컨텍스트) 및보기 (귀하가하려는 것)의 차이점이 있습니다. 활동을 시작하기 위해 비정상적으로 실행 한보기가 얻으려는보기의 부모 인 경우보기가 아닌 활동으로 전송하려고 할 수 있습니다. 그렇지 않으면 ViewGroup 유형의 인스턴스 변수를 만들고 setter를 사용하여 상위 뷰를 전달하십시오.

+0

나는 그가 레이아웃을 부 풀린다고 생각하지 않는다. Eclipse가 제안했기 때문에 그는 View에 그것을 캐스팅했다. – Enrichman

+0

네, 당신이 옳다고 생각합니다 (질문에 응답하는 동안 댓글을 보지 못했습니다). 나는 활동에 던지기가 해결책이라는 데 동의한다. 아마도 캐스트는 Context 인스턴스 변수 대신 Activity 인스턴스 변수로 피할 수 있습니다 (코드의 나머지 부분을 모른 채 이것을 말합니다) – Scott

0

문맥은 그냥 같이 그것을해야 할 경우

당신은 목록 활동이 ... 당신이 그랬던 것처럼 당신의 활동 때문에보기에 당신의 활동에 캐스팅하지 수 있습니다

ListView lv=((ListActivity) context).getListView(); 
관련 문제