I am getting a Null Pointer Exception. I want to retrieve a random quote from this Quotes Api - https://quotes.rest/ to display in my android application. Where am I going wrong?
(I apologise if I had not asked the question properly or violated any rules by posting a question. This is my first time asking a question)
I have created necessary POJOs and tried retrieving the quote in the MainActivity.
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<Example> call = service.getRandomQuote();
call.enqueue(new Callback<Example>() {
@Override
public void onResponse(Call<Example> call, Response<Example> response) {
String quote = response.body().getContents().getQuotes().get(0).getQuote();
Log.d(TAG, "onResponse: ************" + quote);
}
GetDataService
public interface GetDataService {
@GET("/quote/random")
Call<Example> getRandomQuote();
}
POJO- Quote
public class Quote {
@SerializedName("quote")
private String quote;
public Quote(String quote) {
this.quote = quote;
}
public String getQuote() {
return quote;
}
public void setQuote(String quote) {
this.quote = quote;
}
}
POJO- Contents
public class Contents {
@SerializedName("quotes")
@Expose
private List<Quote> quotes;
public List<Quote> getQuotes() {
return quotes;
}
public void setQuotes(List<Quote> quotes) {
this.quotes = quotes;
}
}
POJO- Example
public class Example {
@SerializedName("contents")
@Expose
private Contents contents;
public Contents getContents() {
return contents;
}
public void setContents(Contents contents) {
this.contents = contents;
}
}
RetrofitClientInstance class
public class RetrofitClientInstance {
private static Retrofit retrofit = null;
private static final String BASE_URL = "https://quotes.rest";
public static Retrofit getRetrofitInstance(){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
I expect the output to be a random quote from this Quotes Api (https://quotes.rest/) but I am getting a Null Pointer Exception. Following is the error-
java.lang.NullPointerException: Attempt to invoke virtual method 'com.platinumstudio.contactsdemo7.network.Contents com.platinumstudio.contactsdemo7.Example.getContents()' on a null object reference
at com.platinumstudio.contactsdemo7.MainActivity$3.onResponse(MainActivity.java)
body()first check what data it returnsIf you are a subscriber and you are trying this from a console add 'X-TheySaidSo-Api-Secret' header and add your api key as the header value. You can test and play with the API right here on this web page. For using the private end points and subscribing to the API please visit https://theysaidso.com/api.