使用notifyDataSetChanged()不更新GridView

时间:2013-06-10 09:03:19

标签: android gridview android-asynctask android-gridview notifydatasetchanged

我有Activity GridView,其中包含图片。图像从设备的SD卡解析。 Activity启动后,使用AsyncTask将图像下载到SD卡。

问题是,下载图像时,GridView没有更新。 如果将更多图像添加到目录中(即,如果下载了更多图像),我希望更新此GridView 。我尝试了notifyDataSetChanged()invalidateViews(),但他们没有帮助。

这是我的MainActivity,Image适配器和AsyncTask的代码。请试着告诉我哪里弄错了。

MainActivity:

ImageAdapter ia = new ImageAdapter(this);   
GridView gridView; 

@Override   
public void onCreate(Bundle savedInstanceState){  
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_layout);

    gridView = (GridView) findViewById(R.id.grid_view);

    // Instance of ImageAdapter Class   
    ImageAdapter iAdapter = new ImageAdapter(this);     
    gridView.setAdapter(iAdapter);      
    iAdapter.notifyDataSetChanged();
    gridView.invalidateViews();
    new ImageDownlader(AndroidGridLayoutActivity.this, this).execute(downloadUrl);
    gridView.setOnItemClickListener(new OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {

            // Sending image id to FullScreenActivity
            Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
            // passing array index
            i.putExtra("id", position);
            startActivity(i);
        }
    });     
图像适配器的

getView()

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         ImageView imageView = new ImageView(mContext);
         imageView.setImageBitmap(getImageByIndex(imageThumbnails, position));
         imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
         imageView.setLayoutParams(new GridView.LayoutParams(155, 155));
         return imageView;
    }

ImageDownlader:

class ImageDownlader extends AsyncTask<String, Void, Void> {
    private Context context;
    public ImageDownlader(Context c){
    context = c;
}


Sync s = new Sync();

@Override
protected Void doInBackground(String... param) {
        // this is where images are downloaded to SD card
    saveToSD ();
    return null;
}

@Override
protected void onPreExecute() {
    Log.i("Async-Example", "onPreExecute Called");
}

protected void onPostExecute()
{
    Log.i("Async-Example", "onPostExecute Called");
}

1 个答案:

答案 0 :(得分:1)

首先,您应该从URL下载图像并将其返回。

import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
}   

第二个,创建一个适配器

import java.util.List;

import vn.mve.obj.Video;
import vn.mve.util.DownloadImageTask;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import vn.mve.e4u.Detail;
import vn.mve.e4u.R;

public class VideoAdapter extends BaseAdapter {
    private List<Video> list;
    private Context context;
    private LayoutInflater inflater;
    public VideoAdapter(Context context, List<Video> list) {
        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = inflater.inflate(R.layout.layout_video_gridview, parent, false);
        ImageView iv_thumb = (ImageView) view.findViewById(R.id.iv_thumb);
        new DownloadImageTask(iv_thumb).execute(list.get(position).getThumbnail());

        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText(list.get(position).getTitle());

        LinearLayout item = (LinearLayout) view.findViewById(R.id.item);
        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, Detail.class);
                intent.putExtra("ID", list.get(position).getId());
                context.startActivity(intent);
            }
        });
        return view;
    }

}

就在这里:

new DownloadImageTask(iv_thumb).execute(list.get(position).getThumbnail());

您可以创建一个DownloadImageTask实例,之后您可以获得这样的图像:

imageTask = new DownloadImageTask(iv_thumb).execute(list.get(position).getThumbnail());
Bitmap myImage = imageTask.get(); // Please put in try-catch

最后一个,在 MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    List<Video> list = null;
    MVideo mVideo = new MVideo(getApplicationContext());
    list = mVideo.getList(VideoType.GET_ALL);
    VideoAdapter adapter = new VideoAdapter(this, list);
    if (list != null) {
        GridView gvVideo = (GridView) findViewById(R.id.gv_video);
        gvVideo.setAdapter(adapter);
    }
}

希望这会对你有帮助!