tccpg288 tccpg288 - 9 months ago 55
Android Question

Cannot Query with Retrofit

I am using Retrofit and I want to query FlickR based on a search term that a user enters. I want to make sure I have it set up correctly, as I have limited experiences with Retrofit/REST. Any tutorials, advice, and commentary on my code would be appreciated.

I have labeled some of the items "UNSURE" where I didn't know what exactly was supposed to be entered. With REST, is "q" always used to denote a query?

At the end of the day, I want the image results to be displayed in a GridView and available for selection to the user:

public class MainActivity extends AppCompatActivity {

private EditText mSearchTerm;
private Button mRequestButton;
private String mQuery;

protected void onCreate(Bundle savedInstanceState) {

mSearchTerm = (EditText) findViewById(;
mRequestButton = (Button) findViewById(;
mRequestButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mQuery = mSearchTerm.getText().toString();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()

ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<List<Photo>> call = apiInterface.getPhotos(mQuery);
call.enqueue(new Callback<List<Photo>>() {
public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {


public void onFailure(Call<List<Photo>> call, Throwable t) {




//Synchronous vs. Asynchronous
public interface ApiInterface {
@GET("?&<mQuery>&api_key=1c448390199c03a6f2d436c40defd90e&format=json") //
Call<List<Photo>> getPhotos(@Query("q") String photoSearchTerm);



Almost. BTW looks like you're using Retrofit 1.9; Retrofit 2 is available and you may want to switch now as eventually I assume 1.9 will be deprecated.

RestAdapter restAdapter=new RestAdapter.Builder()
        .setLogLevel(RestAdapter.LogLevel.FULL)//log your request

public interface ApiInterface {
@GET("/rest")  //
void getPhotos(@Query("method") String method, @Query("api_key") String key, @Query ("user_id") String user, @Query("format") String format, @Query("city") String city, Callback<FlickrResponse> callback);

FlickrResponse is a Java class that represents the response you're expecting. You can plug some example JSON into this and then tweak the result as needed: There could be some other details that aren't exactly right but that should get you started. You can research request interceptors if you would like to avoid passing the key and user id and such every time. That way you can define an interceptor that will inject them into the request and you can remove those parameters from the interface.

Here's some info on migrating to Retrofit 2: