square / retrofit

A type-safe HTTP client for Android and the JVM
https://square.github.io/retrofit/
Apache License 2.0
43.05k stars 7.31k forks source link

Not able to fetch data from API using Retrofit #2574

Closed Lalitv7 closed 6 years ago

Lalitv7 commented 6 years ago

I want to fatch data from restcountries api. MainActivity

 public class MainActivity extends AppCompatActivity {
    TextView tv4,tv1,tv2,tv3;
    EditText edit;
        public void loadCountryInfo(View view) {
            //EditText cn=(EditText) findViewById(R.id.CountryName);
            edit=(EditText)findViewById(R.id.ed1);
            final String countryName=edit.getText().toString();
            final String strURL="http://restcountries.eu";

            if (countryName.length() == 0) {
                Toast.makeText(this, "No Country Specified", Toast.LENGTH_SHORT).show();
            } else {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(strURL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

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

                Call<CountriesInfo> call = service.getCountryInfo(countryName);//countryName

                call.enqueue(new Callback<CountriesInfo>() {
                    @Override
                    public void onResponse(Call<CountriesInfo> call, Response<CountriesInfo> response) {

                        tv4=(TextView) findViewById(R.id.textView4);
                        tv1=(TextView) findViewById(R.id.textView1);
                        tv2=(TextView) findViewById(R.id.textView2);
                        tv3=(TextView) findViewById(R.id.textView3);
                        try {

                            tv1.setText(response.body().getCapital());    
                            tv2.setText(response.body().getArea().toString());                              
 tv3.setText(response.body().getPopulation().toString());
                             tv4.setText(response.body().getName().toString());

                        } catch (Exception e) {
                            tv1.setText(countryName);
                            Toast.makeText(MainActivity.this, "Something Went Wrong! Maybe due to invalid country name or Something like this.", Toast.LENGTH_SHORT).show();
                            int code =response.code();

                            System.out.println("this is errror♠♠  "+code);
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<CountriesInfo> call, Throwable t) {
                        //System.out.println("Here is some this is errror♠♠  ");
                        String code =  t.getMessage();
                        System.out.println("this is errror♠♠ helloooooooooo "+code);
                        Toast.makeText(MainActivity.this, "Something Went Wrong! Maybe due to invalid country name.", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button b=(Button) findViewById(R.id.button);
            //loadCountryInfo();
           }

    }

CountriesInfo: getters and setter


public class CountriesInfo {

    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("capital")
    @Expose
    private String capital;
    @SerializedName("altSpellings")
    @Expose
    private List<String> altSpellings = new ArrayList<String>();
    @SerializedName("relevance")
    @Expose
    private String relevance;
    @SerializedName("region")
    @Expose
    private String region;
    @SerializedName("subregion")
    @Expose
    private String subregion;
//    @SerializedName("translations")
//    @Expose
//    private Translations translations;
    @SerializedName("population")
    @Expose
    private Integer population;
    @SerializedName("latlng")
    @Expose
    private List<Double> latlng = new ArrayList<Double>();
    @SerializedName("demonym")
    @Expose
    private String demonym;
    @SerializedName("area")
    @Expose
    private Double area;
    @SerializedName("gini")
    @Expose
    private Double gini;
    @SerializedName("timezones")
    @Expose
    private List<String> timezones = new ArrayList<String>();
    @SerializedName("borders")
    @Expose
    private List<String> borders = new ArrayList<String>();
    @SerializedName("nativeName")
    @Expose
    private String nativeName;
    @SerializedName("callingCodes")
    @Expose
    private List<String> callingCodes = new ArrayList<String>();
    @SerializedName("topLevelDomain")
    @Expose
    private List<String> topLevelDomain = new ArrayList<String>();
    @SerializedName("alpha2Code")
    @Expose
    private String alpha2Code;
    @SerializedName("alpha3Code")
    @Expose
    private String alpha3Code;
    @SerializedName("currencies")
    @Expose
    private List<String> currencies = new ArrayList<String>();
    @SerializedName("languages")
    @Expose
    private List<String> languages = new ArrayList<String>();

    /**
     *
     * @return
     *     The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     *     The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     *     The capital
     */
    public String getCapital() {
        return capital;
    }

    /**
     *
     * @param capital
     *     The capital
     */
    public void setCapital(String capital) {
        this.capital = capital;
    }

    /**
     *
     * @return
     *     The altSpellings
     */
    public List<String> getAltSpellings() {
        return altSpellings;
    }

    /**
     *
     * @param altSpellings
     *     The altSpellings
     */
    public void setAltSpellings(List<String> altSpellings) {
        this.altSpellings = altSpellings;
    }

    /**
     *
     * @return
     *     The relevance
     */
    public String getRelevance() {
        return relevance;
    }

    /**
     *
     * @param relevance
     *     The relevance
     */
    public void setRelevance(String relevance) {
        this.relevance = relevance;
    }

    /**
     *
     * @return
     *     The region
     */
    public String getRegion() {
        return region;
    }

    /**
     *
     * @param region
     *     The region
     */
    public void setRegion(String region) {
        this.region = region;
    }

    /**
     *
     * @return
     *     The subregion
     */
    public String getSubregion() {
        return subregion;
    }

    /**
     *
     * @param subregion
     *     The subregion
     */
    public void setSubregion(String subregion) {
        this.subregion = subregion;
    }

    /**
     *
     * @return
     *     The translations
     */
//    public Translations getTranslations() {
//        return translations;
//    }

    /**
     *
     * @param translations
     *     The translations
     */
//    public void setTranslations(Translations translations) {
//        this.translations = translations;
//    }

    /**
     *
     * @return
     *     The population
     */
    public Integer getPopulation() {
        return population;
    }

    /**
     *
     * @param population
     *     The population
     */
    public void setPopulation(Integer population) {
        this.population = population;
    }

    /**
     *
     * @return
     *     The latlng
     */
    public List<Double> getLatlng() {
        return latlng;
    }

    /**
     *
     * @param latlng
     *     The latlng
     */
    public void setLatlng(List<Double> latlng) {
        this.latlng = latlng;
    }

    /**
     *
     * @return
     *     The demonym
     */
    public String getDemonym() {
        return demonym;
    }

    /**
     *
     * @param demonym
     *     The demonym
     */
    public void setDemonym(String demonym) {
        this.demonym = demonym;
    }

    /**
     *
     * @return
     *     The area
     */
    public Double getArea() {
        return area;
    }

    /**
     *
     * @param area
     *     The area
     */
    public void setArea(Double area) {
        this.area = area;
    }

    /**
     *
     * @return
     *     The gini
     */
    public Double getGini() {
        return gini;
    }

    /**
     *
     * @param gini
     *     The gini
     */
    public void setGini(Double gini) {
        this.gini = gini;
    }

    /**
     *
     * @return
     *     The timezones
     */
    public List<String> getTimezones() {
        return timezones;
    }

    /**
     *
     * @param timezones
     *     The timezones
     */
    public void setTimezones(List<String> timezones) {
        this.timezones = timezones;
    }

    /**
     *
     * @return
     *     The borders
     */
    public List<String> getBorders() {
        return borders;
    }

    /**
     *
     * @param borders
     *     The borders
     */
    public void setBorders(List<String> borders) {
        this.borders = borders;
    }

    /**
     *
     * @return
     *     The nativeName
     */
    public String getNativeName() {
        return nativeName;
    }

    /**
     *
     * @param nativeName
     *     The nativeName
     */
    public void setNativeName(String nativeName) {
        this.nativeName = nativeName;
    }

    /**
     *
     * @return
     *     The callingCodes
     */
    public List<String> getCallingCodes() {
        return callingCodes;
    }

    /**
     *
     * @param callingCodes
     *     The callingCodes
     */
    public void setCallingCodes(List<String> callingCodes) {
        this.callingCodes = callingCodes;
    }

    /**
     *
     * @return
     *     The topLevelDomain
     */
    public List<String> getTopLevelDomain() {
        return topLevelDomain;
    }

    /**
     *
     * @param topLevelDomain
     *     The topLevelDomain
     */
    public void setTopLevelDomain(List<String> topLevelDomain) {
        this.topLevelDomain = topLevelDomain;
    }

    /**
     *
     * @return
     *     The alpha2Code
     */
    public String getAlpha2Code() {
        return alpha2Code;
    }

    /**
     *
     * @param alpha2Code
     *     The alpha2Code
     */
    public void setAlpha2Code(String alpha2Code) {
        this.alpha2Code = alpha2Code;
    }

    /**
     *
     * @return
     *     The alpha3Code
     */
    public String getAlpha3Code() {
        return alpha3Code;
    }

    /**
     *
     * @param alpha3Code
     *     The alpha3Code
     */
    public void setAlpha3Code(String alpha3Code) {
        this.alpha3Code = alpha3Code;
    }

    /**
     *
     * @return
     *     The currencies
     */
    public List<String> getCurrencies() {
        return currencies;
    }

    /**
     *
     * @param currencies
     *     The currencies
     */
    public void setCurrencies(List<String> currencies) {
        this.currencies = currencies;
    }

    /**
     *
     * @return
     *     The languages
     */
    public List<String> getLanguages() {
        return languages;
    }

    /**
     *
     * @param languages
     *     The languages
     */
    public void setLanguages(List<String> languages) {
        this.languages = languages;
    }

}

RetrofiApi Interface : HTTP requests


public interface RetrofiApi {
   // String base_url = "https://restcountries.eu/";
    @GET("/rest/v2/name/")
    Call<CountriesInfo> getCountryInfo(@Query("q") String name);
}

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sony.finalsubmission.MainActivity">

    <EditText
        android:id="@+id/ed1"
        android:layout_width="322dp"
        android:layout_height="87dp"
        android:hint="kombro"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="322dp"
        android:layout_height="50dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="322dp"
        android:layout_height="50dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView1"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="322dp"
        android:layout_height="50dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:ignore="MissingConstraints" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="322dp"
        android:layout_height="50dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3"
        tools:ignore="MissingConstraints" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/textView1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ed1"
        android:onClick="loadCountryInfo"/>
</android.support.constraint.ConstraintLayout>

I am getting java.lang.NullPointerException in com.example.sony.finalsubmission.MainActivity$1.onResponse(MainActivity.java:53)

REBOOTERS commented 6 years ago

the body() method can be consumed only once . This maybe the reason of NullPointerException

JakeWharton commented 6 years ago

That's only true for OkHttp. It's a cached object in Retrofit.

That being said, it's impossible to know what's null here, but it's likely the views are absent or something in your model is deserializing as null. It's definitely not clear that it's a Retrofit problem. If it is, we'd need a self contained test case or executable sample demonstrating that is was. What you've provided is complicated and cannot be run to validate behavior.

On Mon, Nov 27, 2017, 7:19 AM Rookie notifications@github.com wrote:

the body() method can be consumed only once . This maybe the reason of NullPointerException

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/square/retrofit/issues/2574#issuecomment-347165757, or mute the thread https://github.com/notifications/unsubscribe-auth/AAEEEWNJwL721ag6J_V1Cbo2TMEO1mXuks5s6qjcgaJpZM4QrSH4 .