我想在GridView
中使用真实路径和缩略图图像显示设备中显示的所有图像。我的问题是"我得到设备中存在的所有图像,但没有得到真正的图像路径"。我的代码如下。我想要下面的图像名称而不是缩略图路径。
**button.java**
public class button extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1= (Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i1= new Intent(button.this, MainActivity.class);
startActivity(i1);
}
});
}
**MainActivity.java**
public class MainActivity extends Activity implements OnItemClickListener {
/**
* Grid view holding the images.
*/
private GridView sdcardImages;
/**
* Image adapter for the grid view.
*/
private ImageAdapter imageAdapter;
/**
* Display used for getting the width of the screen.
*/
private Display display;
public Object data = null;
/**
* Creates the content view, sets up the grid, the adapter, and the click
* listener.
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Request progress bar
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.sdcard);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
setupViews();
setProgressBarIndeterminateVisibility(true);
loadImages();
}
/**
* Free up bitmap related resources.
*/
protected void onDestroy() {
super.onDestroy();
final GridView 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 = (GridView) findViewById(R.id.sdcard);
sdcardImages.setNumColumns(display.getWidth() / 95);
sdcardImages.setClipToPadding(false);
sdcardImages.setOnItemClickListener(MainActivity.this);
imageAdapter = new ImageAdapter(getApplicationContext());
sdcardImages.setAdapter(imageAdapter);
}
/**
* Load images.
*/
private void loadImages() {
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 GridView 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(), null, null);
}
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,
MediaStore.Images.Media.DATA };
// Create the cursor pointing to the SDCard
Cursor cursor = getContentResolver().query(
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 image_column_index_next = cursor
.getColumnIndex(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, 100, 100,
true);
bitmap.recycle();
if (newBitmap != null) {
String filename = cursor
.getString(image_column_index_next);
File f = new File(filename);
publishProgress(new LoadedImage(newBitmap,
f.getName(), f.getName()));
}
}
} 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 LayoutInflater mInflater;
public ImageAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
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) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.mInflater.inflate(R.layout.image_click2,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
holder.textview = (TextView) convertView
.findViewById(R.id.thumbText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
LoadedImage item = photos.get(position);
holder.textview.setId(position);
holder.imageview.setId(position);
holder.imageview.setImageBitmap(item.mBitmap);
holder.textview.setText(item.mName);
;
return convertView;
}
}
/**
* A LoadedImage contains the Bitmap loaded for the image.
*/
private static class LoadedImage {
Bitmap mBitmap;
String mName;
String mPath;
LoadedImage(Bitmap bitmap, String Name, String Path) {
mBitmap = bitmap;
mName = Name;
}
public Bitmap getBitmap() {
return mBitmap;
}
public String getName() {
return mName;
}
public String getPAth() {
return mPath;
}
}
/**
* 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 = getContentResolver().query(
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) {
}
}
}
}
}
**ViewHolder.java**
class ViewHolder {
ImageView imageview;
TextView textview;
}
**activity_main.xml**
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.test.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginLeft="33dp"
android:layout_marginTop="70dp"
android:layout_toRightOf="@+id/textView1"
android:text="Button" />
</RelativeLayout>
**image_click2.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="8" >
<ImageView
android:id="@+id/thumbImage"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="4"
android:src="@drawable/loading_back" />
<TextView
android:id="@+id/thumbText"
android:layout_width="65dp"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_margin="1dp"
android:layout_weight="3.5"
android:maxLength="20"
android:maxLines="2"
android:text="This is an image"
android:textColor="#000000"
android:textSize="8sp" />
</LinearLayout>
**sdcard.xml**
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<GridView
android:id="@+id/sdcard"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />