Android Open Source - KangarooImageSearch Image Search Activity






From Project

Back to project page KangarooImageSearch.

License

The source code is released under:

MIT License

If you think the Android project KangarooImageSearch listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.nickrasband.kangarooimagesearchv2;
/* w w w  .  j  av a 2 s. c  o m*/
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

/**
 * This Activity handles the retrieval and display of images
 * retrieved by search the Google Image API.
 * @author Nik Rasband
 */
public class ImageSearchActivity extends Activity {
  
  private EditText etSearch;
  private GridView gvImages;
  private ArrayList<ImageData> images;
  private ImageDataAdapter imageAdapter;
  private SettingsData settingsData;
  
  // Tag used for debugging.
  private static final String DEBUG_TAG = "DEBUG";
  
  // Standard error message for toast when something goes wrong with the request.
  private static final String REQUEST_ERROR_TEXT = "There was an error with your request. Please try your search again.";
  
  // This is the base url used to make requests to the google image api. Additional key=value pairs
  // are concatenated to this string.
  private static final String BASE_URL = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&safe=active";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_search);
    
    settingsData = new SettingsData();
    setupViews();
    
    gvImages.setOnScrollListener(new EndlessScrollListener() {
        @Override
        public void onLoadMore(int page, int totalItemsCount) {
                  // Whatever code is needed to append new items to your AdapterView
                  // probably sending out a network request and appending items to your adapter. 
                  // Use the page or the totalItemsCount to retrieve correct data.
            loadMoreData(page); 
        }

      private void loadMoreData(int page) {
        requestImages(page * 8, false);
      }
    });
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.image_search, menu);
    return true;
  }

  /**
   * Grab the views needed by this activity and save them to member variables.
   * Also setup the adapter responsible for updating the images as that data changes.
   */
  private void setupViews() {
    // Store references to important views from the layout.
    etSearch = (EditText)findViewById(R.id.etSearch);
    gvImages = (GridView)findViewById(R.id.gvImages);
    
    // Setup the data container and adapter.
    images = new ArrayList<ImageData>();
    imageAdapter = new ImageDataAdapter(this, images);
    gvImages.setAdapter(imageAdapter);
    
    // Setup a click listener for any images in the grid view.
    gvImages.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapter, View item, int pos, long rowId) {
            // Launch the FullScreenImage activity to display a large version of the image.
          ImageData data = imageAdapter.getItem(pos);
          Intent intent = new Intent(getBaseContext(), FullScreenImageActivity.class);
          intent.putExtra("url", data.getFullUrl());
          startActivity(intent);
        }
    });
  }
  
  /**
   * Force the soft keyboard to be dismissed.
   */
  private void hideSoftKeyboard() {
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
  }
  
  /**
   * This method handles when the settings action is tapped
   * in the ActionBar.
   * @param item = the menu item that was clicked
   */
  public void showSettings(MenuItem item) {
    Intent intent = new Intent(this, SettingsActivity.class);
    intent.putExtra("settings", settingsData);
    startActivityForResult(intent, 0);
  }
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0 && resultCode == RESULT_OK) {
      settingsData = (SettingsData)data.getSerializableExtra("settings");
    }
  }
  
  // Build the correct url based on the page and user settings.
  private String buildUrl(int start) {
    // Retrieve the query string from the text field.
    String query = etSearch.getText().toString();
        
    // Get the user's ip address. This is highly recommended by the Google Search API,
    // because it lets the service validate that the requests are not automated (which is against 
    // the service's terms of service. See https://developers.google.com/image-search/v1/jsondevguide
    String ipAddress = Utils.getIPAddress(true);
    String url = BASE_URL + "&q=" + Uri.encode(query) + "&rsz=8&userip=" + ipAddress + "&start=" + String.valueOf(start);
    url += settingsData.getParams();
    Log.d(DEBUG_TAG, "url: " + url);
    return url;
  }
  
  /**
   * Search for images via Google's image search api.
   * Populate a grid view with the results.
   * @param v - the view (Button in this case) which was clicked.
   */
  public void search(View v) {
    // Dismiss the keyboard so that the user can see more images.
    hideSoftKeyboard();
    
    requestImages(0, true);
  }
  
  private void requestImages(int page, final Boolean clearResults) {
    // Create a url by concatenating all of the arguments we need.
    // rsz = the number of images to be retrieved at once. Must be 1-8.
    // q = query
    Log.d(DEBUG_TAG, "page: " + page);
    String url = buildUrl(page);
    
    // Create an asynchronous http client using the android-async-http library.
    AsyncHttpClient client = new AsyncHttpClient();
    
    // Make a get request to the Google Image API service. It should return json
    // which contains urls to the images.
    client.get(url, new JsonHttpResponseHandler() {

      @Override
      public void onFailure(Throwable throwable, JSONObject json) {
        String errorMessage = "Async Http Request failed.";
        if (json != null) {
          errorMessage += "json: " + json.toString();
        }
        Log.d(DEBUG_TAG, errorMessage);
        
        // Display the toast so that it wasn't just a silent failure.
        Toast.makeText(getBaseContext(), 
            REQUEST_ERROR_TEXT, 
            Toast.LENGTH_SHORT).show();
      }

      /**
       * When this request succeeds, it returns a json object
       * through which the image urls are accessed.
       */
      @Override
      public void onSuccess(JSONObject json) {
        if (json != null) {
          Log.d("DEBUG", "json: " + json.toString());
        }
        JSONArray imageResultsArray = null;
        try {
          // The json object has an outermost object with responseData as the key. Inside of
          // that resides the results array, which contains all of the image results.
          imageResultsArray = json.getJSONObject("responseData").getJSONArray("results");
          
          if (clearResults)
          {
            // Clear out the old data, because this is a different search.
            imageAdapter.clear();
          }
          
          // Update the image adapter which the images returned by the query.
          imageAdapter.addAll(ImageData.getImageDataForJsonArray(imageResultsArray));
        }
        catch (JSONException e) {
          e.printStackTrace();
          Toast.makeText(getBaseContext(), REQUEST_ERROR_TEXT, Toast.LENGTH_SHORT).show();
        }
      }

      @Override
      public void onFinish() {
        Log.d("DEBUG", "Finished Async Http request");
      }

      @Override
      public void onStart() {
        Log.d("DEBUG", "Started Async Http request");
      }
    });
  }

}




Java Source Code List

com.nickrasband.kangarooimagesearchv2.EndlessScrollListener.java
com.nickrasband.kangarooimagesearchv2.FullScreenImageActivity.java
com.nickrasband.kangarooimagesearchv2.ImageDataAdapter.java
com.nickrasband.kangarooimagesearchv2.ImageData.java
com.nickrasband.kangarooimagesearchv2.ImageSearchActivity.java
com.nickrasband.kangarooimagesearchv2.SettingsActivity.java
com.nickrasband.kangarooimagesearchv2.SettingsData.java
com.nickrasband.kangarooimagesearchv2.Utils.java