1

In my application I am using a webview to use Facebook. In Facebook page we will find many posts with images. so to download the images from Facebook, I am using longpress method and HitTestResult method for the webview. My long press is working and HitTestResult is having the data where i have longpressed. I am getting Url's(text with https links) properly.

My problem is that if I longpressed on facebook image post(simply on images), i am not getting the images, instead I am getting the url links (like-https://something). how to get access to the images and download them.

Permissions I added in manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

In my activity:

WebSettings settings = ((WebView) findViewById(R.id.webview)).getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setAppCacheEnabled(true);
settings.setLoadWithOverviewMode(true);
webView2.setWebViewClient(new PQClient());
webView2.setWebChromeClient(new PQChromeClient());

and

@Override
protected void onResume() {
    super.onResume();
    final WebView wv = (WebView) findViewById(R.id.webview);
    wv.setOnLongClickListener(new View.OnLongClickListener() {
            public boolean onLongClick(View v) {
                WebView.HitTestResult hitResult = null;
                hitResult = wv.getHitTestResult();
                if (hitResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                        hitResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    try {
                        String imageUrl = hitResult.getExtra();
                        Toast.makeText(SocialMediaActivity.this,imageUrl,Toast.LENGTH_LONG).show();
                        URL url = new URL(imageUrl);
                        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                        urlConnection.setRequestMethod("GET");
                        urlConnection.setDoOutput(true);
                        urlConnection.connect();

                        File sdcard = Environment.getExternalStorageDirectory();
                        File file = new File(sdcard, "filename.ext");

                        FileOutputStream fileOutput = new FileOutputStream(file);
                        InputStream inputStream = urlConnection.getInputStream();

                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;

                        while ((bufferLength = inputStream.read(buffer)) > 0) {
                            fileOutput.write(buffer, 0, bufferLength);
                        }
                        fileOutput.close();

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                return true;
            }
        });
    }

Here, I think the problem is in if condition because where ever i performed longpress, it is not returning the image but giving the url link. If i get the image i can download that to local SD card.

if (hitResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                    hitResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE)

I tried the code with Bitmap also to get the image.

     @Override
protected void onResume() {
    super.onResume();
    final WebView wv = (WebView) findViewById(R.id.webview);
    wv.setOnLongClickListener(new View.OnLongClickListener() {
            public boolean onLongClick(View v) {
                WebView.HitTestResult hitResult = null;
                hitResult = wv.getHitTestResult();
                    try {
                        String imageUrl = hitResult.getExtra();
                        URL url = new URL(imageUrl);
                        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                        Toast.makeText(SocialMediaActivity.this,imageUrl,Toast.LENGTH_LONG).show();
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        image.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

                    //you can create a new file name "test.jpg" in sdcard folder.
                        File f = new File(Environment.getExternalStorageDirectory()
                                + File.separator + "test.jpg");
                        f.createNewFile();
                    //write the bytes in file
                        FileOutputStream fo = new FileOutputStream(f);
                        fo.write(bytes.toByteArray());

                    // remember close de FileOutput
                        fo.close();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                return true;
            }
        });
    }

My application is crashing if i use this code.

Mustansir
  • 2,445
  • 1
  • 21
  • 32
Praveen Kumar
  • 225
  • 5
  • 18
  • You need to use that link and convert it to a bitmap and then save it in your SD card. http://stackoverflow.com/a/11831325/3111083 – Sunil Sunny Aug 18 '16 at 07:06
  • Actually it is not checking the if() condition. I mean the IMAGE_TYPE and SRC_IMAGE_ANCHOR_TYPE. so if i long press the image nothing is happening. – Praveen Kumar Aug 18 '16 at 07:20
  • I tested the application in debug mode, so i came to know that it is not executing the if() condition. But the hitresult is having the url link. – Praveen Kumar Aug 18 '16 at 07:22
  • Of course it will crash because you are doing it on MainThread. http://stackoverflow.com/questions/9671546/asynctask-android-example this should help you to learn about async task. – Sunil Sunny Aug 18 '16 at 09:01

1 Answers1

0

Your problem is unclear. If you can get the url of the image then you can try to download that image.

But you did put the download code in an on click handler. So it will be executed on the main thread. That will cause a NetworkOnMainThreadException clearly visible in the LogCat.

To prevent this you should place the download code in a thread or AsyncTask.

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • yes i am able to get the Url of the image, and i don't know the further steps to do, if the above code is not right..! Can u please guide me to use Asynk Task related to above code. – Praveen Kumar Aug 18 '16 at 08:00
  • Every day you can find examples of using an AsyncTask to download something from web and save to file or something else. Just read some `android` tagged pages here. Or google for it. There is nothing special in your code that it should not work. – greenapps Aug 18 '16 at 08:06
  • I tried to download image from webview using Async task, it is working fine. But i am using facebook in webview. So i have to download images on long press on them from facebook(like posts, profile pics, etc,.. ). When i perform long press on any image, i am getting the url link of that posted image page. How to download image from facebook on longpress on them – Praveen Kumar Aug 19 '16 at 05:55
  • for normal image to download the url link may be like this- http://www.gettyimages.ca/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg. If we are selecting any image from the facebook posts the url link will not be like this – Praveen Kumar Aug 19 '16 at 06:04
  • Unclear what your problem is. First you say that you can download an image fine. For that you needed an url. After long pressing you got an image url. And now you dont know how to download the image? I do not understand that. – greenapps Aug 19 '16 at 06:45
  • its simple, I want to download images which are posted in facebook. where the facebook is opened in webview in my application. – Praveen Kumar Aug 19 '16 at 06:54
  • Yes i know that already. But please react to the point. Your reaction makes no sense. If you can get the url -as you said- than download the image. – greenapps Aug 19 '16 at 06:55
  • ok, when i long press on any image i am getting the url link of that image using HitTestResult, but the image is not downloading. – Praveen Kumar Aug 19 '16 at 06:58
  • i tried to download an image outside of facebook using async task, and it works fine – Praveen Kumar Aug 19 '16 at 07:00
  • If you want help then you should explain why the image not downloads. – greenapps Aug 19 '16 at 07:09
  • Please try to understand patiently. Just concentrate only on Url's. If u want to download image directly from Url, you will find url like this - http://www.freedigitalphotos.net/images/img/homepage/87357.jpg. If you click on any facebook posted image you will get link this - https://www.facebook.com/Interesting2016/photos/a.637169979754423.1073741828.637167476421340/728277977310289/?type=3&theater. – Praveen Kumar Aug 19 '16 at 07:21
  • Please explain what the difference is betwen these urls. You should of course tell that us first. And what the difficulty would be. Inform us about your problem. – greenapps Aug 19 '16 at 07:28
  • @greenapps I have facing the same problem in facebook. Perhaps questioner wasn't able to explain the problem. The problem is webview hitresults isn't able to grab url of image, when longpressed on image in facebook, what happens is, instead of grabbing url of image it grabs the url of that post, due to this, image is not able to isolate from the post. that's a facebook kind of problem. I was able to verify the issue using SRC_ANCHOR_TYPE in hitresults. – Mustansir Oct 03 '16 at 13:01