0

아래 코드를 시도한 후 AsyncTaskLoader 접근 방식을 시도했습니다. AsyncTask을 인스턴스화하면 앱이 다운됩니다. 탭 호스트 내부의 목록 조각에 JSON을로드하는 가장 좋은 방법에 대해 조언 해줍니다.ListFragment에서 AsyncTask를 사용할 수 있습니까? 또는 AsyncTaskLoader를 사용해야합니까?

public class TabTop extends ListFragment { 
Context context = getActivity().getBaseContext(); 
String API_URL = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json?apikey=crhhxb4accwwa6cy6fxrm8vj&limit=1"; 
ArrayList<Deal> deals; 
DealsListAdapter adapter; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     @SuppressWarnings("unused") 
     int a = 0; 
     return super.onCreateView(inflater, container, savedInstanceState); 
} 


@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    GetTopDeals getTopDeals = new GetTopDeals(context); 
    getTopDeals.execute(API_URL); 
    super.onActivityCreated(savedInstanceState); 
} 


class GetTopDeals extends AsyncTask<String, Void, ArrayList<Deal>>{ 
    ProgressDialog progressDialog; 

    public GetTopDeals(Context activity) { 
     this.progressDialog = new ProgressDialog(activity); 
    } 

    @Override 
    protected void onPostExecute(ArrayList<Deal> result) { 
     adapter = new DealsListAdapter(context, result); 
     setListAdapter(adapter); 
     super.onPostExecute(result); 
    } 

    @Override 
    protected void onPreExecute() { 
     progressDialog.setCancelable(true); 
     progressDialog.setProgress(0); 
     progressDialog.setMessage("loading Top deals..."); 
     progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     super.onPreExecute(); 
    } 


    @Override 
    protected ArrayList<Deal> doInBackground(String... urls) { 
     String response = sendRequest(urls[0]); // make request for json 
     return processResponse(response); // parse the Json and return ArrayList to postExecute 

    } 

    private String sendRequest(String apiUrl) { 
     BufferedReader input = null; // get the json 
     HttpURLConnection httpCon = null; // the http connection object 
     StringBuilder response = new StringBuilder(); // hold all the data from the jason in string separated with "\n" 

     try { 
      URL url = new URL(apiUrl); 
      httpCon = (HttpURLConnection) url.openConnection(); 

      if (httpCon.getResponseCode() != HttpURLConnection.HTTP_OK) { // check for connectivity with server 
       return null; 
      } 
      input = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); // pull all the json from the site 
      String line; 
      while ((line = input.readLine()) != null) { 
       response.append(line + "\n"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      if (httpCon != null) { 
       httpCon.disconnect(); 
      } 
     } 
     return response.toString(); 
    } 
} 

public ArrayList<Deal> processResponse(String response) { 
    try { 
     JSONObject responseObject = new JSONObject(response); // Creates a new JSONObject with name/value mappings from the JSON string. 
     JSONArray results = responseObject.getJSONArray("movies"); // Returns the value mapped by name if it exists and is a JSONArray. 
     deals = new ArrayList<Deal>(); 
     for (int i = 0; i < results.length(); i++) { // in this loop i copy the json array to movies arraylist in order to display listView 
      JSONObject jMovie = results.getJSONObject(i); 
      int api_id = jMovie.getInt("id"); 
      String name = jMovie.getString("title"); 
      String content = jMovie.getString("synopsis"); 
      JSONObject posters = jMovie.getJSONObject("posters"); 
      String image_url = posters.getString("profile"); 
     } 
    }catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return deals; 
} 

@Override 
public void onStart() { 
    super.onStart(); 

} 
@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    Intent intent = new Intent(getActivity().getBaseContext(), DealInformation.class); 
    startActivity(intent); 
    super.onListItemClick(l, v, position, id); 
} 
} 

답변

1

자신의 파일에 AsyncTask를합니다

아래의 코드는 탭 조각 (나는 주요 활동의 작업 표시 줄 탭을 사용)입니다.

asynctask가 완료되면 자동으로 호출되는 OnPostExecute를 구현하십시오. 그런 notifyDataSetChanged하여 어댑터를 통보 : 당신의 AsyncTask를 자체 파일이있는 경우

@Override 
    protected void onPostExecute(List<NewItem> list) { 
    Adapter.getListe().clear();  
    Adapter.getListe().addAll(list); 
    Adapter.notifyDataSetChanged(); 
} 
0

그것은 중요하지 않습니다. asynctask를 확장하면 활동이 비동기가되기 때문에 활동을 원하지 않습니다.하지만 자바의 이중 상속 규칙으로 인해 어쨌든 할 수 없습니다.

앱의 아키텍처와 프로그래밍 스타일에 따라 asyntask는 액티비티의 내부 클래스가 될 수 있습니다. PostExecute 메서드를 사용하여 어댑터에 데이터를 제공했는지 확인하고 어댑터가 목록에 설정된 다음 notifyDataSetChanged()를 실행하십시오.

당신의 AsyncTask를 캐시 또는 당신이 당신의 접근 방식과 올바른 궤도에 네트워크에서 데이터를로드하는 가정.

1

고마워요,

내 대답을 게시하고 싶습니다. 일부 연구 후에 AsyncTaskLoader를 사용하기로 결정했습니다. 이 내 코드

public class TabOurPicks extends ListFragment implements LoaderCallbacks<String[]> { 

// when activity loads- onActivityCreated() calls the initLoader() who activate onCreateLoader() 
@Override 
public void onActivityCreated(Bundle savedInstance) { 
    super.onActivityCreated(savedInstance); 
    setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new String[]{})); 
    getLoaderManager().initLoader(0, null,this).forceLoad(); 
} 

// onCreateLoader instantiate the asynctaskloaser who work in bg 
@Override 
public RSSLoader onCreateLoader(int arg0, Bundle arg1) { 
    return new RSSLoader(getActivity()); // 
} 

// after bg process invoke onLoadFinished() who work in ui thread 
@Override 
public void onLoadFinished(Loader<String[]> loader, String[] data) { 
    setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data 
)); 

} 

@Override 
public void onLoaderReset(Loader<String[]> arg0) { 
    // TODO Auto-generated method stub 

} 

이며,이 로더의 내부 클래스입니다 :

static public class RSSLoader extends AsyncTaskLoader<String[]> 
{ 
    public RSSLoader(Context context) { 
     super(context); 
    } 

    @Override 
    public String[] loadInBackground() { 
     String url = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json?apikey=crhhxb4accwwa6cy6fxrm8vj&limit=1"; 
     String response = sendRequest(url); 
     return processResponse(response); 
    } 


    private String sendRequest(String url) { 
     BufferedReader input = null; // get the json 
     HttpURLConnection httpCon = null; // the http connection object 
     StringBuilder response = new StringBuilder(); // hold all the data from the jason in string separated with "\n" 

     try { 
      URL apiUrl = new URL(url); 
      httpCon = (HttpURLConnection) apiUrl.openConnection(); 

      if (httpCon.getResponseCode() != HttpURLConnection.HTTP_OK) { // check for connectivity with server 
       return null; 
      } 
      input = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); // pull all the json from the site 
      String line; 
      while ((line = input.readLine()) != null) { 
       response.append(line + "\n"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      if (httpCon != null) { 
       httpCon.disconnect(); 
      } 
     } 
     return response.toString(); 
    } 

    private String[] processResponse(String response) { 
     String[] deals = null; 
     try { 
      JSONObject responseObject = new JSONObject(response); // Creates a new JSONObject with name/value mappings from the JSON string. 
      JSONArray results = responseObject.getJSONArray("movies"); // Returns the value mapped by name if it exists and is a JSONArray. 
      deals = new String[10]; 
      for (int i = 0; i < 9; i++) { // in this loop i copy the json array to movies arraylist in order to display listView 
       JSONObject jMovie = results.getJSONObject(i); 
       String name = jMovie.getString("title"); 
       deals[i] = name; 
      } 
     }catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return deals; 
    } 
} 

}