我想从 sd 卡中获取图像并将其放置在图库视图中。为此,我已将该图像转换为位图,但它显示了某些错误..
图像转换代码..我附上了显示空指针异常的完整代码
private Gallery gallery;
private ImageView imgView;
int position;
private byte[] data = { };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
System.out.println("Enter the activity");
try{
String filepath = "/sdcard/";
File imagefile = new File(filepath + "abcdoutput.jpg");
FileInputStream fis = new FileInputStream(imagefile);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
System.out.println("cnvrtn");
}
catch(Exception e) {
e.printStackTrace();
}
Bitmap bitmapimage = BitmapFactory.decodeByteArray(data, 0, data.length);
position = 0;
imgView = (ImageView) findViewById(R.id.ImageView01);
imgView.setImageBitmap(bitmapimage);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
imgView.setImageResource(data[position]);
DisplayImage.this.position = position;
}
});
System.out.println("Enter the activity//////////");
imgView.setOnLongClickListener(new View.OnLongClickListener() {
@SuppressWarnings("deprecation")
public boolean onLongClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(
DisplayImage.this).create();
alertDialog.setTitle("Confirmation");
alertDialog
.setMessage("Do you want to set this image as wallaper?");
alertDialog.setButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Bitmap bitmap = BitmapFactory.decodeResource(
getResources(), data[position]);
try {
DisplayImage.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
});
alertDialog.show();
return true;
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = null;
GalItemBg = typArray.getResourceId(
0, 0);
typArray.recycle();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
imgView.setImageResource(data[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}