How to set Retrofit response body data in Listview - java

In Daata function try to fetch data from server. Successfully fetched, but data cant be set in ArrayList
List<FlowerListModel>flowerListModels=new ArrayList<>();
Cause i want to set flowerListModels data in FlowerAdapter and show in listview
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
List<FlowerListModel>flowerListModels=new ArrayList<>();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
Here is FlowerListModel class
package bdservers.com.schoolmanagement.Model;
public class FlowerListModel {
private String category;
private String instructions;
private String photo;
private String name;
private String price;
public FlowerListModel(){}
public FlowerListModel(String category, String instructions, String photo, String name,String price){
this.category=category;
this.instructions=instructions;
this.photo=photo;
this.name=name;
this.price=price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}

You are setting empty ArrayList to your adapter, I have highlighted the line where you have made the error, and also the correct line that you need
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
/**
* You are setting this empty list to adapter
*List<FlowerListModel>flowerListModels=new ArrayList<>();
*/
List<FlowerListModel> flowerListModels = new ArrayList<>();
flowerListModels = response.body();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}

You are creating new empty List here: List<FlowerListModel>flowerListModels=new ArrayList<>();
You can try something like this:
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),response.body());
listView.setAdapter(flowerAdapter);
}

Create BaseResponse model like this
public class BaseResponse {
#SerializedName("data")
private List<Object> alObjects;
public BaseResponse(List<Object> alObjects) {
this.alObjects = alObjects;
}
public List<Object> getAlObjects() {
return alObjects;
}
public void setAlObjects(List<Object> alObjects) {
this.alObjects = alObjects;
}
}
Then get data from server
#POST(Constants.URL_API_DATA)
BaseResponse executeBaseResponse(#Body String mData);
Cheers!!

Related

How to set the request payload for the below example in Rest assured?

I need to set a request Payload as (attached image) in rest assured, the images tag has to contain a array of name and job value pair and followed by url string array. I tried using POJO, but I could not replicate the payload exactly.
sample payload
{
"id":1,
"title":"iPhone 9",
"description":"An apple mobile which is nothing like apple",
"price":549,
"images":[
{
"name":"aaa",
"job":"dev"
},
"https://i.dummyjson.com/data/products/1/1.jpg",
"https://i.dummyjson.com/data/products/1/2.jpg"
]
}
The code I tried.
Main class,
public class PostDataWithoutSerial {
pojoimage p1 = new pojoimage();
Images i1=new Images();
List<Images> img = new ArrayList<Images>();
ArrayList<String> url1 = new ArrayList<String>();
#Test
public void postRequestWithoutSerial()
{
p1.setTitle("google");
p1.setDescription("google phone");
p1.setPrice("800");
i1.setName("james");
i1.setJob("watt");
url1.add("aaa");
url1.add("bbb");
i1.setUrl(url1);
img.add(i1);
p1.setImages(img);
given().log().all()
.contentType("application/json")
.body(p1)
.when()
.post("http://localhost:3000/products")
.then()
.statusCode(201);
//validating single value in response
}
}
pojoimage.java class (Getters and setters class)
import java.util.ArrayList;
import java.util.List;
import java.util.List;
public class pojoimage {
public String id;
public String title;
public String description;
public String price;
public List< Images> images;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public List<Images> getImages() {
return images;
}
public void setImages(List<Images> images) {
this.images = images;
}
}
Images. java class
import java.util.ArrayList;
public class Images {
public String name;
public String job;
ArrayList<String> url = new ArrayList<String>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public ArrayList<String> getUrl() {
return url;
}
public void setUrl(ArrayList<String> url1) {
TODO Auto-generated method stub
this.url = url1;
}
}
Since images in your json contains json object and string, then the correct data type to hold both of them is List<Object>. In this solution, I use Map<> to simplify setting data for json object, you can replace by POJO.
import lombok.Data;
#Data
static class PojoImage {
public int id;
public String title;
public String description;
public int price;
public List<Object> images;
}
#Test
public void postRequestWithoutSerial() {
PojoImage pojoImage = new PojoImage();
pojoImage.setId(1);
pojoImage.setTitle("iPhone 9");
pojoImage.setDescription("An apple mobile which is nothing like apple");
pojoImage.setPrice(549);
List<Object> images = new ArrayList<>();
images.add(Map.of("name", "aaa", "job", "dev"));
images.add("https://i.dummyjson.com/data/products/1/1.jpg");
images.add("https://i.dummyjson.com/data/products/1/2.jpg");
pojoImage.setImages(images);
given().log().all()
.contentType("application/json")
.body(pojoImage)
.when()
.post("https://postman-echo.com/post");
}

Retrofit with Gson Response.body() not working

I'am trying to parse data to a recyclerview, i had some problems about expecting JSONArray/JSONObject that i fixed with some help, but this moment I am a little bit lost in what to do in the Onresponse, the original - generatePhonesList(response.body()) isnt working.
this is my json and i am trying to parse the data inside the array results[] :
{
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
MainActivity (CALL and Recyclerview creation) :
GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);
Call<APIReponse> call = service.getAllPhones();
call.enqueue(new Callback<APIReponse>() {
#Override
public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<APIReponse> call, Throwable t) {
Log.e("eee" , "" + t.getMessage());
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
this is the POJO Class's created in jsonschema2pojo :
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
2 class
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Integer getTotalProducts() {
return totalProducts;
}
public void setTotalProducts(Integer totalProducts) {
this.totalProducts = totalProducts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
3 class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getMaxSavingPercentage() {
return maxSavingPercentage;
}
public void setMaxSavingPercentage(Integer maxSavingPercentage) {
this.maxSavingPercentage = maxSavingPercentage;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(Integer specialPrice) {
this.specialPrice = specialPrice;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
}
You are passing the APIReponse model to the generatePhonesList(List<Result> phonesList) function. You need to pass only the list of results in this function.
Replace this:
generatePhonesList(response.body());
with:
generatePhonesList(response.body().getMetadata().getResults());
Here getMetadata() and getResults() are the getter functions of metadata model and List.
If you pay close attention response.body() will provide you with class APIResponse. But you need is List<Result>. To achieve this, try response.body().getMetadata().getResults()
This should give you the desired output.

How to pass raw data in API request using Retrofit2 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to call login API using Retrofit2.
But in onResponse i alwasy get null as response.
Login API endpoint
#FormUrlEncoded
#POST("/api/login/{mobile}")
Call<ResObj> userLogin( #Field("phoneNumber") String mobile );
And the API implementation
private void doLogin(final String mobile){
Call<ResObj> call = userService.login(mobile);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body(); // here i am getting null response.body()
if(resObj.getMessage().equals("true")){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
Toast.makeText(Login.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
ResObj class:
public class ResObj {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I just want to know what causes the error and what are possible solutions.
UPDATE
POSTMAN
You are getting null response in your login API. It may be due to many reasons. You can check your API is working as expected or not using POSTMAN.
And inside your code, you can prevent this type of exception by checking OBJECT is null or not. like the following.
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body();
if(resObj != null){ // checking object is not null
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}else{
// handle null response here.
}
}
Update:
According to your Response JSON, Your Model(ResObj) class should be like the following.
public class ResObj
{
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getDate ()
{
return date;
}
public void setDate (String date)
{
this.date = date;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getContactPerson ()
{
return contactPerson;
}
public void setContactPerson (String contactPerson)
{
this.contactPerson = contactPerson;
}
public String getTimeOut ()
{
return timeOut;
}
public void setTimeOut (String timeOut)
{
this.timeOut = timeOut;
}
public String getProblem ()
{
return problem;
}
public void setProblem (String problem)
{
this.problem = problem;
}
public String getSrNo ()
{
return srNo;
}
public void setSrNo (String srNo)
{
this.srNo = srNo;
}
public String getFieldEngineer ()
{
return fieldEngineer;
}
public void setFieldEngineer (String fieldEngineer)
{
this.fieldEngineer = fieldEngineer;
}
public String getJoNo ()
{
return joNo;
}
public void setJoNo (String joNo)
{
this.joNo = joNo;
}
public String getIrNo ()
{
return irNo;
}
public void setIrNo (String irNo)
{
this.irNo = irNo;
}
public String getDesignation ()
{
return designation;
}
public void setDesignation (String designation)
{
this.designation = designation;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getTimeIn ()
{
return timeIn;
}
public void setTimeIn (String timeIn)
{
this.timeIn = timeIn;
}
public String getProductType ()
{
return productType;
}
public void setProductType (String productType)
{
this.productType = productType;
}
public boolean getStatus ()
{
return status;
}
public void setStatus (boolean status)
{
this.status = status;
}
public String getContactNo ()
{
return contactNo;
}
public void setContactNo (String contactNo)
{
this.contactNo = contactNo;
}
}
You are passing parameter as raw data(according to your screen-shot). So your API endpoint would be like below.
#Headers("Content-Type: application/json")
#POST("/api/login")
Call<ResObj> userLogin(#Body JsonObject jsonObject);
And call your API like this
private void doLogin(final String mobile){
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResObj> call = userService.login(paramObject);
call.enqueue(new Callback<ResObj>() {
//your rest of code
});
}
UPDATE-2:
To send object from one Activity to another using intent you have to make your model class Percelable. like this
// implements Parcelable
public class ResObj implements Parcelable {
// ...........your previous code here
// just simply add the following methods
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(date);
dest.writeString(address);
dest.writeString(accountName);
dest.writeString(contactPerson);
dest.writeString(timeOut);
dest.writeString(problem);
dest.writeString(srNo);
dest.writeString(fieldEngineer);
dest.writeString(joNo);
dest.writeString(irNo);
dest.writeString(designation);
dest.writeString(email);
dest.writeString(timeIn);
dest.writeString(productType);
dest.writeByte((byte) (status ? 1 : 0));
dest.writeString(contactNo);
}
public static final Parcelable.Creator<ResObj> CREATOR
= new Parcelable.Creator<ResObj>() {
public ResObj createFromParcel(Parcel in) {
return new ResObj(in);
}
public ResObj[] newArray(int size) {
return new ResObj[size];
}
};
protected ResObj(Parcel in) {
date = in.readString();
address = in.readString();
accountName = in.readString();
contactPerson = in.readString();
timeOut = in.readString();
problem = in.readString();
srNo = in.readString();
fieldEngineer = in.readString();
joNo = in.readString();
irNo = in.readString();
designation = in.readString();
email = in.readString();
timeIn = in.readString();
productType = in.readString();
status = in.readByte() != 0;
contactNo = in.readString();
}
}
Now pass your object via intent like the following.
if(resObj != null){
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("your_key", resObj); // pass resObj and use same key to get data
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
Get data from your ListActivity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final ResObj yourObject = getIntent().getParcelableExtra("your_key"); // make sure you use same key like data.
// Now you can use your data like that
yourEditText.setText(yourObject.getEmail());
}

Android: Use result from stringrequest in individual textviews

I have been able to get a string from an url, using volley. This string is now shown as one block in a textview. But I would like to be able to display this data in individual textviews. How could I do this?
Maybe important to know: I'm completely new at programming and this is my first week I'm doing this. So my method I used could be strange, and this might be a stupid question, but I'm just trying to learn, and to get the result I want.
This is the code I have now, to get the data from the url:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response.toString());
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
queue.add(request);
And this is how the result from the GET from the url looks like:
{"DeliveryDetailId":91003,"Delivery":{"DeliveryId":91,"DeliveryNumber":"1248","DropLocation":null,"DeliveryState":0},"ProductNumber":null,"Description":null,"PickLocation":"104","LocationCheck":null,"Quantity":64.0,"Histories":[],"BinNumberToUse":null}
So in this case I would like to have textviews which show the DeliveryID, Picklocation and Quantity. How can I extract this info from the string, so I can show it in the Textviews?
create model classes like below and store the response in Response.class
Then you can able to access DeliveryID by calling getDeliveryID()
-----------------------------------com.saranga.app.model.Delivery.java-----------------------------------
package com.saranga.app.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Delivery {
#SerializedName("DeliveryId")
#Expose
private Integer deliveryId;
#SerializedName("DeliveryNumber")
#Expose
private String deliveryNumber;
#SerializedName("DropLocation")
#Expose
private Object dropLocation;
#SerializedName("DeliveryState")
#Expose
private Integer deliveryState;
public Integer getDeliveryId() {
return deliveryId;
}
public void setDeliveryId(Integer deliveryId) {
this.deliveryId = deliveryId;
}
public String getDeliveryNumber() {
return deliveryNumber;
}
public void setDeliveryNumber(String deliveryNumber) {
this.deliveryNumber = deliveryNumber;
}
public Object getDropLocation() {
return dropLocation;
}
public void setDropLocation(Object dropLocation) {
this.dropLocation = dropLocation;
}
public Integer getDeliveryState() {
return deliveryState;
}
public void setDeliveryState(Integer deliveryState) {
this.deliveryState = deliveryState;
}
}
-----------------------------------com.saranga.app.model.Response.java-----------------------------------
package com.saranga.app.model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("DeliveryDetailId")
#Expose
private Integer deliveryDetailId;
#SerializedName("Delivery")
#Expose
private Delivery delivery;
#SerializedName("ProductNumber")
#Expose
private Object productNumber;
#SerializedName("Description")
#Expose
private Object description;
#SerializedName("PickLocation")
#Expose
private String pickLocation;
#SerializedName("LocationCheck")
#Expose
private Object locationCheck;
#SerializedName("Quantity")
#Expose
private Double quantity;
#SerializedName("Histories")
#Expose
private List<Object> histories = null;
#SerializedName("BinNumberToUse")
#Expose
private Object binNumberToUse;
public Integer getDeliveryDetailId() {
return deliveryDetailId;
}
public void setDeliveryDetailId(Integer deliveryDetailId) {
this.deliveryDetailId = deliveryDetailId;
}
public Delivery getDelivery() {
return delivery;
}
public void setDelivery(Delivery delivery) {
this.delivery = delivery;
}
public Object getProductNumber() {
return productNumber;
}
public void setProductNumber(Object productNumber) {
this.productNumber = productNumber;
}
public Object getDescription() {
return description;
}
public void setDescription(Object description) {
this.description = description;
}
public String getPickLocation() {
return pickLocation;
}
public void setPickLocation(String pickLocation) {
this.pickLocation = pickLocation;
}
public Object getLocationCheck() {
return locationCheck;
}
public void setLocationCheck(Object locationCheck) {
this.locationCheck = locationCheck;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public List<Object> getHistories() {
return histories;
}
public void setHistories(List<Object> histories) {
this.histories = histories;
}
public Object getBinNumberToUse() {
return binNumberToUse;
}
public void setBinNumberToUse(Object binNumberToUse) {
this.binNumberToUse = binNumberToUse;
}
}
You need to decode your JSONObject and individually get each element unless it's in a JSONArray in that case you need to loop through it
#Override
public void onResponse(String response) {
JSONObject json = new JSONObject(response);
textView.setText(json.getString("DeliveryDetailld"));
JSONObject details = json.getJSONObject("Delivery");
//Get data in Delivery Object
textView2.setText(details.getString("DeliveryId"));
}

Android - unable to fetch JSON using Retrofit2

I'm trying to get a JSON file using an URL, but the application is crashing.
JSON file api
MainActivity.java
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
// Logs show error is in the code below
service.getPopulationData(new Callback<Flag> (){
#Override
public void onResponse(Call<Flag> call, Response<Flag> response) {
Log.d("JSONData", response.body().toString());
}
#Override
public void onFailure(Call<Flag> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<Flag> callback) ;
}
Flag.java
public class Flag {
private int rank;
private String country;
private String population;
private String flag;
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
Edit: Error log can be found here: log
I've tried other solutions mentioned on stackoverflow, but I've been unable to get it right.
Also, I only want the flag URLs from the JSON file. How am I supposed to get it?
You will need the following two pojo class
JsonResponse.java
public class JsonResponse {
#SerializedName("worldpopulation")
#Expose
private List<Worldpopulation> worldpopulation = null;
public List<Worldpopulation> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Worldpopulation> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
Worldpopulation.java
public class Worldpopulation {
#SerializedName("rank")
#Expose
private Integer rank;
#SerializedName("country")
#Expose
private String country;
#SerializedName("population")
#Expose
private String population;
#SerializedName("flag")
#Expose
private String flag;
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
and make a retrofit call like below
service.getPopulationData(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
**** edited as per requirement ****
and change ApiService.java
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
Call<JsonResponse> getPopulationData() ;
}
and call it like this
made an edit here
ApiService service = retrofit.create(ApiService.class);
Call<JsonResponse> call = service.getPopulationData();
call.enqueue(new Callback<JsonResponse> (){
#Override
public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
Log.d("JSONData", response.body().toString());
ArrayList<Worldpopulation> population=new ArrayList(response.body().getWorldpopulation());
}
#Override
public void onFailure(Call<JsonResponse> call, Throwable t) {
Log.d("JSONData", t.getMessage());
}
});
The json you are trying to parse with Retrofit contains a JSON Array as its root worldpopulation , So First you need a class WorldPopulation as follow:
public class WorldPopulation
{
private List<Flag> worldpopulation;
public List<Flag> getWorldpopulation() {
return worldpopulation;
}
public void setWorldpopulation(List<Flag> worldpopulation) {
this.worldpopulation = worldpopulation;
}
}
public interface ApiService {
String BASE_URL = "http://www.androidbegin.com/";
#GET("tutorial/jsonparsetutorial.txt")
public void getPopulationData(Callback<WorldPopulation> callback) ;
}

Categories

Resources