Noe Nazza Noe Nazza - 1 month ago 19
Android Question

Apply variable to Retrofit HTTP method annotation

This is the code.
I want put params EMAIL! But i get attribute value must be costant

public interface Api{
Context context=null;
SharedPreferences sharedPref = context.getSharedPreferences("login",Context.MODE_PRIVATE);
static String email = sharedPref.getString("email","");

@GET("Home.php?email="+email+"&")
Call<List<Variabili_Main>> getHome(@Query("page") int index);

}


Help me!

ok i have edit but now how edit this?
And here what i do?

private void load(int index){
Call<List<Variabili_Main>> call = api.getHome(index);
call.enqueue(new Callback<List<Variabili_Main>>() {
@Override
public void onResponse(Call<List<Variabili_Main>> call, Response<List<Variabili_Main>> response) {
if(response.isSuccessful()){
movies.addAll(response.body());
adapter.notifyDataChanged();
}else{
Log.e(TAG," Response Error "+String.valueOf(response.code()));
}
}

@Override
public void onFailure(Call<List<Variabili_Main>> call, Throwable t) {
Log.e(TAG," Response Error "+t.getMessage());
}
});
}

Answer

If you want to concatenate a string in the annotation, it must be a compile-time constant. Something that is received at run-time from SharedPreferences isn't constant.

Probably better to add it as a query parameter.

@GET("Home.php")
Call<List<Variabili_Main>> getHome(@Query("email") String email, @Query("page") int index);

Then, just pass the email when you actually need it.

private void load(int index){

    // TODO: getContext ... shared preferences... 
    String email = prefs.getString("email");
    Call<List<Variabili_Main>> call = api.getHome(email, index);

    call.enqueue(new Callback<List<Variabili_Main>>() {
        @Override
        public void onResponse(Call<List<Variabili_Main>> call, Response<List<Variabili_Main>> response) {
            if(response.isSuccessful()){
                movies.addAll(response.body());
                adapter.notifyDataChanged();
            }else{
                Log.e(TAG," Response Error "+String.valueOf(response.code()));
            }
        }

        @Override
        public void onFailure(Call<List<Variabili_Main>> call, Throwable t) {
            Log.e(TAG," Response Error "+t.getMessage());
        }
    });
}
Comments