将图片从手机图库加载到android中的应用程序库中

时间:2014-09-01 10:16:41

标签: android sd-card image-gallery

按钮单击时调用以下方法。活动必须在创建时加载SD卡图像。但是当我运行它时会给出零点异常。即使我使用INTERNAL_CONTENT_URI,该应用程序显示为空白。请帮帮我。

package com.example.sampleapp;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.sampleapp.MultiPhotoSelectActivity.Album;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions.Builder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;

public class MultiPhotoSelectActivity extends BaseActivity {
     private AlbumAdapter albumAdapter;
      Button done;
      private GridView gridView;
      private ImageAdapter imageAdapter;
      private ArrayList<String> imageUrls;
      private boolean isAlbumView;
      private ArrayList mAlbumsList;
      private DisplayImageOptions options;
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_photo_select);
        fillAlbums();
        this.options = new DisplayImageOptions.Builder().showStubImage(R.drawable.ic_gallery).showImageForEmptyUri(R.drawable.ic_gallery).cacheInMemory().cacheOnDisc().build();
        this.albumAdapter = new AlbumAdapter(this.mAlbumsList);
        this.gridView = ((GridView)findViewById(R.id.gridview));
        this.done = ((Button)findViewById(R.id.done));
        this.gridView.setAdapter(this.albumAdapter);
        this.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
          public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
          {
            if (MultiPhotoSelectActivity.this.isAlbumView)
            {
              MultiPhotoSelectActivity.this.isAlbumView = false;
              MultiPhotoSelectActivity.this.fillGallery(((MultiPhotoSelectActivity.Album)MultiPhotoSelectActivity.this.mAlbumsList.get(paramAnonymousInt)).albumId);
            }
          }
        });
        this.done.setOnClickListener(new View.OnClickListener()
        {
          public void onClick(View paramAnonymousView)
          {
            ArrayList<String> localArrayList = MultiPhotoSelectActivity.this.imageAdapter.getCheckedItems();
            Intent localIntent = new Intent(MultiPhotoSelectActivity.this, CreateSlideActivity.class);
            localIntent.putExtra("list", localArrayList);
            System.out.println(" " + localArrayList);
            MultiPhotoSelectActivity.this.setResult(-1, localIntent);
            MultiPhotoSelectActivity.this.finish();
          }
        });
    }


    private void fillAlbums()
      {
        this.isAlbumView = true;
        this.mAlbumsList = new ArrayList();
        String[] arrayOfString = { "_data", "_id", "bucket_display_name", "bucket_id" };
        Cursor localCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOfString, null, null, null);
        HashSet<String> localHashSet = new HashSet<String>();
        for (int i = 0;; i++)
        {
          if (i >= localCursor.getCount()) {
            return;
          }
          Album localAlbum = new Album();
          localCursor.moveToPosition(i);
          int j = localCursor.getColumnIndex("_data");
          int k = localCursor.getColumnIndex("bucket_display_name");
          int m = localCursor.getColumnIndex("bucket_id");
          localCursor.getColumnIndex("_id");
          String str = localCursor.getString(k);
          localAlbum.setAlbumName(str);
          localAlbum.setImageUrl(localCursor.getString(j));
          localAlbum.albumId = localCursor.getString(m);
          if (localHashSet.add(str)) {
            this.mAlbumsList.add(localAlbum);
          }
          System.out.println("=====> BUCKET_DISPLAY_NAME => " + localCursor.getString(localCursor.getColumnIndex("bucket_display_name")));
        }
      }
     private void fillGallery(String paramString)
      {
        String[] arrayOfString = { "_data", "_id" };
        //String path= Environment.getExternalStorageDirectory();
        Cursor localCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOfString, "bucket_id=?", new String[] { paramString }, "datetaken DESC");
        this.imageUrls = new ArrayList<String>();
        for (int i = 0;; i++)
        {
          if (i >= localCursor.getCount())
          {
            this.imageAdapter = new ImageAdapter(this.imageUrls);
            this.gridView.setAdapter(this.imageAdapter);
            return;
          }
          localCursor.moveToPosition(i);
          int j = localCursor.getColumnIndex("_data");
          this.imageUrls.add(localCursor.getString(j));
        }
      }
      public void onBackPressed()
      {

        if (this.isAlbumView)
        {
          super.onBackPressed();
          return;
        }
        this.isAlbumView = true;
        this.gridView.setAdapter(this.albumAdapter);
      }
      public class Album
      {
        public String albumId;
        private String albumName;
        private String imageUrl;

        public Album() {
            super();
        }

        public String getAlbumName()
        {
          return this.albumName;
        }

        public String getImageUrl()
        {
          return this.imageUrl;
        }

        public void setAlbumName(String paramString)
        {
          this.albumName = paramString;
        }

        public void setImageUrl(String paramString)
        {
          this.imageUrl = paramString;
        }
      }

      public class AlbumAdapter
        extends BaseAdapter
      {
        Context mContext;
        ArrayList<MultiPhotoSelectActivity.Album> mList;

        public AlbumAdapter(ArrayList mAlbumsList)
        {
         // Object localObject;
          this.mList = mAlbumsList;
        }

        public int getCount()
        {
          return this.mList.size();
        }

        public MultiPhotoSelectActivity.Album getItem(int paramInt)
        {
          return (MultiPhotoSelectActivity.Album)this.mList.get(paramInt);
        }

        public long getItemId(int paramInt)
        {
          return paramInt;
        }

        public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
        {
          if (paramView == null) {
            paramView = ((LayoutInflater)MultiPhotoSelectActivity.this.getSystemService("layout_inflater")).inflate(R.layout.row_album_item, null);
          }
          final ImageView localImageView = (ImageView)paramView.findViewById(R.id.albumview);
          TextView localTextView = (TextView)paramView.findViewById(R.id.albumName);
          MultiPhotoSelectActivity.this.imageLoader.displayImage("file://" + ((MultiPhotoSelectActivity.Album)this.mList.get(paramInt)).imageUrl, localImageView, MultiPhotoSelectActivity.this.options, new SimpleImageLoadingListener()
          {

            public void onLoadingComplete(Bitmap paramAnonymousBitmap)
            {
              Animation localAnimation = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this, R.anim.fade_in);
              localImageView.setAnimation(localAnimation);
              localAnimation.start();
            }
          });
          localTextView.setText(((MultiPhotoSelectActivity.Album)this.mList.get(paramInt)).albumName);
          return paramView;
        }
      }

      class ImageAdapter
        extends BaseAdapter
      {
        CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener()
        {
          public void onCheckedChanged(CompoundButton paramAnonymousCompoundButton, boolean paramAnonymousBoolean)
          {
            MultiPhotoSelectActivity.ImageAdapter.this.mSparseBooleanArray.put(((Integer)paramAnonymousCompoundButton.getTag()).intValue(), paramAnonymousBoolean);
          }
        };
        Context mContext;
        ArrayList<String> mList;
        SparseBooleanArray mSparseBooleanArray = new SparseBooleanArray();

        public ImageAdapter(ArrayList<String> imageUrls)
        {
         // Object localObject;
          this.mList = imageUrls;
        }

        public ArrayList<String> getCheckedItems()
        {
          ArrayList<String> localArrayList = new ArrayList<String>();
          int i = 0;
          if (i >= this.mList.size()) {
            return localArrayList;
          }
          if (!this.mSparseBooleanArray.get(i)) {}
          for (;;)
          {
            i++;
            localArrayList.add((String)this.mList.get(i));
          }
        }

        public int getCount()
        {
          return MultiPhotoSelectActivity.this.imageUrls.size();
        }

        public Object getItem(int paramInt)
        {
          return null;
        }

        public long getItemId(int paramInt)
        {
          return paramInt;
        }

        public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
        {
          if (paramView == null) {
            paramView = ((LayoutInflater)MultiPhotoSelectActivity.this.getSystemService("layout_inflater")).inflate(R.layout.row_multiphoto_item, null);
          }
          MultiPhotoSelectActivity.this.done.setVisibility(0);
          CheckBox localCheckBox = (CheckBox)paramView.findViewById(R.id.checkBox1);
          final ImageView localImageView = (ImageView)paramView.findViewById(R.id.imageView2);
          MultiPhotoSelectActivity.this.imageLoader.displayImage("file://" + (String)MultiPhotoSelectActivity.this.imageUrls.get(paramInt), localImageView, MultiPhotoSelectActivity.this.options, new SimpleImageLoadingListener()
          {
            @SuppressWarnings("unused")
            public void onLoadingComplete(Bitmap paramAnonymousBitmap)
            {
              Animation localAnimation = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this,R.anim.fade_in );
              localImageView.setAnimation(localAnimation);
              localAnimation.start();
            }
          });
          localCheckBox.setTag(Integer.valueOf(paramInt));
          localCheckBox.setChecked(this.mSparseBooleanArray.get(paramInt));
          localCheckBox.setOnCheckedChangeListener(this.mCheckedChangeListener);
          return paramView;
        }
      }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.multi_photo_select, menu);
        return true;
    }

}

以下是gridview的xml,其中应显示sdcard图像。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:background="@drawable/plainbackground" 
  xmlns:android="http://schemas.android.com/apk/res/android"
  >
    <GridView 
        android:gravity="center" 
        android:id="@+id/gridview" 
        android:scrollbars="vertical" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:horizontalSpacing="4.0dip" 
        android:verticalSpacing="2.0dip" 
        android:stretchMode="columnWidth" 
        android:columnWidth="100.0dip" 
        android:numColumns="auto_fit" 
        android:layout_weight="1.0" />
    <Button 
        android:layout_gravity="center" 
        android:id="@+id/done" 
        android:background="@drawable/done" 
        android:visibility="gone" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" />

</LinearLayout>

以下xml用于sd卡的专辑视图。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:padding="10.0dip" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout 
        android:id="@+id/container" 
        android:background="@drawable/ic_folder" 
        android:padding="2.0dip" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content">
        <ImageView 
            android:id="@+id/albumview" 
            android:background="@drawable/ic_folder" 
            android:layout_width="50.0dip" 
            android:layout_height="50.0dip" 
            android:scaleType="centerCrop" 
            android:layout_centerHorizontal="true" 
            android:layout_centerVertical="true" />
    </RelativeLayout>
    <TextView 
        android:textSize="11.0dip" 
        android:textColor="@android:color/black" 
        android:id="@+id/albumName" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginTop="3.0dip" 
        android:text="Large Text" 
        android:layout_below="@id/container" 
        android:layout_centerHorizontal="true" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

Intent intent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
      startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK){
 Uri targetUri = data.getData();
 textTargetUri.setText(targetUri.toString());
 Bitmap bitmap;
 try {
  bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
  targetImage.setImageBitmap(bitmap);
 } catch (FileNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
}
}