无法从ViewPager的图像列表中下载和共享第一张图像[奇怪的问题]

时间:2019-05-16 10:34:13

标签: android android-asynctask android-viewpager

你好,我遇到了奇怪的问题。我正在制作一个画廊应用程序,该软件使用齐射下载图像并将其显示在Viewpager中,称为SlideActivity,一切正常。问题:-当我尝试从Viewpager下载和共享第一张图片时,什么都没有发生,但是当滑动并转到第二张图片共享并下载到第二张图片时,当我滑动回到第一张图片时,现在共享并下载作品了吗?这是我到目前为止所做的,希望对此问题有所建议。谢谢您!

SlideActivity.Java

public class TrendingSlideActivity extends AppCompatActivity {
    private static final String URL = "API";

    private ViewPager viewPager;
    private Context context = TrendingSlideActivity.this;
    private TrendingViewPagerAdapter adapter;
    private int position;
    private int currentImage;
    private List<Trending> data;
    private ImageView shareIcon, shareImage, downloadImage;
    private int mAdCounter = 0;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trending_slide_activity);

            viewPager = findViewById(R.id.viewPager);
            ProgressBar progressBar = findViewById(R.id.progress);
            shareIcon = findViewById(R.id.shareviewpager);
            downloadImage = findViewById(R.id.iv_download_slide);

            //final String fileName = getIntent().getStringExtra("filename");
            position = getIntent().getIntExtra("pos", 0);

            progressBar.setVisibility(View.VISIBLE);

            StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("CODE", response);
                    GsonBuilder gsonBuilder = new GsonBuilder();
                    Gson gson = gsonBuilder.create();
                    TrendingData users = gson.fromJson(response, TrendingData.class);
                    data = users.getData();
                    adapter = new TrendingViewPagerAdapter(context, data);
                    viewPager.setAdapter(adapter);
                    viewPager.setOffscreenPageLimit(1);
                    viewPager.setCurrentItem(position);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(TrendingSlideActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
                }
            });

            RequestQueue queue = Volley.newRequestQueue(this);
            queue.add(request);

            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int i, float v, int i1) {
                }

                @Override
                public void onPageSelected(int i) {

                    currentImage = viewPager.getCurrentItem();
                    final String fileName1 = data.get(currentImage).getFileName();
                    Toast.makeText(TrendingSlideActivity.this, "===========" + fileName1, Toast.LENGTH_SHORT).show();


                    final String url2 = "API" + fileName1;

                    new LoadImage(TrendingSlideActivity.this).execute(url2);

                    shareIcon.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onShareItem(shareImage);
                        }

                    });

                    downloadImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            saveImageToGallery(shareImage);
                        }
                    });

                }

                @Override
                public void onPageScrollStateChanged(int i) {

                }
            });

    }

    private static class LoadImage extends AsyncTask<String, Integer, Drawable> {

        private WeakReference<TrendingSlideActivity> activityWeakReference;

        LoadImage(TrendingSlideActivity context) {
            activityWeakReference = new WeakReference<>(context);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Drawable doInBackground(String... strings) {

            Bitmap bmp = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
                connection.connect();
                InputStream input = connection.getInputStream();
                bmp = BitmapFactory.decodeStream(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new BitmapDrawable(bmp);
        }

        @Override
        protected void onPostExecute(Drawable result) {

            TrendingSlideActivity activity = activityWeakReference.get();
            if (activity == null) return;

            activity.shareImage = new ImageView(activity);
            //Add image to ImageView
            activity.shareImage.setImageDrawable(result);

        }

    }


    public void onShareItem(View v) {
        // Get access to bitmap image from view
        // Get access to the URI for the bitmap
        Uri bmpUri = getLocalBitmapUri((ImageView) v);
        if (bmpUri != null) {
            // Construct a ShareIntent  with link to image
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/*");
            // Launch sharing dialog for image
            context.startActivity(Intent.createChooser(shareIntent, "Share TrendingData"));
        } else {
            // ...sharing failed, handle error
        }
    }

    public Uri getLocalBitmapUri(ImageView imageView) {
        // Extract Bitmap from ImageView drawable
        Drawable drawable = imageView.getDrawable();
        Bitmap bmp;
        if (drawable instanceof BitmapDrawable) {
            bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        } else {
            return null;
        }
        // Store image to default external storage directory
        Uri bmpUri = null;
        try {
            // Use methods on Context to access package-specific directories on external storage.
            // This way, you don't need to request external read/write permission.
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
            // **Warning:** This will fail for API >= 24, use a FileProvider as shown below instead.
            bmpUri = Uri.fromFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }

    public boolean isStoragePermissionGranted() {
        String TAG = "Storage Permission";
        if (Build.VERSION.SDK_INT >= 23) {
            if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "Permission is granted");
                return true;
            } else {
                Log.i(TAG, "Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.i(TAG, "Permission is granted");
            return true;
        }
    }

    public void saveImageToGallery(ImageView iv) {
//        //to get the image from the ImageView (say iv)
//        BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
//        Bitmap bitmap = draw.getBitmap();
        if (iv != null) {
            Drawable drawable = iv.getDrawable();

            Bitmap bmp = null;
            if (drawable instanceof BitmapDrawable) {
                bmp = ((BitmapDrawable) iv.getDrawable()).getBitmap();
            } else {
            }

            FileOutputStream outStream = null;

            String sdCard = Environment.getExternalStorageDirectory().toString();
            if (isStoragePermissionGranted()) {
                File dir = new File(sdCard, "/GalleryApp");
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                try {
                    String fileName = String.format("%d.jpg", System.currentTimeMillis());
                    File outFile = new File(dir, fileName);

                    outStream = new FileOutputStream(outFile);
                    assert bmp != null;
                    bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                    Toast.makeText(TrendingSlideActivity.this, "Saved", Toast.LENGTH_SHORT).show();
                    Log.i("TAAAAAAAAAAAAG", "onPictureTaken - wrote to " + outFile.getAbsolutePath());

                    String filePath = outFile.getPath();

                    MediaScannerConnection.scanFile(this,
                            new String[]{filePath}, null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                public void onScanCompleted(String path, Uri uri) {
                                    Log.i("ExternalStorage", "Scanned " + path + ":");
                                    Log.i("ExternalStorage", "-> uri=" + uri);
                                }
                            });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else {
            Toast.makeText(TrendingSlideActivity.this,"Please Wait Image is Loading...",Toast.LENGTH_SHORT).show();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

更新后的答案:

之所以不起作用,是因为您在onPageSelected()内设置了图像视图,并且第一页未调用该方法,而是在刷卡后立即激活了该方法。

解决方案是将整个代码从onPageSelected()移动到函数selectImage(int position)中,并在onPageSelected()内部调用该函数,如下所示: selectImage(i)

这是上面代码的改进版本,其作用与以前相同,但是现在可以通过调用以下操作为第一个视图设置默认状态: selectImage(0)之后的viewPager.setCurrentItem(position)