0

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)
5
  • log body() first check what data it returns Commented Jun 18, 2019 at 10:16
  • This happened because your response.body() might be null. While I tried to open the url on my browser it says unauthorized access. May be thats why your response.body() is null. Check that Commented Jun 18, 2019 at 10:19
  • You need to add an API key to the request. If 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. Commented Jun 18, 2019 at 10:26
  • Pass your apikey as header and try Commented Jun 18, 2019 at 10:29
  • Thank you all for the answers. Unfortunately, I just found out from the website that I have to pay to get the api key. I think i won't proceed with that API anymore. Commented Jun 18, 2019 at 11:40

4 Answers 4

1

The API that you're using here is this. As the API documentation says, an API key is required to fetch data. Since you didn't add an API key in your codes, it's should return an unsuccessful response with the HTTP Status Code of 401.

And it's always the best practice to check if the response is successful before proceeding to execute operations on received data to avoid crash issues in the app. Always keep this code snippet when you're fetching data from an API:

call.enqueue(new Callback<Example>() {
        @Override
        public void onResponse(Call<Example> call, Response<Example> response) {
                if(response.isSuccessful && response.body() != null){
                    //Get contents & quote
                }
                else {
                    //Check response code & show the relevant error message through Toast or Dialog
                }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
                //Show a failed message to the user
        }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I believe that you need to add Api key to your request, otherwise you'll not be allowed to access the data. Hence, your response's body is null, which causes the crash. As it says on the website:

For using the private end points and subscribing to the API please visit https://theysaidso.com/api.

Comments

0

https://theysaidso.com/api/ From the API website you will find the link to access the ramdom quote

here is the link:

http://quotes.rest/quote/random.json?api_key=

without the key you will get Unauthorized access

Comments

0

This API requires Authorization key to access the data. Hence, modify your interface GetDataService like below :

public interface GetDataService {
@GET("/quote/random/")
Call<Example> getRandomQuote(@HeaderMap Map<String, String> headerMap);

}

//HeaderMap will have authorization key and its value as <Key,Value> pair.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.