80,351
社区成员
发帖
与我相关
我的任务
分享
public class LoadImagesFromSDCardActivity extends Activity implements
OnItemClickListener {
private ListView sdcardImages;
private ImageAdapter imageAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.new_stir);
setupViews();
setProgressBarIndeterminateVisibility(true);
loadImages();
}
/**
* Free up bitmap related resources.
*/
protected void onDestroy() {
super.onDestroy();
final ListView grid = sdcardImages;
final int count = grid.getChildCount();
ImageView v = null;
for (int i = 0; i < count; i++) {
v = (ImageView) grid.getChildAt(i);
((BitmapDrawable) v.getDrawable()).setCallback(null);
}
}
/**
* Setup the grid view.
*/
private void setupViews() {
sdcardImages = (ListView) findViewById(R.id.new_listview);
sdcardImages.setOnItemClickListener(LoadImagesFromSDCardActivity.this);
imageAdapter = new ImageAdapter(getApplicationContext());
sdcardImages.setAdapter(imageAdapter);
}
/**
* Load images.
*/
private void loadImages() {
final Object data = getLastNonConfigurationInstance();
if (data == null) {
new LoadImagesFromSDCard().execute();
} else {
final LoadedImage[] photos = (LoadedImage[]) data;
if (photos.length == 0) {
new LoadImagesFromSDCard().execute();
}
for (LoadedImage photo : photos) {
addImage(photo);
}
}
}
/**
* Add image(s) to the grid view adapter.
*
* @param value
* Array of LoadedImages references
*/
private void addImage(LoadedImage... value) {
for (LoadedImage image : value) {
imageAdapter.addPhoto(image);
imageAdapter.notifyDataSetChanged();
}
}
/**
* Save bitmap images into a list and return that list.
*
* @see android.app.Activity#onRetainNonConfigurationInstance()
*/
@Override
public Object onRetainNonConfigurationInstance() {
final ListView grid = sdcardImages;
final int count = grid.getChildCount();
final LoadedImage[] list = new LoadedImage[count];
for (int i = 0; i < count; i++) {
final ImageView v = (ImageView) grid.getChildAt(i);
list[i] = new LoadedImage(
((BitmapDrawable) v.getDrawable()).getBitmap());
}
return list;
}
/**
* Async task for loading the images from the SD card.
*
* @author Mihai Fonoage
*
*/
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
/**
* Load images from SD Card in the background, and display each image on
* the screen.
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Object doInBackground(Object... params) {
// setProgressBarIndeterminateVisibility(true);
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
// Set up an array of the Thumbnail Image ID column we want
String[] projection = { MediaStore.Images.Thumbnails._ID };
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null, null);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
// No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
// Error fetching image, try to recover
}
}
cursor.close();
return null;
}
/**
* Add a new LoadedImage in the images grid.
*
* @param value
* The image.
*/
@Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
/**
* Set the visibility of the progress bar to false.
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Adapter for our image files.
*
* @author Mihai Fonoage
*
*/
class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
public ImageAdapter(Context context) {
mContext = context;
}
public void addPhoto(LoadedImage photo) {
photos.add(photo);
}
public int getCount() {
return photos.size();
}
public Object getItem(int position) {
return photos.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageBitmap(photos.get(position).getBitmap());
return imageView;
}
}
/**
* A LoadedImage contains the Bitmap loaded for the image.
*/
private static class LoadedImage {
Bitmap mBitmap;
LoadedImage(Bitmap bitmap) {
mBitmap = bitmap;
}
public Bitmap getBitmap() {
return mBitmap;
}
}
/**
* When an image is clicked, load that image as a puzzle.
*/
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int columnIndex = 0;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection,
null, null, null);
if (cursor != null) {
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
String imagePath = cursor.getString(columnIndex);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(bitmap,
parent.getWidth(), parent.getHeight(), true);
bitmap.recycle();
// Display bitmap (useThisBitmap)
} catch (Exception e) {
// Try to recover
} finally {
try {
if (bis != null) {
bis.close();
}
if (is != null) {
is.close();
}
cursor.close();
projection = null;
} catch (Exception e) {
}
}
}
}
}
public class MainActivity extends Activity {
private ListView lv;
private String path = "/mnt/sdcard/pingziyi/";
private HashMap<String, Object> map = new HashMap<String, Object>();
private List<HashMap<String, Object>> Map = new ArrayList<HashMap<String, Object>>();
private MyAdapter adapter;
private final String IMAGE = "image";
private final String NAME = "name";
private final String SIZE = "size";
private final String DATE = "date";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
getDate(path);
adapter = new MyAdapter(MainActivity.this);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private List<HashMap<String, Object>> getDate(String path) {
Map = new ArrayList<HashMap<String, Object>>();
File file = new File(path);
String[] filepath = file.list();
if (checkImage() == true) {
for (String str : filepath) {
map = new HashMap<String, Object>();
String filename = str;
System.out.println("filename-:" + filename);
System.out.println("filename--:" + path + filename);
Bitmap bm = ImageCommon.getFitSizePicture(path + filename);
map.put(IMAGE, bm);
map.put(NAME, filename);
map.put(SIZE, file.length());
map.put(DATE, file.lastModified());
Map.add(map);
// handler.obtainMessage(1, null).sendToTarget();
}
}
return Map;
}
private boolean checkImage() {
File allfile = new File(path);
File[] files = allfile.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("file[iname]" + files[i].getName());
if (files[i].getName().endsWith("jpg") && files[i].isFile()
|| files[i].getName().endsWith("png") && files[i].isFile()) {
System.out.println("file[iname]" + files[i].getName());
return true;
}
return true;
}
return false;
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
adapter = new MyAdapter(MainActivity.this);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return getDate(path).size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.share_content, null);
holder = new ViewHolder();
holder.img = (ImageView) convertView.findViewById(R.id.photo);
holder.name = (TextView) convertView
.findViewById(R.id.photo_name);
holder.size = (TextView) convertView
.findViewById(R.id.photo_size);
holder.date = (TextView) convertView
.findViewById(R.id.photo_time);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.img.setImageBitmap((Bitmap) getDate(path).get(position).get(
IMAGE));
holder.name.setText(getDate(path).get(position).get(NAME)
.toString());
holder.size.setText(getDate(path).get(position).get(SIZE)
.toString());
holder.date.setText(getDate(path).get(position).get(DATE)
.toString());
return convertView;
}
public final class ViewHolder {
public ImageView img;
public TextView name;
public TextView size;
public TextView date;
}
}
}
Cursor cursor = MainActivity.this.getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, null,
"bucket_display_name in ('pingziyi')", null, null);
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
@Override
protected Object doInBackground(Object... params) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
// String[] projection = { MediaStore.Images.Thumbnails._ID };
Cursor cursor = MainActivity.this.getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, null,
"bucket_display_name in ('pingziyi')", null, null);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int size = cursor.getCount();
if (size == 0) {
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
cursor.close();
return null;
}
@Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
@Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
@Override
protected Object doInBackground(Object... params) {
// setProgressBarIndeterminateVisibility(true);
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
Cursor cursor = context.getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, null,
"bucket_display_name in ('pingziyi')",
null, null);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int size = cursor.getCount();
if (size == 0) {
// No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, ""
+ imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
// Error fetching image, try to recover
}
}
cursor.close();
return null;
}
@Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
@Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
private String path = "content://main.images/";
private static final String AUTHORTY = "mnt/sdcard/pingziyi/";
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
@Override
protected Object doInBackground(Object... params) {
// setProgressBarIndeterminateVisibility(true);
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
Uri mUri = Uri.parse(path+AUTHORTY);
// Set up an array of the Thumbnail Image ID column we want
String[] projection = { MediaStore.Images.Thumbnails._ID };
Cursor cursor = managedQuery(mUri, projection, null,
null, null);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int size = cursor.getCount();
// If size is 0, there are no images on the SD Card.
if (size == 0) {
// No Images available, post some message to the user
}
int imageID = 0;
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
imageID = cursor.getInt(columnIndex);
uri = Uri.withAppendedPath(mUri, "" + imageID);
try {
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(mUri));
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
// Error fetching image, try to recover
}
}
cursor.close();
return null;
}
@Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
@Override
protected void onPostExecute(Object result) {
setProgressBarIndeterminateVisibility(false);
}
}
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);