R
R
Roman_Craft2020-04-19 17:36:44
Java
Roman_Craft, 2020-04-19 17:36:44

Why is Retrofit not working?

I have a site that contains json. I want to parse, but nothing comes out. Here is the site: https://my-json-server.typicode.com/typicode/demo/posts

MainActivity.java:

package org.myapp.retrofittest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    TextView text;
    Link link;
    String url = "https://my-json-server.typicode.com/typicode/";
    Retrofit retrofit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.text);
        retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
        link = retrofit.create(Link.class);
        link.getSongs().enqueue(new Callback<GetData>() {
            @Override
            public void onResponse(Call<GetData> call, Response<GetData> response) {
                int id = response.body().getId();
                text.setText(String.valueOf(id));
            }

            @Override
            public void onFailure(Call<GetData> call, Throwable t) {
                text.setText("Fail");
            }
        });
    }
}

GetData.java:
package org.myapp.retrofittest;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class GetData {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

Link.java(Interface):
package org.myapp.retrofittest;

import retrofit2.Call;
import retrofit2.http.GET;

public interface Link {
    @GET("demo/posts/")
    Call<GetData> getSongs();
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question