我正在尝试使用picasso使用gridview和imageview(在运行时)将图像作为网格加载。代码失败,无法启动活动ComponentInfo {com.dbprox.tagpic / com.dbprox.tagpic.ImageGallaryPicasso}:java.lang.NullPointerException
package com.dbprox.tagpic;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.ArrayList;
public class ImageGallaryPicasso extends Activity {
ArrayList<String> stringArrayList = new ArrayList<String>();
String path= Environment.getExternalStorageDirectory().toString()+"/Pictures";
File f=new File(path);
File file[]=f.listFiles();
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallary_picasso);
for (int i = 0; i < file.length; i++) {
stringArrayList.add(file[i].getAbsolutePath());
}
GridView gridview = (GridView) findViewById(R.id.imagegridview);
//LoadPicassaImages();
gridview.setAdapter(new ImageListAdapter(this, stringArray));
}
class ImageListAdapter extends ArrayAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageUrls;
public ImageListAdapter(Context context, String[] imageUrls) {
super(context, R.layout.activity_image_gallary_picasso, imageUrls);
this.context = context;
this.imageUrls = imageUrls;
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = inflater.inflate(R.layout.activity_image_gallary_picasso, parent, false);
}
Picasso
.with(context)
.load(imageUrls[position])
.fit() // will explain later
.into((ImageView) convertView);
return convertView;
}
}
}
&#13;
答案 0 :(得分:1)
在适配器中试用此代码,
ViewHolder viewHolder;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = inflater.inflate(R.layout.activity_image_gallary_picasso, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.your_imageview);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Picasso.with(context)
.load(imageUrls[position])
.fit() // will explain later
.into(viewHolder.imageView);
return convertView;
}
public class ViewHolder{
ImageView imageView;
}