I want to fetch some data from the server by using the retrofitlibrary on RecyclerView but the data is not showing on RecycleView. I read lots of answers but did not solve it yet so please solve my problem thank you in advance.
Below is my JSON Data
{
"item": [
{
"Item_Id": "1",
"Item_Name": "Item Name 1",
"Item_Description": "Item Name 1 Description",
"Item_Price": "330.00",
"Discount": "10",
"Item_Image": "http://192.168.1.5/easyshop/Items_Image/xyz.jpg",
"First_Name": "abc",
"Last_Name": "xyz",
"Mobile": "**********"
},
{
"Item_Id": "2",
"Item_Name": "Item Name 2",
"Item_Description": "Item Name 2 Description",
"Item_Price": "40.00",
"Discount": "30",
"Item_Image": "http://192.168.1.5/easyshop/Items_Image/xyz1.jpg",
"First_Name": "def",
"Last_Name": "uvw",
"Mobile": "**********"
}
]
}
API Client class where I have used the base URL, GSON and retrofit object
public class ApiClient {
public static final String BASE_URL = "http://192.168.1.5/easyshop/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(100, TimeUnit.SECONDS)
.readTimeout(100,TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
Interface
public interface APIService {
#FormUrlEncoded
#POST("GetItem.php")
Call<ItemArray> getItem(#Field("Retailer_Id")int Retailer_Id);
}
When I put JSON data in www.jsonschema2pojo.org it generates two files which are following as below
public class ItemArray {
#SerializedName("item")
#Expose
private List<ItemList> item = null;
public List<ItemList> getItem() {
return item;
}
public void setItem(List<ItemList> item) {
this.item = item;
}
}
getter Setter Class
public class ItemList {
#SerializedName("Item_Id")
#Expose
private String itemId;
#SerializedName("Item_Name")
#Expose
private String itemName;
#SerializedName("Item_Description")
#Expose
private String itemDescription;
#SerializedName("Item_Price")
#Expose
private String itemPrice;
#SerializedName("Discount")
#Expose
private String discount;
#SerializedName("Item_Image")
#Expose
private String itemImage;
#SerializedName("First_Name")
#Expose
private String firstName;
#SerializedName("Last_Name")
#Expose
private String lastName;
#SerializedName("Mobile")
#Expose
private String mobile;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; }
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getItemImage() {
return itemImage;
}
public void setItemImage(String itemImage) {
this.itemImage = itemImage;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
Adapter Class
public class Item_Card_Adapter extends RecyclerView.Adapter<Item_Card_Adapter.ViewHolder> {
//List to store all items
List<ItemList> items;
//Constructor of this class
public Item_Card_Adapter(List<ItemList> items){
super();
//Getting all items
this.items = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_layout,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(Item_Card_Adapter.ViewHolder holder, int position) {
holder.itemName.setText(items.get(position).getItemName());
holder.itemDesc.setText(items.get(position).getItemDescription());
holder.itemPrice.setText(items.get(position).getItemPrice());
}
#Override
public int getItemCount() {return items.size();}
class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.ItemName) TextView itemName;
#Bind(R.id.ItemDesc) TextView itemDesc;
#Bind(R.id.ItemPrice) TextView itemPrice;
#Bind(R.id.cardView) CardView cardView;
//Initializing Views
public ViewHolder(final View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
Item_Get_Activity Activity class
public class Item_Get_Activity extends AppCompatActivity {
#Bind(R.id.recyclerrView) RecyclerView recyclerView;
#Bind(R.id.progressBar) ProgressBar progressBar;
private List<ItemList> data;
private Item_Card_Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_get_activity);
ButterKnife.bind(this);
initViews();
}
private void initViews() {
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
getDataFromServer();
}
public void getDataFromServer() {
int i = 1;
APIService service = ApiClient.getClient().create(APIService.class);
Call<ItemArray> userCall = service.getItem(i);
userCall.enqueue(new Callback<ItemArray>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(Call<ItemArray> call, Response<ItemArray> response) {
if(response.isSuccessful()){
progressBar.setVisibility(View.GONE);
data = response.body().getItem();
adapter = new Item_Card_Adapter(data);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<ItemArray> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
}
You need to change your ApiServices Interface like this
public interface APIService {
#FormUrlEncoded
#POST("GetItem.php")
Call<ItemArray> getItem(#Field("Retailer_Id")int Retailer_Id);
}
Then in your Activity update the calling method
public void getDataFromServer() {
int i = 1;
APIService service = ApiClient.getClient().create(APIService.class);
Call<ItemArray> userCall = service.getItem(i);
userCall.enqueue(new Callback<ItemArray>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onResponse(Call<ItemArray> call, Response<ItemArray> response) {
if(response.isSuccessful()){
progressBar.setVisibility(View.GONE);
data = response.body().getItem();
adapter = new Item_Card_Adapter(data);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<List<ItemList>> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
Since your api response contain the "list" inside a Json object. You need a class that has a List variable. So retrofit will parse the response to ItemArray successfully
Update
The demo code link https://github.com/Siddharth-Dev/RetrofitDemo
This has your code and a working API code too.
Related
I'm stuck somewhere in between getting json array inside a object setting it to recylerview, I have to send a key to fetch data and getting response in json array inside a object. Didn't understand solutions got here, so I'm here if Somebody can help mre understand.
////Main class
public class today_doctors extends AppCompatActivity {
viewModel_doc listViewModel;
List<model_doc> datalist;
todayDoctorAdapter adapter;
TextView clinic_name;
RecyclerView recview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_today_doctors);
recview=findViewById(R.id.rv);
recview.setLayoutManager(new LinearLayoutManager(this));
recview.addItemDecoration(new DividerItemDecoration(this, 0));
adapter=new todayDoctorAdapter(datalist);
recview.setAdapter(adapter);
clinic_name=findViewById(R.id.tvDrName);
process();
}
public void process(){
listViewModel= new ViewModelProvider(this).get(viewModel_doc.class);
listViewModel.getDatalistObserver ().observe(this, new Observer<List<model_doc>>() {
#Override
public void onChanged(List<model_doc> Models) {
if(Models!=null) {
datalist= Models;
adapter.updateList(Models);
}
else
{
recview.setVisibility(View.GONE);
Toast.makeText(today_doctors.this, "No data recieved", Toast.LENGTH_SHORT).show();
}
}
});
listViewModel.makeApiCall();
}
//////////Viewmodel class
public class viewModel_doc extends ViewModel
{
private MutableLiveData<List<model_doc>> datalist2;
public viewModel_doc(){
datalist2=new MutableLiveData<>();
}
public MutableLiveData<List<model_doc>> getDatalistObserver()
{
return datalist2;
}
public void makeApiCall()
{
apiSet apiServices= apiController.getInstance().getApi();
Call<List<model_doc>> calldoc=apiServices.getList2("ll0004");
calldoc.enqueue(new Callback<List<model_doc>>() {
#Override
public void onResponse(Call<List<model_doc>> call, Response<List<model_doc>> response) {
datalist2.postValue(response.body());
}
#Override
public void onFailure(Call<List<model_doc>> call, Throwable t) {
datalist2.postValue(null);
Log.e("Error :",t.getMessage());
}
});
}
}
///////////////////main model
public class model_doc {
String status,msg;
ArrayList<Data> data;
public model_doc(String status, String msg, ArrayList<Data> data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public String getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public ArrayList<Data> getData() {
return data;
}
public static class Data {
String doctor_id;
String doctor_name;
String proposed_date;
String date;
// Getters setters
public Data(String doctor_id, String doctor_name, String proposed_date, String date) {
this.doctor_id = doctor_id;
this.doctor_name = doctor_name;
this.proposed_date = proposed_date;
this.date = date;
}
public String getDoctor_id() {
return doctor_id;
}
public String getDoctor_name() {
return doctor_name;
}
public String getProposed_date() {
return proposed_date;
}
public String getDate() {
return date;
}
}
}
////api interface
#FormUrlEncoded
#POST("doctor_list")
Call<List<model_doc>>getList2(
#Field("clinic_id") String clinic_id
);
//////////////////controller
public class apiController {
private static final String url="https://xyz.in/api/";
private static apiController clientObject;
private static Retrofit retrofit;
apiController()
{
retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized apiController getInstance(){
if(clientObject==null)
clientObject=new apiController();
return clientObject;
}
public apiSet getApi(){
return retrofit.create(apiSet.class);
}
}
////////////recycler adapter, made some changes in main model for nested data could handle it to adapter
public class todayDoctorAdapter extends RecyclerView.Adapter<todayDoctorAdapter.viewholder>
{
List<model_doc> datalist2;
public todayDoctorAdapter(List<model_doc> list){
this.datalist2=list;}
public void updateList(List<model_doc>list){
this.datalist2=list;
notifyDataSetChanged();
}
#NonNull
#Override
public todayDoctorAdapter.viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_doctors,parent,false);
return new todayDoctorAdapter.viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull todayDoctorAdapter.viewholder holder, int position){
holder.doctor_name.setText(String.format("Dr.%s", datalist2.get(position).getDoctor_app()));
holder.proposed_date.setText(String.format("Apt: %s","TODAY"));
String doc=datalist2.get(position).getDoctor_app();
holder.cv.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(arg0.getContext(), PatientsUnderDoctor.class);
intent.putExtra("doc_name", doc);
arg0.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount(){
if (this.datalist2!=null){
return this.datalist2.size();
}
return 0;
}
public static class viewholder extends RecyclerView.ViewHolder{
TextView doctor_name,proposed_date;
CardView cv;
public viewholder(#NonNull View itemView) {
super(itemView);
doctor_name=itemView.findViewById(R.id.drName);
proposed_date=itemView.findViewById(R.id.apptDate);
cv=itemView.findViewById(R.id.cv_patient);
}
}
}
//////////////////json data look like this
{
"status": "success",
"msg": "Found",
"data": [
{
"doc_code": "jhjh0001",
"app_date": "2022-09-13",
"doc_name": "kjk",
"count": 1
}
]
}
Hi I am trying to parse Json from this api https://restcountries.eu. But when i trie to parse the topLevelDomain i ve got the error: "E/Error: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 42 path $[0].topLevelDomain"
How can i fix it ?
Thanks in advance
Below is Json structure, My Model , and MainActivity
Json structure
[{
"name": "Colombia",
"topLevelDomain": [".co"],
"alpha2Code": "CO",
"alpha3Code": "COL",
"callingCodes": ["57"],
"capital": "Bogotá",
"altSpellings": ["CO", "Republic of Colombia", "República de Colombia"],
"region": "Americas",
"subregion": "South America",
"population": 48759958,
"latlng": [4.0, -72.0],
"demonym": "Colombian",
"area": 1141748.0,
"gini": 55.9,
"timezones": ["UTC-05:00"],
"borders": ["BRA", "ECU", "PAN", "PER", "VEN"],
"nativeName": "Colombia",
"numericCode": "170",
"currencies": [{
"code": "COP",
"name": "Colombian peso",
"symbol": "$"
}],
Model
public class ModelJsona {
private String flag;
private String name;
private String region;
private String topLevelDomain;
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getTopLevelDomain() {
return topLevelDomain;
}
public void setTopLevelDomain(String region) {
this.topLevelDomain = region;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<ModelJsona> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://restcountries.eu/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<ModelJsona>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<ModelJsona>>() {
#Override
public void onResponse(Call<List<ModelJsona>> call, Response<List<ModelJsona>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
}
#Override
public void onFailure(Call<List<ModelJsona>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
topLevelDomain is an array, not String. You should map it as so:
public class ModelJsona {
private String flag;
private String name;
private String region;
private List<String> topLevelDomain;
...
}
If you need it to be Serializable use ArrayList instead.
please advise. I have a complex json object which I get requesting to openweathermap API using Retrofit and GSONConverterFactory. I have a trouble requesting forecast for 5 days, I can't populate my Recyclerview with the data, something goes wrong. I can't get what should I write in the onResponse method of Retrofit callback.
Retrofit requests are all with code 200 and message OK. So trouble is not in this area.
Thank you in advance!
Here is structure of Json object
WeatherData is a root Object which I get parsing my Json, please find the code below. All the code for it (as well as for other POJO's is imported from jsonschema2pojo:
public class WeatherData {
#SerializedName("coord")
#Expose
private Coord coord;
#SerializedName("weather")
#Expose
private List<Weather> weather = null;
#SerializedName("base")
#Expose
private String base;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("visibility")
#Expose
private Integer visibility;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("dt")
#Expose
private Long dt;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("cod")
#Expose
private Integer cod;
public Coord getCoord() {
return coord;
}
public void setCoord(Coord coord) {
this.coord = coord;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Long getDt() {
return dt;
}
public void setDt(Long dt) {
this.dt = dt;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCod() {
return cod;
}
public void setCod(Integer cod) {
this.cod = cod;
}
Here is my RecyclerView.Adapter
public class Forecast5DaysAdapter extends RecyclerView.Adapter<Forecast5DaysAdapter.ForecastHolder> {
List<WeatherData> mWeatherDataList;
public static class ForecastHolder extends RecyclerView.ViewHolder {
public TextView dateOnDate;
public ImageView weatherOnDate;
public TextView tempOnDate;
public TextView windSpeedOnDate;
public ForecastHolder(View view) {
super(view);
dateOnDate = (TextView) view.findViewById(R.id.dateOnDate);
windSpeedOnDate = (TextView) view.findViewById(R.id.windSpeedOnDate);
tempOnDate = (TextView) view.findViewById(R.id.tempOnDate);
weatherOnDate = (ImageView) view.findViewById(R.id.imageOnDate);
}
}
public Forecast5DaysAdapter(List<WeatherData> mWeatherDataList) {
this.mWeatherDataList = mWeatherDataList;
}
#Override
public ForecastHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.forecast_card, parent, false);
final ForecastHolder forecastHolder = new ForecastHolder(view);
return forecastHolder;
}
#Override
public void onBindViewHolder(ForecastHolder holder, int position) {
//FILLING THE CARDS IN RECYCLERVIEW WITH INFORMATION
holder.dateOnDate.setText(mWeatherDataList.get(position).getDt().toString());
holder.tempOnDate.setText(mWeatherDataList.get(position).getMain().getTemp().toString());
holder.windSpeedOnDate.setText(mWeatherDataList.get(position).getWind().getSpeed().toString());
Picasso.with(holder.weatherOnDate.getContext()).load("http://openweathermap.org/img/w/" + mWeatherDataList.get(position).getWeather().get(position).getIcon() + ".png").into(holder.weatherOnDate);
}
#Override
public int getItemCount() {
return 0;
}
Here is the class I want to display the Recyclerview
public class Forecast5Days extends AppCompatActivity {
private static final String API_KEY = "HERE IS THE KEY";
private RecyclerView forecastRecycler;
private ArrayList<WeatherData> mWeatherData;
private Forecast5DaysAdapter forecast5DaysAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forecast_5_days);
forecastRecycler = (RecyclerView) findViewById(R.id.forecast_5_daysRecycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
forecastRecycler.setLayoutManager(layoutManager);
final Forecast5DaysAdapter forecast5DaysAdapter = new Forecast5DaysAdapter(mWeatherData);
forecastRecycler.setAdapter(forecast5DaysAdapter);
Intent intent = getIntent();
final String cityName = intent.getStringExtra("cityName");
if (!cityName.isEmpty()) {
Call<WeatherData> call = RetrofitBuilderHelper.weatherAPI.getForecast5Days(cityName, "ru", "metric", API_KEY);
call.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
//????????????????
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with request", Toast.LENGTH_LONG);
toast.show();
}
});
} else {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with intent", Toast.LENGTH_LONG);
toast.show();
}
}
Your onResponse should be like this
call.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
if(response.isSuccessful() && response.body != null) {
WeatherData data = response.body();
}
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with request", Toast.LENGTH_LONG);
toast.show();
}
});
Also your Call is Call<WeatherData> which will give you a single object. If you want a list of objects your call should be Call<List<WeatherData>>
I think you are looking to pass Weatherinstead of WeatherData so your onResponse should look like
call.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
if(response.isSuccessful() && response.body != null) {
WeatherData data = response.body();
List<Weather> weatherList = data.getWeatherList();
//Pass this list to your adapter
}
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Toast toast = Toast.makeText(Forecast5Days.this, "Something went wrong with request", Toast.LENGTH_LONG);
toast.show();
}
});
Your JSON return is a List not only a Single WeatherData Object.
So all you should have to do is a cange of the Expected return value.
Try this:
Call<List<WeatherData>> call = RetrofitBuilderHelper.weatherAPI.getForecast5Days(cityName, "ru", "metric", API_KEY);
call.enqueue(new Callback<List<WeatherData>>() {
#Override
public void onResponse(Call<List<WeatherData>> call, Response<List<WeatherData>> response) {
forecastRecycler.weatherList = response.body();
forecastRecycler.notifyDatasetChanged();
}
I've been working with Recycler view Android. I try to make a Recycler view from API Response. But, the list didn't show up, my adapter was not working. When i tried to debug this program, I got List<Produclist> list is null.
This my JSON Response from API
{
"code": 0,
"data": [
{
"product_list": [
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0011",
"price": {
"date": null,
"value": 0
},
"name": "Dana Ekuitas Prima"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0001",
"price": {
"date": "2017-01-03T11:44:52.6152Z",
"value": 150000
},
"name": "Manulife Dana Saham"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0008",
"price": {
"date": null,
"value": 0
},
"name": "Trim Kapital Plus"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0004",
"price": {
"date": "2017-01-03T11:44:52.6152Z",
"value": 150000
},
"name": "Manulife Syariah Sektoral Amanah"
}
],
"type": "Reksa Dana Saham"
}
],
"info": "Product list successfully loaded"
}
This My setter getter
public class ProductListResponse {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("info")
#Expose
private String info;
#SerializedName("data")
#Expose
private List<CategoryType> listCategory = new ArrayList<>();
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public List<CategoryType> getListCategory() {
return listCategory;
}
public void setListCategory(List<CategoryType> listCategory) {
this.listCategory = listCategory;
}
}
Setter getter of category type
public class CategoryType {
#SerializedName("type")
#Expose
private String type;
#SerializedName("product_list")
#Expose
private List<ProductList> productList = new ArrayList<ProductList>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<ProductList> getProductList() {
return productList;
}
public void setProductList(List<ProductList> productList) {
this.productList = productList;
}
}
Setter getter of ProductList
public class ProductList implements Serializable {
#SerializedName("code")
#Expose
private String code;
#SerializedName("name")
#Expose
private String name;
#SerializedName("price")
#Expose
private Price price;
#SerializedName("risk_level")
#Expose
private String riskLevel;
#SerializedName("return_level")
#Expose
private Double returnLevel;
#SerializedName("image")
#Expose
private String image;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRiskLevel() {
return riskLevel;
}
public void setRiskLevel(String riskLevel) {
this.riskLevel = riskLevel;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
public Double getreturnLevel() {
return returnLevel;
}
public void setReturnLevel(Double returnLevel) {
this.returnLevel = returnLevel;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
This my Activity
public class ProductActivity extends AppCompatActivity {
private RecyclerView rvView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
public List<ProductList> list;
Context context;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_list_of_product);
request(constructSignUpRequest());
rvView = (RecyclerView) findViewById(R.id.rv);
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
public BTNService.Api getApi() {
return getBTNService().getApi();
}
public BTNService getBTNService() {
return new BTNService(this);
}
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
Intent intent = new Intent(ProductActivity.this, ProductList.class);
startActivity(intent);
}
}
});
}
public ProductListRequest constructSignUpRequest() {
ProductListRequest request = new ProductListRequest();
request.setCode(Category);
return request;
}
}
This my Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CatalogueHolder> {
private Context context;
private List<ProductList> list;
public ProductAdapter(Context context, List<ProductList> list) {
this.context = context;
this.list = list;
}
#Override
public CatalogueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_product, parent, false);
CatalogueHolder catalogueHolder = new CatalogueHolder(itemView);
return catalogueHolder;
}
#Override
public void onBindViewHolder(CatalogueHolder holder, int position) {
final ProductList item = list.get(position);
holder.itemView.setTag(item);
holder.productName.setText(item.getName());
}
#Override
public int getItemCount() {
return list != null ? list.size() : 0;
}
public static class CatalogueHolder extends RecyclerView.ViewHolder {
#Bind(R.id.productname)
TextView productName;
#Bind(R.id.typeProduct)
TextView typeProduct;
#Bind(R.id.price)
TextView price;
#Bind(R.id.date)
TextView date;
public CatalogueHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
Sorry, if it's quite long. I have to show all my code to make it clear. I really need your help guys. Thanks
Set adapter inside onComplete method:
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
Intent intent = new Intent(ProductActivity.this, ProductList.class);
startActivity(intent);
}
}
});
}
i tried retrofit with simple json response which have [ {},{},{},{},{},{},] array of objects which works but when i tried retrofit with status:
{"ok",count: 4,count_total: 4,pages: 1,posts: [{},{},{},{}] }
I came up with null results ..plz find the correct solution how do i Call the retrofit for correct result.
pojo class`
public class Categories {
#SerializedName("status")
private int status;
#SerializedName("id")
private int id;
#SerializedName("type")
private String type;
#SerializedName("title")
private String title;
#SerializedName("content")
private String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
mainactivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<List<Categories>> call = apiService.response();
call.enqueue(new Callback<List<Categories>>() {
#Override
public void onResponse(Call<List<Categories>> call, Response<List<Categories>> response) {
List<Categories> movies = response.body();
recyclerView
.setAdapter(new MoviesAdapter(movies,
R.layout.list_item_movie, getApplicationContext()));
}
#Override
public void onFailure(Call<List<Categories>> call, Throwable t) {
}
});
}
apiclient.java
public class ApiClient {
public static final String BASE_URL = "http://androidaura.com/health/api/get_recent_posts/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
You should change your POJO to following:
Public class Model {
String status; // because "ok" is string not boolean
int count;
int count_total;
int pages;
List<Post> posts;
public class Post {
// add attribute of your old pojo
}
}
Also make sure your class attribute be same as Server response;