Jesse Cochran Jesse Cochran - 1 month ago 11
Android Question

Using Retrofit 2.0 for POST in Android Studio

I am working on one of my personal Android projects and I have run into a roadblock. I am attempting to POST to a URL using Retrofit 2.0.0-beta2, but am having some trouble with the service method that is supposed to convert the properties of my object (JsonPost) into a JSON Object. Below is my code for sending an object in a request body, this is in my MainActivity.

public void getTone() {
JsonPost jPost = new JsonPost("email", mJsonText);
Call<JsonPost> call = JsonService.createJsonPost(jPost);
call.enqueue(new Callback<JsonPost>() {
@Override
public void onResponse(retrofit.Response<JsonPost> response, Retrofit retrofit) {

}

@Override
public void onFailure(Throwable t) {

}
});
}


JsonService interface:

public interface JsonService {
@POST("/tone")
Call<JsonPost> createJsonPost(@Body JsonPost jPost);
}


The error is 'Non-static method .createJsonPost() cannot be referenced from static context'. While I understand what this means, I am not sure how to go about fixing this issue. If someone could please provide some insight, it would be much appreciated. Thanks!

Answer

Your issue relates to your line below in which you try and make the web service call:

Call<JsonPost> call = JsonService.createJsonPost(jPost);

The error you are getting:

'Non-static method .createJsonPost() cannot be referenced from static context'

Is generated because you are treating the interface JsonService and its method createJsonPost() as if it was a static method and not an instance method.

It looks like you may have not yet properly configured Retrofit to use your Service interface.

You need to have done the following code somewhere to initialise your service:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://yoururl.com")
    .build();

JsonService service = retrofit.create(JsonService.class);

and then you are free to use the service as follows:

Call<JsonPost> call = service.createJsonPost(jPost);
Comments