简体   繁体   中英

How to call a REST api using retrofit without api key and present it in listview in Android?

REST API is " http://citywall.in/category.php "

O/P of code :

{
    "category": [{
        "id": "1",
        "name": "Recipe",
        "image": "receipe.jpg",
        "createdDate": "2019-03-27 00:00:00"
    }, {
        "id": "2",
        "name": "Gardening",
        "image": "gardening.jpg",
        "createdDate": "2019-03-27 00:00:00"
    }, {
        "id": "3",
        "name": "Services",
        "image": "services.jpg",
        "createdDate": "2019-03-27 00:00:00"
    }, {
        "id": "4",
        "name": "Tourism",
        "image": "tourism.jpg",
        "createdDate": "2019-03-27 00:00:00"
    }, {
        "id": "5",
        "name": "Lifestyle",
        "image": "lifestyle.jpg",
        "createdDate": "2019-03-27 00:00:00"
    }, {
        "id": "6",
        "name": "Other",
        "image": "other.jpg",
        "createdDate": "2019-03-27 00:00:00"
    }]
}

Fist you need to instantiate Retrofit:

   Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://citywall.in/")
    .build();

Then you should create and interface where Category is corresponding Class for each item in category list:

public interface CategoryServiceInterface{
    @Get("/category.php")
    Call<Response> getCategoryList(); 
}

Response class is a data class:

   public class Response{
        @SerializedName("category")
        private List<Category> categoryList = new ArrayList()

        /**
            Getters and setters....
        */
   }

   public class Category{
       @SerializedName("id")
       private String id;
       @SerializedName("name")
       private String name;
       @SerializedName("image")
       private String imageName;
       @SerializedName("createdDate")
       private Date createdDate;

       /**
            Getters and setters....
        */
   }

Now you have all fundamental. just call following:

   CategoryServiceInterface service = retrofit.create(CategoryServiceInterface.class)

   Response response = service.getCategoryList().body()

Now you have data model needed to be present in android list. For more details refer to following link.: https://square.github.io/retrofit/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM