将图像加载到Gridview中

时间:2013-01-04 19:40:20

标签: android

我正在尝试使用通用图像加载程序将图像加载到gridview中,但我的应用程序似乎在活动加载时崩溃,我无法识别问题。我正在从数组中加载图像,然后调用图像适配器来填充它们。

非常感谢所有帮助:)

public class MainActivity extends Activity {

String[] imageUrls;

DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();

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

    Bundle bundle = getIntent().getExtras();
    imageUrls = bundle.getStringArray(Extra.IMAGES);

    options = new DisplayImageOptions.Builder()
        .showStubImage(R.drawable.stub_image)
        .showImageForEmptyUri(R.drawable.image_for_empty_url)
        .cacheInMemory()
        .cacheOnDisc()
        .bitmapConfig(Bitmap.Config.RGB_565)
        .build();

    GridView gridView = (GridView) findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter());


}

public class ImageAdapter extends BaseAdapter {
    @Override
    public int getCount() {
        return imageUrls.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ImageView imageView;
        if (convertView == null) {
            imageView = (ImageView) getLayoutInflater().inflate(R.layout.item_grid_image, parent, false);
        } else {
            imageView = (ImageView) convertView;
        }

        imageLoader.displayImage(imageUrls[position], imageView, options);

        return imageView;
    }
}

}

Logcat错误:

01-04 14:43:40.990: E/AndroidRuntime(11510): FATAL EXCEPTION: main
01-04 14:43:40.990: E/AndroidRuntime(11510): java.lang.RuntimeException: ImageLoader must be init with configuration before using
01-04 14:43:40.990: E/AndroidRuntime(11510):    at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:175)
01-04 14:43:40.990: E/AndroidRuntime(11510):    at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:131)
01-04 14:43:40.990: E/AndroidRuntime(11510):    at com.example.breaktheglass.ImageGridActivity$ImageAdapter.getView(ImageGridActivity.java:96)

所以我补充说:

ImageLoader.init(ImageLoaderConfiguration.createDefault(this));

在我调用imageloader之前(在.getInstance下面),但它只是给了我这个错误:

Syntax error on token "init", Identifier expected after this token

我不太确定从哪里开始......

1 个答案:

答案 0 :(得分:1)

只需改变你的代码序列,

protected ImageLoader imageLoader;

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

    imageLoader = ImageLoader.getInstance();
    imageLoader.init(ImageLoaderConfiguration.createDefault(this));

让我知道发生了什么......

有关详细信息,请查看https://github.com/nostra13/Android-Universal-Image-Loader