Last active
August 29, 2015 14:01
-
-
Save dashorst/47d8f47ab4555fa5d921 to your computer and use it in GitHub Desktop.
Flickr API client om in een AsyncTask foto's voor een locatie op te halen.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.util.HashSet; | |
import java.util.Iterator; | |
import java.util.List; | |
import javax.xml.parsers.ParserConfigurationException; | |
import org.json.JSONException; | |
import android.location.Location; | |
import android.os.AsyncTask; | |
import android.util.Log; | |
import com.googlecode.flickrjandroid.Flickr; | |
import com.googlecode.flickrjandroid.FlickrException; | |
import com.googlecode.flickrjandroid.Parameter; | |
import com.googlecode.flickrjandroid.REST; | |
import com.googlecode.flickrjandroid.oauth.OAuthUtils; | |
import com.googlecode.flickrjandroid.photos.Photo; | |
import com.googlecode.flickrjandroid.photos.PhotoList; | |
import com.googlecode.flickrjandroid.photos.SearchParameters; | |
import com.googlecode.flickrjandroid.util.IOUtilities; | |
import com.googlecode.flickrjandroid.util.UrlUtilities; | |
/** | |
* Opzoeken van fotos op Android voor Flickr, gegeven een bepaalde locatie. Is | |
* een achtergrondtaak omdat je op Android geen netwerkverkeer mag genereren op | |
* de main-thread. | |
* | |
* <h3>Gebruik</h3> | |
* | |
* Je kan op twee manieren de fotos binnen krijgen: | |
* {@link AsyncTask#onProgressUpdate(Photos...) per foto die opgehaald is} of | |
* {@link AsyncTask#onPostExecute(PhotoList) nadat alles opgehaald is}. | |
* | |
* <pre> | |
* FlickrLookup lookup = new FlickrLoopup() { | |
* public void onProgressUpdate(Photo... photos) { | |
* // doe iets met de photos | |
* } | |
* | |
* public void onPostExecute(PhotoList photos) { | |
* // doe iets met de photos | |
* } | |
* }); | |
* lookup.execute(location); | |
* </pre> | |
*/ | |
public class FlickrLookup extends AsyncTask<Location, Photo, PhotoList> { | |
@Override | |
protected PhotoList doInBackground(Location... locations) { | |
PhotoList list = new PhotoList(); | |
try { | |
for (Location location : locations) { | |
PhotoList photos = retrievePhotoDescriptions(location); | |
list.addAll(photos); | |
} | |
for (Photo photo : list) { | |
retrievePhotoContents(photo); | |
publishProgress(photo); | |
} | |
} catch (Exception e) { | |
Log.e("FlickrLookup", e.getClass() + ":" + e.getMessage(), e); | |
} | |
return list; | |
} | |
/** | |
* Haalt de foto omschrijvingen op voor de locatie, bevat niet de | |
* daadwerkelijke JPG. | |
*/ | |
private PhotoList retrievePhotoDescriptions(Location location) | |
throws ParserConfigurationException, IOException, FlickrException, | |
JSONException { | |
// maak een flickr client met onze eigen HTTPS aware rest client | |
Flickr f = new Flickr("4a67c256e5b0e4db6aa274513108928c", new MyREST()); | |
// creeer de zoek parameters voor het zoeken op locatie | |
SearchParameters pars = new SearchParameters(); | |
pars.setLatitude(Double.toString(location.getLatitude())); | |
pars.setLongitude(Double.toString(location.getLongitude())); | |
// vertel Flickr om ook de maker van de foto en de omschrijving terug te | |
// geven | |
HashSet<String> extras = new HashSet<String>(); | |
extras.add("owner_name"); | |
extras.add("description"); | |
pars.setExtras(extras); | |
// haal 10 fotos op van de locatie | |
PhotoList photos = f.getPhotosInterface().search(pars, 10, 0); | |
return photos; | |
} | |
/** | |
* Haalt de JPG op van de foto omschrijving. | |
*/ | |
private void retrievePhotoContents(Photo photo) throws IOException, | |
MalformedURLException { | |
// gebruik de medium 640px brede foto (Glass heeft 640x360 resolutie) | |
URL photoUrl = new URL(photo.getMedium640Url()); | |
// HttpUrlConnection om deze later te kunnen sluiten | |
HttpURLConnection connection = (HttpURLConnection) photoUrl | |
.openConnection(); | |
try { | |
connection.connect(); | |
// kopieer de bytes van de connectie naar een interne byte array | |
InputStream input = connection.getInputStream(); | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
byte[] buffer = new byte[32768]; | |
int len = input.read(buffer); | |
while (len != -1) { | |
baos.write(buffer, 0, len); | |
len = input.read(buffer); | |
} | |
photo.setBytes(baos.toByteArray()); | |
Log.i("Photo", | |
"id: " + photo.getId() + ", url:" + photo.getMedium640Url() | |
+ ", title:" + photo.getTitle() + ", description:" | |
+ photo.getDescription() + ", owner:" | |
+ photo.getOwner().getUsername() + ", size: " | |
+ photo.getBytes().length); | |
} finally { | |
connection.disconnect(); | |
} | |
} | |
private class MyREST extends REST { | |
private MyREST() throws ParserConfigurationException { | |
super(Flickr.DEFAULT_HOST); | |
} | |
/** | |
* Send a GET request to the provided URL with the given parameters, | |
* then return the response as a String. | |
* | |
* @param path | |
* @param parameters | |
* @return the data in String | |
* @throws IOException | |
*/ | |
public String getLine(String path, List<Parameter> parameters) | |
throws IOException { | |
InputStream in = null; | |
BufferedReader rd = null; | |
try { | |
in = getInputStream(path, parameters); | |
rd = new BufferedReader(new InputStreamReader(in, | |
OAuthUtils.ENC)); | |
final StringBuffer buf = new StringBuffer(); | |
String line; | |
while ((line = rd.readLine()) != null) { | |
buf.append(line); | |
} | |
return buf.toString(); | |
} finally { | |
IOUtilities.close(in); | |
IOUtilities.close(rd); | |
} | |
} | |
private InputStream getInputStream(String path, | |
List<Parameter> parameters) throws IOException { | |
URL url = buildUrl(getHost(), 443, path, parameters); | |
Log.i("REST", "url=" + url); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.addRequestProperty("Cache-Control", "no-cache,max-age=0"); | |
conn.addRequestProperty("Pragma", "no-cache"); | |
conn.setRequestMethod("GET"); | |
if (isProxyAuth()) { | |
conn.setRequestProperty("Proxy-Authorization", "Basic " | |
+ getProxyCredentials()); | |
} | |
conn.setDoOutput(false); | |
conn.setInstanceFollowRedirects(false); | |
conn.connect(); | |
int status = conn.getResponseCode(); | |
if (status == 200) { | |
return conn.getInputStream(); | |
} else { | |
return conn.getErrorStream(); | |
} | |
} | |
private URL buildUrl(String host, int port, String path, | |
List<Parameter> parameters) throws MalformedURLException { | |
// see: AuthUtilities.getSignature() | |
// AuthUtilities.addAuthToken(parameters); | |
StringBuffer buffer = new StringBuffer(); | |
buffer.append("https://"); | |
buffer.append(host); | |
if (port > 0 & port != 443) { | |
buffer.append(":"); | |
buffer.append(port); | |
} | |
if (path == null) { | |
path = "/"; | |
} | |
buffer.append(path); | |
Iterator<Parameter> iter = parameters.iterator(); | |
if (iter.hasNext()) { | |
buffer.append("?"); | |
} | |
while (iter.hasNext()) { | |
Parameter p = (Parameter) iter.next(); | |
buffer.append(p.getName()); | |
buffer.append("="); | |
Object value = p.getValue(); | |
if (value != null) { | |
String string = UrlUtilities.encode(value.toString()); | |
buffer.append(string); | |
} | |
if (iter.hasNext()) | |
buffer.append("&"); | |
} | |
/* | |
* RequestContext requestContext = | |
* RequestContext.getRequestContext(); Auth auth = | |
* requestContext.getAuth(); if (auth != null && | |
* !ignoreMethod(getMethod(parameters))) { | |
* buffer.append("&api_sig="); | |
* buffer.append(AuthUtilities.getSignature(sharedSecret, | |
* parameters)); } | |
*/ | |
return new URL(buffer.toString()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import com.google.android.glass.app.Card; | |
import com.google.android.glass.widget.CardScrollAdapter; | |
import com.google.android.glass.widget.CardScrollView; | |
public class CardScrollActivity extends Activity { | |
private List<Card> mCards = new ArrayList<Card>(); | |
private CardScrollView mCardScrollView; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
} | |
protected void addCard(Card c) { | |
mCards.add(c); | |
} | |
protected void updateView(){ | |
mCardScrollView = new CardScrollView(this); | |
ExampleCardScrollAdapter adapter = new ExampleCardScrollAdapter(); | |
mCardScrollView.setAdapter(adapter); | |
mCardScrollView.activate(); | |
setContentView(mCardScrollView); | |
} | |
private class ExampleCardScrollAdapter extends CardScrollAdapter { | |
@Override | |
public int getPosition(Object item) { | |
return mCards.indexOf(item); | |
} | |
@Override | |
public int getCount() { | |
return mCards.size(); | |
} | |
@Override | |
public Object getItem(int position) { | |
return mCards.get(position); | |
} | |
/** | |
* Returns the amount of view types. | |
*/ | |
@Override | |
public int getViewTypeCount() { | |
return Card.getViewTypeCount(); | |
} | |
/** | |
* Returns the view type of this card so the system can figure out | |
* if it can be recycled. | |
*/ | |
@Override | |
public int getItemViewType(int position){ | |
return mCards.get(position).getItemViewType(); | |
} | |
@Override | |
public View getView(int position, View convertView, | |
ViewGroup parent) { | |
return mCards.get(position).getView(convertView, parent); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment