Reputation: 70
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!
Upvotes: 2
Views: 525
Reputation: 1
the JsonService service = retrofit.create(JsonService.class);
is the missing piece. For those willing to take a deeper lookminto it i recommend Consuming-APIs-with-Retrofit
Upvotes: 0
Reputation: 5149
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);
Upvotes: 1