我正在尝试将flickr集成到我的项目中并在搜索时显示图像。但是在搜索时它并没有显示任何图像。我使用过这个教程http://michalu.eu/wordpress/android-flickr-api-tutorial/ ..我无法弄清楚我出错了..
MainActivity.java
public class MainActivity extends Activity {
public final String LAST_IMAGE = "lastImage";
public UIHandler uihandler;
public ImageAdapter imgAdapter;
private ArrayList<ImageContener> imageList;
// UI
private Button downloadPhotos;
private Gallery gallery;
private ImageView imgView;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Init UI Handler
uihandler = new UIHandler();
downloadPhotos = (Button) findViewById(R.id.button1);
editText = (EditText) findViewById(R.id.editText1);
gallery = (Gallery) findViewById(R.id.gallery1);
imgView = (ImageView) findViewById(R.id.imageView1);
// Click on thumbnail
gallery.setOnItemClickListener(onThumbClickListener);
// Click on search
downloadPhotos.setOnClickListener(onSearchButtonListener);
// Get prevoiusly downloaded list after orientation change
imageList = (ArrayList<ImageContener>) getLastNonConfigurationInstance();
if (imageList != null) {
imgAdapter = new ImageAdapter(getApplicationContext(), imageList);
ArrayList<ImageContener> ic = imgAdapter.getImageContener();
gallery.setAdapter(imgAdapter);
imgAdapter.notifyDataSetChanged();
int lastImage = -1;
if (savedInstanceState.containsKey(LAST_IMAGE)) {
lastImage = savedInstanceState.getInt(LAST_IMAGE);
}
if (lastImage >= 0 && ic.size() >= lastImage) {
gallery.setSelection(lastImage);
Bitmap photo = ic.get(lastImage).getPhoto();
if (photo == null)
new GetLargePhotoThread(ic.get(lastImage), uihandler).start();
else
imgView.setImageBitmap(ic.get(lastImage).photo);
}
}
}
/**
* Saving information about images
*/
@Override
public Object onRetainNonConfigurationInstance() {
if (imgAdapter != null)
return this.imgAdapter.getImageContener();
else
return null;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Saving index of selected item in Gallery
outState.putInt(LAST_IMAGE, gallery.getSelectedItemPosition());
super.onSaveInstanceState(outState);
}
/**
*
* @author michalu
*
* Downloading a larger photo using Thread
*/
public class GetLargePhotoThread extends Thread {
ImageContener ic;
UIHandler uih;
public GetLargePhotoThread(ImageContener ic, UIHandler uih) {
this.ic = ic;
this.uih = uih;
}
@Override
public void run() {
// TODO Auto-generated method stub
if (ic.getPhoto() == null) {
ic.setPhoto(FlickrManager.getImage(ic));
}
Bitmap bmp = ic.getPhoto();
if (ic.getPhoto() != null) {
Message msg = Message.obtain(uih, UIHandler.ID_SHOW_IMAGE);
msg.obj = bmp;
uih.sendMessage(msg);
}
}
}
/**
* Runnable to get metadata from Flickr API
*/
Runnable getMetadata = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String tag = editText.getText().toString().trim();
if (tag != null && tag.length() >= 3)
FlickrManager.searchImagesByTag(uihandler, getApplicationContext(), tag);
}
};
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int defaultItemBackground;
private ArrayList<ImageContener> imageContener;
public ArrayList<ImageContener> getImageContener() {
return imageContener;
}
public void setImageContener(ArrayList<ImageContener> imageContener) {
this.imageContener = imageContener;
}
public ImageAdapter(Context c, ArrayList<ImageContener> imageContener) {
mContext = c;
this.imageContener = imageContener;
TypedArray styleAttrs = c.obtainStyledAttributes(R.styleable.PicGallery);
styleAttrs.getResourceId(R.styleable.PicGallery_android_galleryItemBackground, 0);
defaultItemBackground = styleAttrs.getResourceId(R.styleable.PicGallery_android_galleryItemBackground, 0);
styleAttrs.recycle();
}
public int getCount() {
return imageContener.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
if (imageContener.get(position).thumb != null) {
i.setImageBitmap(imageContener.get(position).thumb);
i.setLayoutParams(new Gallery.LayoutParams(75, 75));
i.setBackgroundResource(defaultItemBackground);
} else
i.setImageDrawable(getResources().getDrawable(android.R.color.black));
return i;
}
}
/**
*
* @author michalu
*
* UI Handler to handle messages from threads
*/
class UIHandler extends Handler {
public static final int ID_METADATA_DOWNLOADED = 0;
public static final int ID_SHOW_IMAGE = 1;
public static final int ID_UPDATE_ADAPTER = 2;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ID_METADATA_DOWNLOADED:
// Set of information required to download thumbnails is
// available now
if (msg.obj != null) {
imageList = (ArrayList<ImageContener>) msg.obj;
imgAdapter = new ImageAdapter(getApplicationContext(), imageList);
gallery.setAdapter(imgAdapter);
for (int i = 0; i < imgAdapter.getCount(); i++) {
new GetThumbnailsThread(uihandler, imgAdapter.getImageContener().get(i)).start();
}
}
break;
case ID_SHOW_IMAGE:
// Display large image
if (msg.obj != null) {
imgView.setImageBitmap((Bitmap) msg.obj);
imgView.setVisibility(View.VISIBLE);
}
break;
case ID_UPDATE_ADAPTER:
// Update adapter with thumnails
imgAdapter.notifyDataSetChanged();
break;
}
super.handleMessage(msg);
}
}
OnItemClickListener onThumbClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// Get large image of selected thumnail
new GetLargePhotoThread(imageList.get(position), uihandler).start();
}
};
/**
* to get metadata from Flickr API
*/
OnClickListener onSearchButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (gallery.getAdapter() != null) {
imgAdapter.imageContener = new ArrayList<ImageContener>();
gallery.setAdapter(imgAdapter);
imgView.setVisibility(View.INVISIBLE);
}
new Thread(getMetadata).start();
}
};
}
FlickrManager.java
public class FlickrManager {
// String to create Flickr API urls
private static final String FLICKR_BASE_URL = "http://api.flickr.com/services/rest/?method=";
private static final String FLICKR_PHOTOS_SEARCH_STRING = "flickr.photos.search";
private static final String FLICKR_GET_SIZES_STRING = "flickr.photos.getSizes";
private static final int FLICKR_PHOTOS_SEARCH_ID = 1;
private static final int FLICKR_GET_SIZES_ID = 2;
private static final int NUMBER_OF_PHOTOS = 20;
//You can set here your API_KEY
private static final String APIKEY_SEARCH_STRING = "&api_key=31c97c8908514f10f10b64b1bac83ec9";
private static final String TAGS_STRING = "&tags=";
private static final String PHOTO_ID_STRING = "&photo_id=";
private static final String FORMAT_STRING = "&format=json";
public static final int PHOTO_THUMB = 111;
public static final int PHOTO_LARGE = 222;
public static UIHandler uihandler;
private static String createURL(int methodId, String parameter) {
String method_type = "";
String url = null;
switch (methodId) {
case FLICKR_PHOTOS_SEARCH_ID:
method_type = FLICKR_PHOTOS_SEARCH_STRING;
url = FLICKR_BASE_URL + method_type + APIKEY_SEARCH_STRING + TAGS_STRING + parameter + FORMAT_STRING + "&per_page="+NUMBER_OF_PHOTOS+"&media=photos";
break;
case FLICKR_GET_SIZES_ID:
method_type = FLICKR_GET_SIZES_STRING;
url = FLICKR_BASE_URL + method_type + PHOTO_ID_STRING + parameter + APIKEY_SEARCH_STRING + FORMAT_STRING;
break;
}
return url;
}
// http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
public static void getImageURLS(ImageContener imgCon) {
String url = createURL(FLICKR_GET_SIZES_ID, imgCon.id);
ByteArrayOutputStream baos = URLConnector.readBytes(url);
String json = baos.toString();
try {
JSONObject root = new JSONObject(json.replace("jsonFlickrApi(", "").replace(")", ""));
JSONObject sizes = root.getJSONObject("sizes");
JSONArray size = sizes.getJSONArray("size");
for (int i = 0; i < size.length(); i++) {
JSONObject image = size.getJSONObject(i);
if (image.getString("label").equals("Square")) {
imgCon.setThumbURL(image.getString("source"));
} else if (image.getString("label").equals("Medium")) {
imgCon.setLargeURL(image.getString("source"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static Bitmap getImage(ImageContener imgCon) {
Bitmap bm = null;
try {
URL aURL = new URL(imgCon.largeURL);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (Exception e) {
Log.e("FlickrManager", e.getMessage());
}
return bm;
}
public static void getThumbnails(ArrayList<ImageContener> imgCon, UIHandler uih) {
for (int i = 0; i < imgCon.size(); i++)
new GetThumbnailsThread(uih, imgCon.get(i)).start();
}
public static Bitmap getThumbnail(ImageContener imgCon) {
Bitmap bm = null;
try {
URL aURL = new URL(imgCon.thumbURL);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (Exception e) {
Log.e("FlickrManager", e.getMessage());
}
return bm;
}
public static class GetThumbnailsThread extends Thread {
UIHandler uih;
ImageContener imgContener;
public GetThumbnailsThread(UIHandler uih, ImageContener imgCon) {
this.uih = uih;
this.imgContener = imgCon;
}
@Override
public void run() {
// TODO Auto-generated method stub
imgContener.thumb = getThumbnail(imgContener);
if (imgContener.thumb != null) {
Message msg = Message.obtain(uih, UIHandler.ID_UPDATE_ADAPTER);
uih.sendMessage(msg);
}
}
}
public static ArrayList<ImageContener> searchImagesByTag(UIHandler uih, Context ctx, String tag) {
uihandler = uih;
String url = createURL(FLICKR_PHOTOS_SEARCH_ID, tag);
ArrayList<ImageContener> tmp = new ArrayList<ImageContener>();
String jsonString = null;
try {
if (URLConnector.isOnline(ctx)) {
ByteArrayOutputStream baos = URLConnector.readBytes(url);
jsonString = baos.toString();
}
try {
JSONObject root = new JSONObject(jsonString.replace("jsonFlickrApi(", "").replace(")", ""));
JSONObject photos = root.getJSONObject("photos");
JSONArray imageJSONArray = photos.getJSONArray("photo");
for (int i = 0; i < imageJSONArray.length(); i++) {
JSONObject item = imageJSONArray.getJSONObject(i);
ImageContener imgCon = new ImageContener(item.getString("id"), item.getString("owner"), item.getString("secret"), item.getString("server"),
item.getString("farm"));
imgCon.position = i;
tmp.add(imgCon);
}
Message msg = Message.obtain(uih, UIHandler.ID_METADATA_DOWNLOADED);
msg.obj = tmp;
uih.sendMessage(msg);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NullPointerException nue) {
nue.printStackTrace();
}
return tmp;
}
}
URLConnector.java
public class URLConnector {
private static int CONNECT_TIMEOUT_MS = 5000;
private static int READ_TIMEOUT_MS = 15000;
public static boolean isOnline(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
/**
* Read all bytes from urlS
*
* @param urlS
* @return ByteArrayOutputStream with content or null
*/
public static ByteArrayOutputStream readBytes(String urlS) {
ByteArrayOutputStream baos = null;
InputStream is = null;
HttpURLConnection httpURLConnection = null;
try {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
URL url = new URL(urlS);
Log.i("URL", url.toString());
httpURLConnection = (HttpURLConnection) url.openConnection();
int response = httpURLConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT_MS);
httpURLConnection.setReadTimeout(READ_TIMEOUT_MS);
is = new BufferedInputStream(httpURLConnection.getInputStream());
int size = 1024;
byte[] buffer = new byte[size];
baos = new ByteArrayOutputStream();
int read = 0;
while ((read = is.read(buffer)) != -1) {
if (read > 0) {
baos.write(buffer, 0, read);
buffer = new byte[size];
}
}
}
} catch (Exception exc) {
exc.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (httpURLConnection != null) {
try {
httpURLConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return baos;
}
}
ImageContener.java
public class ImageContener implements IThumb {
String id;
int position;
String thumbURL;
Bitmap thumb;
Bitmap photo;
String largeURL;
String owner;
String secret;
String server;
String farm;
public ImageContener(String id, String thumbURL, String largeURL, String owner, String secret, String server, String farm) {
super();
this.id = id;
this.owner = owner;
this.secret = secret;
this.server = server;
this.farm = farm;
}
public ImageContener(String id, String owner, String secret, String server, String farm) {
super();
this.id = id;
this.owner = owner;
this.secret = secret;
this.server = server;
this.farm = farm;
setThumbURL(createPhotoURL(FlickrManager.PHOTO_THUMB, this));
setLargeURL(createPhotoURL(FlickrManager.PHOTO_LARGE, this));
}
public String getThumbURL() {
return thumbURL;
}
public void setThumbURL(String thumbURL) {
this.thumbURL = thumbURL;
onSaveThumbURL(FlickrManager.uihandler, this);
}
public String getLargeURL() {
return largeURL;
}
public void setLargeURL(String largeURL) {
this.largeURL = largeURL;
}
@Override
public String toString() {
return "ImageContener [id=" + id + ", thumbURL=" + thumbURL + ", largeURL=" + largeURL + ", owner=" + owner + ", secret=" + secret + ", server=" + server + ", farm="
+ farm + "]";
}
private String createPhotoURL(int photoType, ImageContener imgCon) {
String tmp = null;
tmp = "http://farm" + imgCon.farm + ".staticflickr.com/" + imgCon.server + "/" + imgCon.id + "_" + imgCon.secret;// +".jpg";
switch (photoType) {
case FlickrManager.PHOTO_THUMB:
tmp += "_t";
break;
case FlickrManager.PHOTO_LARGE:
tmp += "_z";
break;
}
tmp += ".jpg";
return tmp;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public Bitmap getThumb() {
return thumb;
}
public void setThumb(Bitmap thumb) {
this.thumb = thumb;
}
public Bitmap getPhoto() {
return photo;
}
public void setPhoto(Bitmap photo) {
this.photo = photo;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getFarm() {
return farm;
}
public void setFarm(String farm) {
this.farm = farm;
}
@Override
public void onSaveThumbURL(UIHandler uih, ImageContener ic) {
// TODO Auto-generated method stub
new GetThumbnailsThread(uih, ic).start();
}
}
IThumb.java
public interface IThumb {
public void onSaveThumbURL(UIHandler uih, ImageContener ic);
}
答案 0 :(得分:0)
&#34; http://api.flickr.com/services/rest/?method=&#34 ;;而不是&#34; https://api.flickr.com/services/rest/?method=&#34;那就行了。