如何在android中顺利显示SD卡中的图像

时间:2015-10-17 12:27:10

标签: java android sd-card

以下代码是从显示为SD卡的数据库中下载图像。预览时显示图像。第一张图片显示得很完美,但是从下一张图片开始,它显示为空白并从SD卡中加载图像,但是从SD卡开始,它没有直接下载图像显示图像。

的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;
    public ImageLoader imageLoader;
    //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;

           // ImageLoader loader = new ImageLoader(context, 1);
           // loader.DisplayImage(ImageSource.uri(imageFull.get(imagePosition)),imageView,imagePosition,new ProgressDialog(context));
            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)

这将是您解决方案的最佳方法,请尝试使用Universal Image Loader。

功能

  • 多线程图像加载(异步或同步)

  • ImageLoader配置的广泛定制(线程执行器,下载器,解码器,内存和磁盘缓存,显示图像选项等)

  • 每个显示图像调用的许多自定义选项(存根图像,缓存切换,解码选项,位图处理和显示等)

  • 内存和/或磁盘上的图像缓存(设备的文件系统或SD卡) 听力加载过程(包括下载进度)

在此处查找链接: https://github.com/nostra13/Android-Universal-Image-Loader