从Sd卡显示图像,但在android中花时间

时间:2015-10-17 06:36:05

标签: android

您好,在下面我显示来自sdcard.sdcard的图片意味着存储到本地。但是当图像显示时它显示了一些黑色的图像。

希望用黑色屏幕显示流畅的预览。我无法找出问题。任何人都可以帮助我。

的java

public class ImageGallery extends Activity {

    Bundle bundle;
    String catid, temp, responseJson;
    JSONObject json;
    ImageView imageViewPager;
    // for parsing
    JSONObject o1, o2;
    JSONArray a1, a2;
    int k;
    Boolean toggleTopBar;
    ArrayList<String> imageThumbnails;
    ArrayList<String> imageFull;
    public static int imagePosition=0;
    SubsamplingScaleImageView imageView, imageViewPreview, fullImage ;
    ImageView thumb1,  back;
    private  LinearLayout thumb2;
    RelativeLayout topLayout, stripeView;
    RelativeLayout thumbnailButtons;
    FrameLayout gridFrame;

    //SharedPreferences data
    SharedPreferences s1;
    SharedPreferences.Editor editor;

    int swipeCounter;
    ParsingForFinalImages parsingObject;
int position_grid;
    SharedPreferences p;

    Bitmap bm;
    int numOfImagesInsidee;
    LinearLayout backLinLayout;
    public static boolean isThumb2=false;
    public static boolean isThumb1=false;

public static ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_gallery);
        //isThumb2=false;
        toggleTopBar = false;
        //position_grid=getIntent().getExtras().getInt("position");


        thumbnailButtons = (RelativeLayout)findViewById(R.id.thumbnailButtons);
        topLayout = (RelativeLayout)findViewById(R.id.topLayout);
        //fullImage = (SubsamplingScaleImageView)findViewById(R.id.fullimage);

        backLinLayout = (LinearLayout)findViewById(R.id.lin_back);
        backLinLayout.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        Intent io = new Intent(getBaseContext(), MainActivity.class);
                        // clear the previous activity and start a new task
                        // System.gc();
                        // io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(io);
                        finish();

                    }

                });

        ConnectionDetector cd = new ConnectionDetector(getBaseContext());
        Boolean isInternetPresent = cd.isConnectingToInternet();



        thumb1 = (ImageView)findViewById(R.id.thumb1);
        thumb2 = (LinearLayout)findViewById(R.id.thumb2);
        stripeView = (RelativeLayout)findViewById(R.id.stripeView) ;
        gridFrame = (FrameLayout)findViewById(R.id.gridFrame);


        thumb1.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        stripeView.setVisibility(View.GONE);
                        gridFrame.setVisibility(View.VISIBLE);
                        viewPager.setVisibility(View.GONE);
                        //fullImage.setVisibility(View.GONE);
                        thumb1.setClickable(false);
                        isThumb1=true;
isThumb2=false;
                        Log.i("Thumb Position 1",""+ImageGallery.imagePosition);
                        viewPager.removeAllViews();
                        Fragment newFragment = new GridFragment2();
                        FragmentTransaction ft = getFragmentManager().beginTransaction();
                        ft.replace(R.id.gridFrame, newFragment).commit();


                    }

                });
        thumb2.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {


                        // stripeView.setVisibility(View.VISIBLE);
                        stripeView.setVisibility(View.GONE);
                        gridFrame.setVisibility(View.VISIBLE);
                        viewPager.setVisibility(View.GONE);
                       // fullImage.setVisibility(View.GONE);
                        thumb1.setClickable(true);
                        isThumb2=true;
                        isThumb1=false;
                        Log.i("Thumb Position 2",""+ImageGallery.imagePosition);
                        viewPager.removeAllViews();
                        Fragment newFragment = new ImageStripeFragment();
                        FragmentTransaction ft = getFragmentManager().beginTransaction();
                        ft.replace(R.id.gridFrame, newFragment).commit();

                    }
                });




        // allow networking on main thread
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        /*bundle = getIntent().getExtras();
        catid = bundle.getString("catid");*/
        // Toast.makeText(getBaseContext(), catid, Toast.LENGTH_LONG).show();


        // making json using the catalogue id we got

        p = getSharedPreferences("gridData", Context.MODE_APPEND);
        catid = p.getString("SelectedCatalogueIdFromGrid1", "");
        int clickedListPos = p.getInt("clickedPosition", 0);



        imageViewPreview = (SubsamplingScaleImageView)findViewById(R.id.preview);
        imageThumbnails = new ArrayList<String>();
        imageFull = new ArrayList<String>();
        s1 = this.getSharedPreferences("data", Context.MODE_APPEND);
        editor = s1.edit();


        Log.d("catidfnl", catid);
        numOfImagesInsidee = p.getInt("numberOfItemsSelectedFromGrid1", 0);

        Log.d("blingbling2", String.valueOf(numOfImagesInsidee));

        // adding downloaded images to arraylist
        for(int m=0;m<numOfImagesInsidee;m++){
            imageThumbnails.add(Environment.getExternalStorageDirectory()+"/"+"thumbImage" + catid + m+".png");
            imageFull.add(Environment.getExternalStorageDirectory()+"/"+"fullImage" + catid + m+".png");


            // imageFull.add("file://" + Environment.getExternalStorageDirectory() + "/" + "fullImage32.png");

        }

        viewPager = (ViewPager) findViewById(R.id.pager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);


        // SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);













        // code to display image in a horizontal strip starts here
        LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
        for (int i = 0; i < imageThumbnails.size(); i++) {
            imageView = new SubsamplingScaleImageView(this);
            imageView.setId(i);

            imageView.setPadding(2, 2, 2, 2);

            // Picasso.with(this).load("file://"+imageThumbnails.get(i)).into(imageView);

            // imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.addView(imageView);

            ViewGroup.LayoutParams params = imageView.getLayoutParams();
            params.width = 200;
            params.height = 200;
            imageView.setLayoutParams(params);

            imageView.setZoomEnabled(false);
            imageView.setDoubleTapZoomScale(0);

            imageView.setImage(ImageSource.uri(imageThumbnails.get(0)));

            imageView.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {



                            imageView.setZoomEnabled(false);
                            imageViewPreview.setImage(ImageSource.uri(imageFull.get(view.getId())));
                            imageView.recycle();
                            imageViewPreview.recycle();

                        }
                    });
        }
        // code to display image in a horizontal strip ends here

        imageViewPreview.setZoomEnabled(false);

        /*imageViewPreview.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        imageViewPreview.setZoomEnabled(false);
                        stripeView.setVisibility(View.GONE);
                        gridFrame.setVisibility(View.GONE);
                        viewPager.setVisibility(View.VISIBLE);

                    }
                });*/

        imageViewPreview.setOnClickListener(new DoubleClickListener() {

            @Override
            public void onSingleClick(View v) {
                 Log.d("yo click", "single");
            }

            @Override
            public void onDoubleClick(View v) {
                Log.d("yo click", "double");
            }
        });


    }


    public abstract class DoubleClickListener implements View.OnClickListener {

        private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

        long lastClickTime = 0;

        @Override
        public void onClick(View v) {
            long clickTime = System.currentTimeMillis();
            if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
                onDoubleClick(v);
            } else {
                onSingleClick(v);
            }
            lastClickTime = clickTime;
        }

        public abstract void onSingleClick(View v);
        public abstract void onDoubleClick(View v);
    }




//    @Override
//    public void onBackPressed() {
//        Intent io = new Intent(getBaseContext(), MainActivity.class);
//        // clear the previous activity and start a new task
//        super.onBackPressed();
//        finish();
//        // System.gc();
//        // io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//        startActivity(io);
//    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_image_gallery, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class ImagePagerAdapter extends PagerAdapter {
       /* private int[] mImages = new int[] {
                R.drawable.scroll3,
                R.drawable.scroll1,
                R.drawable.scroll2,
                R.drawable.scroll4

        };*/
        /* private String[] description=new String[]
                 {
                    "One","two","three","four"
                 };
 */
        @Override
        public int getCount() {
            Log.i("Image List Size", "" + imageFull.size());
            return imageFull.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((SubsamplingScaleImageView) object);
        }




        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Context context = ImageGallery.this;

            SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);

            // for placeholder
            // fullImage.setImage(ImageSource.resource(R.drawable.tan2x));

            if(!GridFragment2.isSelectedGrid2&&!ImageStripeFragment.isImageStripe) {
            imagePosition = position;
            fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));

        }
       /* else if(!ImageStripeFragment.isImageStripe)
        {
            imagePosition = position;
            fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
        }
        else if(ImageStripeFragment.isImageStripe)
        {
            position=imagePosition;
            viewPager.setCurrentItem(imagePosition);
            fullImage.setImage(ImageSource.uri(imageFull.get(position)));
        }*/
            else
        {
            position=imagePosition;
            viewPager.setCurrentItem(imagePosition);
            fullImage.setImage(ImageSource.uri(imageFull.get(position)));


            //viewPager.removeAllViews();

        }

          // ImageView  imageViewPager = new ImageView(context);
           // ImageView imageViewPager = new ImageView(getApplicationContext());
           // SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);

            GridFragment2.isSelectedGrid2=false;
            ImageStripeFragment.isImageStripe=false;

           // Log.i("Image Resource", "" + ImageSource.uri(imageFull.get(position)));
        // imageViewPager.setImageBitmap(BitmapFactory.decodeFile(imageFull.get(position)));
       // imageViewPager.setImageBitmap(myBitmap);

            // fullImage.setImage(ImageSource.bitmap(bmImg));

            //imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
          /*int padding = context.getResources().getDimensionPixelSize(
              R.dimen.padding_medium);
          imageView.setPadding(padding, padding, padding, padding);*/
            /*imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageResource(Integer.parseInt(imageFull.get(position)));

            if(position==3)
            {

            }*/
            //  Log.i("Image Position",""+position);
          /*text.setText(description[position]);
          Log.i("Text Position",""+position);*/
          /*switch(position)
          {

          case 0:
              String pos=String.valueOf(position);
            text.setText(pos);

              break;
          case 1:
              String pos1=String.valueOf(position);
              text.setText(pos1);
              break;
          case 2:
              String pos2=String.valueOf(position);
              text.setText(pos2);
              break;
          case 3:
              String pos3=String.valueOf(position);
              text.setText(pos3);
              break;
          }*/



            fullImage.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            if (toggleTopBar == false) {
                                // thumbnailButtons.setVisibility(View.GONE);
                                thumbnailButtons.animate()
                                        .translationY(-2000)
                                        .setDuration(1000)
                                        .start();
                                toggleTopBar = true;
                            } else if (toggleTopBar == true) {
                                // thumbnailButtons.setVisibility(View.VISIBLE);
                                thumbnailButtons.animate()
                                        .translationY(0)
                                        .setDuration(1000)
                                        .start();
                                toggleTopBar = false;
                            }

                        }
                    });
            ((ViewPager) container).addView(fullImage, 0);

            return fullImage;
        }

       @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((SubsamplingScaleImageView) object);
        }
       /* @Override
        public void destroyItem(View collection, int position, Object o) {
            Log.d("DESTROY", "destroying view at position " + position);
            View view = (View) o;
            ((ViewPager) collection).removeView(view);
            view = null;
        }*/


    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        super.onBackPressed();

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();

    }

1 个答案:

答案 0 :(得分:0)

使用此ImageLoader类

 public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
        .synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();// handler to display images in UI thread
int stub_id;
int widht;

public ImageLoader(Context context, int stub_idx) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);

    stub_id = stub_idx;
}

public void DisplayImage(String url, ImageView imageView, int widht, ProgressBar bar) {
    this.widht = widht;

    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
    {
        bar.setVisibility(View.GONE);
        imageView.setImageBitmap(bitmap);
    }
    else {
        queuePhoto(url, imageView, widht, bar);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView, int w, ProgressBar bar) {
    PhotoToLoad p = new PhotoToLoad(url, imageView, bar);
    executorService.submit(new PhotosLoader(p, w));
}

public  Bitmap getBitmap(String url, int w) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f, w);
    if (b != null)
        return b;

    // from web
    try {
        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl
                .openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        conn.disconnect();
        bitmap = decodeFile(f, w);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f, int w) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        FileInputStream stream1 = new FileInputStream(f);
        BitmapFactory.decodeStream(stream1, null, o);
        stream1.close();
        // Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE = w;
        System.out.println("screen wdth " + widht);
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        System.out.println("image with === " + width_tmp);
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
                    || height_tmp / 2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        FileInputStream stream2 = new FileInputStream(f);
        Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
        stream2.close();
        return bitmap;
    }
    catch (FileNotFoundException e) {
        Log.e(e.getMessage(), "");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;
    public ProgressBar bar;

    public PhotoToLoad(String u, ImageView i, ProgressBar progressBar) {
        url = u;
        imageView = i;
        bar = progressBar;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;
    int w;

    PhotosLoader(PhotoToLoad photoToLoad, int w) {
        this.photoToLoad = photoToLoad;
        this.w = w;

    }

    @Override
    public void run() {
        try {
            if (imageViewReused(photoToLoad))
                return;
            Bitmap bmp = getBitmap(photoToLoad.url, w);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            handler.post(bd);
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag = imageViews.get(photoToLoad.imageView);
    return tag == null || !tag.equals(photoToLoad.url);
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
        bitmap = b;
        photoToLoad = p;
    }

    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        if (bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);

        photoToLoad.bar.setVisibility(View.GONE);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

然后为文件缓存创建新类

public class FileCache {

private File cacheDir;

public FileCache(Context context) {
    // Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED))
        cacheDir = new File(
                android.os.Environment.getExternalStorageDirectory(),
                "LazyList");
    else
        //cacheDir = url.getCacheDir();
    if (!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url) {
    // I identify images by hashcode. Not a perfect solution, good for the
    // demo.
    String filename = String.valueOf(url.hashCode());
    // Another possible solution (thanks to grantland)
    // String filename = URLEncoder.encode(url);
    File f = new File(cacheDir, filename);
    return f;

}

public void clear() {
    File[] files = cacheDir.listFiles();
    if (files == null)
        return;
    for (File f : files)
        f.delete();
}

}

然后最后制作内存缓存类,全部三个单独的类

public class MemoryCache {

private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache=Collections.synchronizedMap(
        new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes

public MemoryCache(){
    //use 25% of available heap size
    setLimit(Runtime.getRuntime().maxMemory()/4);
}

public void setLimit(long new_limit){
    limit=new_limit;
    Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}

public Bitmap get(String id){
    try{
        if(!cache.containsKey(id))
            return null;
        //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
      return cache.get(id);
    }catch(NullPointerException ex){
        ex.printStackTrace();
        return null;
    }
}

public void put(String id, Bitmap bitmap){
    try{
        if(cache.containsKey(id))
            size-=getSizeInBytes(cache.get(id));
        cache.put(id, bitmap);
        size+=getSizeInBytes(bitmap);
        checkSize();
    }catch(Throwable th){
        th.printStackTrace();
    }
}

private void checkSize() {
    Log.i(TAG, "cache size="+size+" length="+cache.size());
    if(size>limit){
        Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
        while(iter.hasNext()){
            Entry<String, Bitmap> entry=iter.next();
            size-=getSizeInBytes(entry.getValue());
            iter.remove();
            if(size<=limit)
                break;
        }
        Log.i(TAG, "Clean cache. New size "+cache.size());
    }
}

public void clear() {
    try{
        //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
        cache.clear();
        size=0;
    }catch(NullPointerException ex){
        ex.printStackTrace();
    }
}

long getSizeInBytes(Bitmap bitmap) {
    if(bitmap==null)
        return 0;
    return bitmap.getRowBytes() * bitmap.getHeight();
}