我试图将图像文件带到android存储但是android事件日志显示错误java.lang.RuntimeException和java.lang.nullpointerexception。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView=(GridView)findViewById(R.id.gridView);
custom adCustom= new custom(this);
gridView.setAdapter(adCustom);
}
类自定义扩展BaseAdapter {
Context context;
public custom(Context context){
this.context=context;
}
@Override
public int getCount(){
return getImage().length;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
if(convertView==null){ imageView=new ImageView(context);}else{imageView=(ImageView)convertView;}
imageView.setImageURI(getImage()[position]);
return imageView;
}
Uri[] uri;
String[] mfile=null;
public Uri[] getImage(){
File file= Environment.getExternalStorageDirectory();
final File[] filelist=file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return ((filename.endsWith(".jpg"))||(filename.endsWith(".png")));
}
}) ; mfile=new String[filelist.length];
for(int i=0;i<filelist.length;i++){
mfile[i]=filelist[i].getAbsolutePath();
}
uri=new Uri[mfile.length];
for(int i=0;i<uri.length;i++){
uri[i]=Uri.parse(mfile[i]);
}return uri;}}
答案 0 :(得分:0)
每次调用getView时,您都在重新创建和重建uri数组。这是低效的,可能会导致并发问题。因此,在适配器的构造函数中只调用一次getImage():
public custom(Context context){
this.context=context;
getImage();
}
然后您可以访问getView实现中的图像:
imageView.setImageURI(uri[position]);
P.S。将适配器类命名为custom
以外的其他类。 CustomImageAdapter
怎么样?