2014-02-11 2 views
2

AsyncTask을 사용하여 웹에서 String[] 개의 이미지를 검색하고 있습니다.GridView에 비동기 데이터를로드하는 방법은 무엇입니까?

GridView Adapter을로드하려고하면 데이터가 아직 도착하지 않은 것입니다. 따라서 그 순간의 arraynull입니다. GridView을 인스턴스화하는 순간에 String[]에 데이터가 포함되도록하려면 어떻게해야합니까? 여기

다음은 onCreate()

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sample_grid_view); 

    Bundle extras = getIntent().getExtras(); 
    if (extras != null) { 
     query = extras.getString("query"); 
    } 

    new AsyncDownload().execute(); 

    GridView gv = (GridView) findViewById(R.id.grid_view); 
    gv.setAdapter(new SampleGridViewAdapter(this)); 
    gv.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     Toast.makeText(getApplicationContext(), "You have touched picture number " + String.valueOf(position) , Toast.LENGTH_SHORT).show(); 

    } 

    }); 
} 

이다 인 Adapter (즉, 이미지에 대한 설명을 참조하십시오)

final class SampleGridViewAdapter extends BaseAdapter { 
    private final Context context; 
    private final List<String> urls = new ArrayList<String>(); 

    public SampleGridViewAdapter(Context context) { 
    this.context = context; 
//In this line is where I call the images retrieved by the AsyncTask. 
//After finishing and opening the activity again, the images will be there, and will load correctly. 
    Collections.addAll(urls, SampleGridViewActivity.returnImages()); 
    Collections.shuffle(urls); 

    } 

    @Override public View getView(int position, View convertView, ViewGroup parent) { 
    SquaredImageView view = (SquaredImageView) convertView; 
    if (view == null) { 
     view = new SquaredImageView(context); 
     view.setScaleType(CENTER_CROP); 
    } 

    // Get the image URL for the current position. 
    String url = getItem(position); 

    // Trigger the download of the URL asynchronously into the image view. 
    Picasso.with(context) // 
     .load(url) // 
     .placeholder(R.drawable.placeholder) // 
     .error(R.drawable.error) // 
     .fit() // 
     .into(view); 

    return view; 
    } 

    @Override public int getCount() { 
    return urls.size(); 
    } 

    @Override public String getItem(int position) { 
    return urls.get(position); 
    } 

    @Override public long getItemId(int position) { 
    return position; 
    } 

} 

답변

2

당신은 어떤 내용없이 어댑터를 인스턴스화 할 수 주셔서 감사합니다 .. 생성자에서만 URL 컬렉션을 인스턴스화하기 만하면 생성시에 컨텐트를 추가 할 필요가 없습니다. 그것은 당신이 그것을 제공 할 때까지 그냥 아무것도 표시되지 않습니다 .. 예를 들어 addData()라는 메서드를 추가하면로드 된 데이터를 인수로 사용하고이 데이터를 어댑터의 Collection에 추가합니다. 그런 다음 어댑터의 notifyDatasetChanged() 메서드를 호출해야합니다.이 메서드는 새 내용으로 GridView를 다시 쿼리해야 함을 알립니다.

관련 문제