How to search for images in Android Programmatically?

meditat Source

I have some EditTexts in my Activity.First text the for the title, second is for author.Now the user loose focus from the second edittext ie author.I want to get the images related to that content (title and author).So what I did, I concat the title and author name and make HTTP request using Volley.And I print that response.But the response is so unpredictable that I can not fetch the images from it.

try {
        String googleImageUrl = "http://images.google.com/images?q=";
        String query = URLEncoder.encode(title + " " + author, "utf-8");
        String url = googleImageUrl + query;
        Toast.makeText(context, url, Toast.LENGTH_SHORT).show();
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);

  // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        post_des.setText("Response is: " + response);
                        Log.i("Show me something awesome dude", response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                post_des.setText("That didn't work!");
            }
        });
 // Add the request to the RequestQueue.
        queue.add(stringRequest);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

And the responce is like this:

Response is: <!doctype html><html itemscope="" itemtype="http://schema.org/SearchResultsPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><link href="/images/branding/product/ico/googleg_lodp.ico" rel="shortcut icon"><title>something something - Google Search</title><style>#gb{font:13px/27px Arial,sans-serif;height:30px}#gbz,#gbg{position:absolute;white-space:nowrap;top:0;height:30px;z-index:1000}#gbz{left:0;padding-left:4px}#gbg{right:0;padding-right:5px}#gbs{background:transparent;position:absolute;top:-999px;visibility:hidden;z-index:998;right:0}.gbto #gbs{background:#fff}#gbx3,#gbx4{background-color:#2d2d2d;background-image:none;_background-image:none;background-position:0 -138px;background-repeat:repeat-x;border-bottom:1px solid #000;font-size:24px;height:29px;_height:30px;opacity:1;filter:alpha(opacity=100);position:absolute;top:0;width:100%;z-index:990}#gbx3{left:0}#gbx4{right:0}#gbb{position:relative}#gbbw{left:0;position:absolute;top:30px;width:100%}.gbtcb{position:absolute;visibility:hidden}#gbz .gbtcb{right:0}#gbg .gbtcb{left:0}.gbxx{display:none........like wise

I was expecting to get a Html doc. So how to make a HTTP request for images with the content(title and author).

Edit In layman language,

Suppose I am on images.google.com, and I typed in something in search bar, and make a search, now I want the data that Google return as the Url of the images on that webpage(I am doing all this in backend not showing it to the user.) I think it is now understandable :)

androidandroid-volleygoogle-image-search

Answers

answered 6 months ago Rainmaker #1

You got html but of the whole search page. You can retrieve pictures' urls with css selectors and [JSOUP library][2] (easy to use). Just go to Chrome browser and then choose Settings - More tools - Developer tools. Then click the right mouse button on a picture and choose inspect and you'll see which container is for the pictures and what div contains src url of the images and then you right click this div and choose copy css selector. Then work with the library.

But be aware, it's not practical cause if they change the page html your code will beak. You better use specific api for this purpose, like Google Custom Search API as it was suggested in comments above.

To put image into UI you need to get its url address and then you can use Glide or Picasso or even Volley

// Retrieves an image with Volley specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
    new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap bitmap) {
            mImageView.setImageBitmap(bitmap);
        }
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            mImageView.setImageResource(R.drawable.image_load_error);
        }
    });

EDIT:

Here is CSS selector for all images on the google search page img.rg_ic. Using Jsoup and this selector you'll get access to all the image tags on the page

Jsoup example:

Document doc = Jsoup.connect(your link string).get();
Elements imgs = doc.select("img");//the selector
for (Element img : imgs) {
  //add img urls to String array and then use to get imgs with them
  String s = img.attr("src");
  arr.add(s);
}

[![enter image description here][3]][3]

enter image description here

EDIT2 :

Your code with changes:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {


TextView textView;
String googleImageUrl = "https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=";
ArrayList<String> urls = new ArrayList<>();
String url;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            Log.i("someething" , "something");
            getImages("https://www.google.co.in/search?biw=1366&bih=675&tbm=isch&sa=1&ei=qFSJWsuTNc-wzwKFrZHoCw&q=somethingsomething");
        }
    });
}

private void getImages(String url) {
    Document doc = null;
    try{
        doc = Jsoup.connect(url).get();
    }catch (IOException e){
        e.printStackTrace();
    }
    Elements imgs = doc.select("img");
    System.out.println("Damn images"+imgs);
    for (Element img : imgs){
        Log.d("image-src", img.attr("data-src"));//changed `src` to `data-src`
    }

}

}

comments powered by Disqus