Related
I have the following JSON data i.e 10 objects in one array. I am fetching objects in recyclerview wihtout any error.
Now I need two things to do:
I want to show next page data i.e. (next 10 records on so on) when user scroll recyclerview.
I want to show total_quotes in recyclerview on every object. I am facing "LeadsMeta.getTotalQuotes()' on a null object reference" this error while showing total quotes.
I have commented that line in onBind in Adapter.
Please help me to solve these two problems. Many thanks in advance.
JSON Data
{
"meta":{
"code":200,
"message":"success",
"total_pages":247,
"current_page":1,
"total_items":2469,
"total_quotes":5
},
"data":[
{
"id":"4968",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Pune",
"name":"Shashikant ",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 21:53:38"
},
{
"id":"4963",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Bangalore",
"name":"Amani",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 20:46:03"
},
{
"id":"4962",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Delhi",
"name":"Mechanical Engineer",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 20:23:00"
},
{
"id":"4961",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Mumbai",
"name":"Ankush patil",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 20:20:20"
},
{
"id":"4960",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Delhi",
"name":"ER Vikash Thakur",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 20:17:32"
},
{
"id":"4957",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Kolkata",
"name":"Shiladitya Ghosh",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 20:09:44"
},
{
"id":"4956",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Delhi",
"name":"Vikash",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 20:08:44"
},
{
"id":"4953",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Rishikesh",
"name":"Rahul",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 19:51:17"
},
{
"id":"4950",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Pune",
"name":"Abhishek",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 19:43:27"
},
{
"id":"4949",
"topic":"Topic",
"sub_topic":"Sub Topic",
"city":"Chandigarh ",
"name":"K Singh ",
"quotes":"0",
"credits":"10",
"timestamp":"2021-01-05 19:40:36"
}
]
}
My Fragment:
public class LeadsFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
private static final String url = "myurl";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_leads, container, false);
recyclerView = view.findViewById(R.id.recyclerview);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
LeadModel leadsModelList = gson.fromJson(response, LeadModel.class);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
LeadsAdapter leadsAdapter = new LeadsAdapter(getContext(), leadsModelList, recyclerView);
recyclerView.setAdapter(leadsAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(stringRequest);
return view;
}
}
My Adapter:
public class LeadsAdapter extends RecyclerView.Adapter<LeadsAdapter.ViewHolder> {
Context context;
LeadModel leadsModelList;
RecyclerView recyclerView;
final View.OnClickListener onClickListener = new MyOnClickListener();
public LeadsAdapter(Context context, LeadModel leadsModelList, RecyclerView recyclerView) {
this.context = context;
this.leadsModelList = leadsModelList;
this.recyclerView = recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView name, topic, sub_topic, city, credits, quotes;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
topic = itemView.findViewById(R.id.tvTopic);
sub_topic = itemView.findViewById(R.id.tvSubTopic);
city = itemView.findViewById(R.id.tvLocation);
credits = itemView.findViewById(R.id.tvCredits);
quotes = itemView.findViewById(R.id.tvQuotes);
}
}
#NonNull
#Override
public LeadsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.lead_card, viewGroup, false);
view.setOnClickListener(onClickListener);
LeadsAdapter.ViewHolder viewHolder = new LeadsAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull LeadsAdapter.ViewHolder viewHolder, int position) {
viewHolder.name.setText(leadsModelList.getData().get(position).getName());
viewHolder.topic.setText(leadsModelList.getData().get(position).getTopic());
viewHolder.sub_topic.setText(leadsModelList.getData().get(position).getSubTopic());
viewHolder.city.setText(leadsModelList.getData().get(position).getCity());
viewHolder.credits.setText(leadsModelList.getData().get(position).getCredits()+ " Credits");
// viewHolder.quotes.setText(leadsModelList.getData().get(position).getQuotes()+"/"+ leadsModelList.getMeta().getTotalQuotes() +" Quotes");
}
#Override
public int getItemCount() {
return leadsModelList.getData().size();
}
}
}
}
Model Class:
public class LeadModel {
#SerializedName("leadsMeta")
#Expose
private LeadsMeta leadsMeta;
#SerializedName("data")
#Expose
private List<LeadsData> data = null;
public LeadsMeta getMeta() {
return leadsMeta;
}
public void setMeta(LeadsMeta leadsMeta) {
this.leadsMeta = leadsMeta;
}
public List<LeadsData> getData() {
return data;
}
public void setData(List<LeadsData> data) {
this.data = data;
}
}
Meta Class
public class LeadsMeta {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("message")
#Expose
private String message;
#SerializedName("total_pages")
#Expose
private Integer totalPages;
#SerializedName("current_page")
#Expose
private Integer currentPage;
#SerializedName("total_items")
#Expose
private Integer totalItems;
#SerializedName("total_quotes")
#Expose
private Integer totalQuotes;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getTotalPages() {
return totalPages;
}
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getTotalItems() {
return totalItems;
}
public void setTotalItems(Integer totalItems) {
this.totalItems = totalItems;
}
public Integer getTotalQuotes() {
return totalQuotes;
}
public void setTotalQuotes(Integer totalQuotes) {
this.totalQuotes = totalQuotes;
}
}
Data Class
public class LeadsData {
#SerializedName("id")
#Expose
private String id;
#SerializedName("topic")
#Expose
private String topic;
#SerializedName("sub_topic")
#Expose
private String subTopic;
#SerializedName("city")
#Expose
private String city;
#SerializedName("name")
#Expose
private String name;
#SerializedName("quotes")
#Expose
private String quotes;
#SerializedName("credits")
#Expose
private String credits;
#SerializedName("timestamp")
#Expose
private String timestamp;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getSubTopic() {
return subTopic;
}
public void setSubTopic(String subTopic) {
this.subTopic = subTopic;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuotes() {
return quotes;
}
public void setQuotes(String quotes) {
this.quotes = quotes;
}
public String getCredits() {
return credits;
}
public void setCredits(String credits) {
this.credits = credits;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
SerializedName for "meta" object should be "meta" in your LeadModel class.
public class LeadModel {
//#SerializedName("leadsMeta")
#SerializedName("meta")
#Expose
private LeadsMeta leadsMeta;}
I want to show next page data
Please use recyclerView.addOnScrollListener on your recyclerview. When user scrolls and reaches the last item, you need to load more 10 items and append the list to existing list
public class LeadsFragment extends Fragment {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
private static final String url = "myurl";
boolean isLoading = false; // For Tracking
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
......
........
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (!isLoading) {
if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == yourList.size() - 1) {
// Last item reached
loadMore(); // Note this method
isLoading = true;
}
}
}
});
private void loadMore() {
// Make http Request
// append the new data to LeadsData
// notifyAdapter items changed
// set isLoading = false
}
I am facing "LeadsMeta.getTotalQuotes()' on a null object reference"
Its because your serialized name in LeadModel should be as per your json
#SerializedName("meta")
For your first problem:
You need to check this code. In MainActivity.java class here is a method loadMore(). In your case you need to do your API call to load 10 more items and then notify your adapter that you have new items and it will load them in your list. Thats how you can implement your recyclerview with endless items.
For 2nd problem:
You should change leadsMeta to meta in your #SerializedName.
Here is your edited class:
public class LeadModel {
#SerializedName("meta")
#Expose
private LeadsMeta leadsMeta;
#SerializedName("data")
#Expose
private List<LeadsData> data = null;
public LeadsMeta getMeta() {
return leadsMeta;
}
public void setMeta(LeadsMeta leadsMeta) {
this.leadsMeta = leadsMeta;
}
public List<LeadsData> getData() {
return data;
}
public void setData(List<LeadsData> data) {
this.data = data;
}
}
I'm trying to get all the JSON result into my listview. I have successfully retrieved the data but it keeps only shows one data (example if JNE, only showing OKE result). I'm using Retrofit. Below is the example JSON data from the documentation that I want to show all in my listview. Please help me why it is not showing all the result. Thank you.
{
"rajaongkir":{
"query":{
"origin":"501",
"destination":"114",
"weight":1700,
"courier":"jne"
},
"status":{
"code":200,
"description":"OK"
},
"origin_details":{
"city_id":"501",
"province_id":"5",
"province":"DI Yogyakarta",
"type":"Kota",
"city_name":"Yogyakarta",
"postal_code":"55000"
},
"destination_details":{
"city_id":"114",
"province_id":"1",
"province":"Bali",
"type":"Kota",
"city_name":"Denpasar",
"postal_code":"80000"
},
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
}
}
My Call
public void getCoast(String origin,
String destination,
String weight,
String courier) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiUrl.URL_ROOT_HTTPS)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ItemCost> call = service.getCost(
"c5333cdcc37b3511c909088d99587fd8",
origin,
destination,
weight,
courier
);
call.enqueue(new Callback<ItemCost>() {
#Override
public void onResponse(Call<ItemCost> call, Response<ItemCost> response) {
Log.v("wow", "json : " + new Gson().toJson(response));
progressDialog.dismiss();
if (response.isSuccessful()) {
int statusCode = response.body().getRajaongkir().getStatus().getCode();
if (statusCode == 200) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = inflater.inflate(R.layout.custom_results, null);
alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Result Cost");
alert.setMessage("this result your search");
alert.setView(alertLayout);
alert.setCancelable(true);
ad = alert.show();
String originCity = response.body().getRajaongkir().getOriginDetails().getCityName();
String originPostalCode = response.body().getRajaongkir().getOriginDetails().getPostalCode();
String destinationCity = response.body().getRajaongkir().getDestinationDetails().getCityName();
String destinationPostalCode = response.body().getRajaongkir().getDestinationDetails().getPostalCode();
//results
List<com.bagicode.cekongkir.model.cost.Result> ListResults = response.body().getRajaongkir().getResults();
//costs
List<com.bagicode.cekongkir.model.cost.Cost> ListCosts = response.body().getRajaongkir().getResults().get(0).getCosts();
//cost
List<com.bagicode.cekongkir.model.cost.Cost_> ListCost = response.body().getRajaongkir().getResults().get(0).getCosts().get(0).getCost();
mListView = (ListView) alertLayout.findViewById(R.id.listItem);
adapter_results = new ResultsAdapter(MainActivity.this, originCity, originPostalCode, destinationCity, destinationPostalCode, ListResults, ListCosts, ListCost);
mListView.setAdapter(adapter_results);
mListView.setClickable(true);
adapter_results.notifyDataSetChanged();
} else {
String message = response.body().getRajaongkir().getStatus().getDescription();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
} else {
String error = "Error Retrive Data from Server !!!";
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ItemCost> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Message : Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Api Interface
// Cost
#FormUrlEncoded
#POST("cost")
Call<ItemCost> getCost (#Field("key") String Token,
#Field("origin") String origin,
#Field("destination") String destination,
#Field("weight") String weight,
#Field("courier") String courier);
Pojo
ItemCost
public class ItemCost {
#SerializedName("rajaongkir")
#Expose
private Rajaongkir rajaongkir;
public Rajaongkir getRajaongkir() {
return rajaongkir;
}
public void setRajaongkir(Rajaongkir rajaongkir) {
this.rajaongkir = rajaongkir;
}
}
rajaOngkir Pojo (List)
public class Rajaongkir {
#SerializedName("query")
#Expose
private Query query;
#SerializedName("status")
#Expose
private Status status;
#SerializedName("origin_details")
#Expose
private OriginDetails originDetails;
#SerializedName("destination_details")
#Expose
private DestinationDetails destinationDetails;
#SerializedName("results")
#Expose
private List<Result> results = null;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public OriginDetails getOriginDetails() {
return originDetails;
}
public void setOriginDetails(OriginDetails originDetails) {
this.originDetails = originDetails;
}
public DestinationDetails getDestinationDetails() {
return destinationDetails;
}
public void setDestinationDetails(DestinationDetails destinationDetails) {
this.destinationDetails = destinationDetails;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
Results List Pojo
public class Result {
#SerializedName("code")
#Expose
private String code;
#SerializedName("name")
#Expose
private String name;
#SerializedName("costs")
#Expose
private List<Cost> costs = null;
public Result(String code, String name, List<Cost> costs) {
this.code = code;
this.name = name;
this.costs = costs;
}
public Result(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Cost> getCosts() {
return costs;
}
public void setCosts(List<Cost> costs) {
this.costs = costs;
}
}
Costs List Pojo
public class Cost {
#SerializedName("service")
#Expose
private String service;
#SerializedName("description")
#Expose
private String description;
#SerializedName("cost")
#Expose
private List<Cost_> cost = null;
public Cost(String service, String description) {
this.service = service;
this.description = description;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Cost_> getCost() {
return cost;
}
public void setCost(List<Cost_> cost) {
this.cost = cost;
}
}
cost list Pojo
public class Cost_ {
#SerializedName("value")
#Expose
private Integer value;
#SerializedName("etd")
#Expose
private String etd;
#SerializedName("note")
#Expose
private String note;
public Cost_(Integer value, String etd, String note) {
this.value = value;
this.etd = etd;
this.note = note;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getEtd() {
return etd;
}
public void setEtd(String etd) {
this.etd = etd;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
ListView Adapter
public class ResultsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Result> resulsItems;
private List<Cost> costsItems;
private List<Cost_> costItems;
TextView tv_origin, tv_destination, tv_expedisi, tv_coast, tv_time;
private String originCity, destinationCity, originPostalCode, destinationPostalCode;
public ResultsAdapter(MainActivity mainActivity, String originCity, String originPostalCode, String destinationCity, String destinationPostalCode, List<Result> listResults, List<Cost> listCosts, List<Cost_> listCost) {
this.activity = mainActivity;
this.originCity = originCity;
this.originPostalCode = originPostalCode;
this.destinationCity = destinationCity;
this.destinationPostalCode = destinationPostalCode;
this.resulsItems = listResults;
this.costsItems = listCosts;
this.costItems = listCost;
}
#Override
public int getCount() {
return resulsItems.size();
}
#Override
public Object getItem(int location) {
return resulsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.item_results, null);
tv_origin = (TextView) convertView.findViewById(R.id.tv_origin);
tv_destination = (TextView) convertView.findViewById(R.id.tv_destination);
tv_expedisi = convertView.findViewById(R.id.tv_expedisi);
tv_coast = convertView.findViewById(R.id.tv_coast);
tv_time = convertView.findViewById(R.id.tv_time);
results = resulsItems.get(i);
costs = costsItems.get(i);
cost = costItems.get(i);
tv_origin.setText(originCity);
tv_destination.setText(destinationCity);
tv_expedisi.setText(results.getName());
tv_coast.setText(String.valueOf(cost.getValue()));
tv_time.setText(cost.getEtd());
return convertView;
}
}
ACtual Response Log
{"body":{"rajaongkir":{"destination_details":{"city_id":"114","city_name":"Denpasar","postal_code":"80227","province":"Bali","province_id":"1","type":"Kota"},"origin_details":{"city_id":"501","city_name":"Yogyakarta","postal_code":"55111","province":"DI Yogyakarta","province_id":"5","type":"Kota"},"query":{"courier":"jne","destination":"114","key":"c5333cdcc37b3511c909088d99587fd8","origin":"501","weight":1000},"results":[{"code":"jne","costs":[{"cost":[{"etd":"4-5","note":"","value":26000}],"description":"Ongkos Kirim Ekonomis","service":"OKE"},{"cost":[{"etd":"2-3","note":"","value":28000}],"description":"Layanan Reguler","service":"REG"},{"cost":[{"etd":"1-1","note":"","value":43000}],"description":"Yakin Esok Sampai","service":"YES"}],"name":"Jalur Nugraha Ekakurir (JNE)"}],"status":{"code":200,"description":"OK"}}},"rawResponse":{"body":{"contentLength":823,"contentType":{"mediaType":"application/json","subtype":"json","type":"application"}},"code":200,"handshake":{"cipherSuite":"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","localCertificates":[],"peerCertificates":[{"hash":-1,"type":"X.509"},{"hash":-1,"type":"X.509"}],"tlsVersion":"TLS_1_2"},"headers":{"namesAndValues":["Date","Thu, 02 May 2019 13:09:21 GMT","Server","Apache/2.4.7 (Ubuntu)","Content-Length","823","Keep-Alive","timeout\u003d15, max\u003d100","Connection","Keep-Alive","Content-Type","application/json"]},"message":"OK","networkResponse":{"code":200,"handshake":{"cipherSuite":"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","localCertificates":[],"peerCertificates":[{"hash":-1,"type":"X.509"},{"hash":-1,"type":"X.509"}],"tlsVersion":"TLS_1_2"},"headers":{"namesAndValues":["Date","Thu, 02 May 2019 13:09:21 GMT","Server","Apache/2.4.7 (Ubuntu)","Content-Length","823","Keep-Alive","timeout\u003d15, max\u003d100","Connection","Keep-Alive","Content-Type","application/json"]},"message":"OK","protocol":"HTTP_1_1","receivedResponseAtMillis":1556802600578,"request":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"cacheControl":{"isPrivate":false,"isPublic":false,"maxAgeSeconds":-1,"maxStaleSeconds":-1,"minFreshSeconds":-1,"mustRevalidate":false,"noCache":false,"noStore":false,"noTransform":false,"onlyIfCached":false,"sMaxAgeSeconds":-1},"headers":{"namesAndValues":["Content-Type","application/x-www-form-urlencoded","Content-Length","87","Host","api.rajaongkir.com","Connection","Keep-Alive","Accept-Encoding","gzip","User-Agent","okhttp/3.3.0"]},"method":"POST","tag":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"sentRequestAtMillis":1556802600415},"protocol":"HTTP_1_1","receivedResponseAtMillis":1556802600578,"request":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":["Content-Type","application/x-www-form-urlencoded","Content-Length","87"]},"method":"POST","tag":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"sentRequestAtMillis":1556802600415}}
public void getCoast(String origin,
String destination,
String weight,
String courier) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiUrl.URL_ROOT_HTTPS)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ItemCost> call = service.getCost(
"c5333cdcc37b3511c909088d99587fd8",
origin,
destination,
weight,
courier
);
call.enqueue(new Callback<ItemCost>() {
#Override
public void onResponse(Call<ItemCost> call, Response<ItemCost> response) {
Log.v("wow", "json : " + new Gson().toJson(response));
progressDialog.dismiss();
if (response.isSuccessful()) {
int statusCode = response.body().getRajaongkir().getStatus().getCode();
if (statusCode == 200) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = inflater.inflate(R.layout.custom_results, null);
alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Result Cost");
alert.setMessage("this result your search");
alert.setView(alertLayout);
alert.setCancelable(true);
ad = alert.show();
String originCity = response.body().getRajaongkir().getOriginDetails().getCityName();
String originPostalCode = response.body().getRajaongkir().getOriginDetails().getPostalCode();
String destinationCity = response.body().getRajaongkir().getDestinationDetails().getCityName();
String destinationPostalCode = response.body().getRajaongkir().getDestinationDetails().getPostalCode();
//results
List<com.bagicode.cekongkir.model.cost.Result> ListResults = response.body().getRajaongkir().getResults();
//costs
List<com.bagicode.cekongkir.model.cost.Cost> ListCosts = response.body().getRajaongkir().getResults().get(0).getCosts();
//cost
List<com.bagicode.cekongkir.model.cost.Cost_> ListCost = response.body().getRajaongkir().getResults().get(0).getCosts().get(0).getCost();
mListView = (ListView) alertLayout.findViewById(R.id.listItem);
adapter_results = new ResultsAdapter(MainActivity.this, originCity, originPostalCode, destinationCity, destinationPostalCode, ListResults, ListCosts, ListCost);
mListView.setAdapter(adapter_results);
mListView.setClickable(true);
adapter_results.notifyDataSetChanged();
} else {
String message = response.body().getRajaongkir().getStatus().getDescription();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
} else {
String error = "Error Retrive Data from Server !!!";
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ItemCost> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Message : Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have following JSON returned from server
{
"matches": [
{
"unique_id": 1122278,
"date": "2018-01-24T00:00:00.000Z",
"team-2": "India",
"team-1": "South Africa",
"type": "Test",
"dateTimeGMT": "2018-01-24T08:00:00.000Z",
"squad": true,
"toss_winner_team": "India",
"matchStarted": true
},
{
"unique_id": 1116929,
"team-2": "India Under-19s",
"team-1": "Bangladesh Under-19s",
"type": "YouthODI",
"date": "2018-01-25T00:00:00.000Z",
"dateTimeGMT": "2018-01-25T21:30:00.000Z",
"squad": true,
"toss_winner_team": "India Under-19s",
"winner_team": "India Under-19s",
"matchStarted": true
},
{
"unique_id": 1115781,
"team-2": "England",
"team-1": "New Zealand",
"type": "Test",
"date": "2018-03-29T00:00:00.000Z",
"dateTimeGMT": "2018-03-29T22:00:00.000Z",
"squad": false,
"matchStarted": false
}
],
"v": "1",
"ttl": 43,
"provider": {
"source": "Various",
"url": "https://cricapi.com/",
"pubDate": "2018-01-27T13:18:55.717Z"
},
"creditsLeft": 250
}
Using Volley library and gson.
I am trying to push JSON array match to Match Model(Pojo). I think I can insert it using a loop, but there any other way to add all JSON array to model?
public class Main2Activity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Match> matches;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recylcer_1);
recyclerView=(RecyclerView) findViewById(R.id.recyler);
myAdapter=new MyAdapter(matches);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAnimation(n);
recyclerView.setAdapter(myAdapter);
callCricket();
}
public void callCricket() {
CallApi callApi = new CallApi();
callApi.setVolleyInterface(new VolleyInterface() {
#Override
public void onSucess(String string) {
Log.d("ApiCall_success", string);
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Match>>(){}.getType();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("matches");
matches.addAll(gson.fromJson(jsonArray,type));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String string) {
}
});
}
}
I have tried using gson but I got an error.
Create pojo classes as below as per your JSON by using jsonschema2pojo:
There are No Need of loop in GSON to insert data in pojo classes.
Example.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
#SerializedName("v")
#Expose
private String v;
#SerializedName("ttl")
#Expose
private Integer ttl;
#SerializedName("provider")
#Expose
private Provider provider;
#SerializedName("creditsLeft")
#Expose
private Integer creditsLeft;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
public String getV() {
return v;
}
public void setV(String v) {
this.v = v;
}
public Integer getTtl() {
return ttl;
}
public void setTtl(Integer ttl) {
this.ttl = ttl;
}
public Provider getProvider() {
return provider;
}
public void setProvider(Provider provider) {
this.provider = provider;
}
public Integer getCreditsLeft() {
return creditsLeft;
}
public void setCreditsLeft(Integer creditsLeft) {
this.creditsLeft = creditsLeft;
}
}
Match.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Match {
#SerializedName("unique_id")
#Expose
private Integer uniqueId;
#SerializedName("date")
#Expose
private String date;
#SerializedName("team-2")
#Expose
private String team2;
#SerializedName("team-1")
#Expose
private String team1;
#SerializedName("type")
#Expose
private String type;
#SerializedName("dateTimeGMT")
#Expose
private String dateTimeGMT;
#SerializedName("squad")
#Expose
private Boolean squad;
#SerializedName("toss_winner_team")
#Expose
private String tossWinnerTeam;
#SerializedName("matchStarted")
#Expose
private Boolean matchStarted;
#SerializedName("winner_team")
#Expose
private String winnerTeam;
public Integer getUniqueId() {
return uniqueId;
}
public void setUniqueId(Integer uniqueId) {
this.uniqueId = uniqueId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDateTimeGMT() {
return dateTimeGMT;
}
public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}
public Boolean getSquad() {
return squad;
}
public void setSquad(Boolean squad) {
this.squad = squad;
}
public String getTossWinnerTeam() {
return tossWinnerTeam;
}
public void setTossWinnerTeam(String tossWinnerTeam) {
this.tossWinnerTeam = tossWinnerTeam;
}
public Boolean getMatchStarted() {
return matchStarted;
}
public void setMatchStarted(Boolean matchStarted) {
this.matchStarted = matchStarted;
}
public String getWinnerTeam() {
return winnerTeam;
}
public void setWinnerTeam(String winnerTeam) {
this.winnerTeam = winnerTeam;
}
}
Provider.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Provider {
#SerializedName("source")
#Expose
private String source;
#SerializedName("url")
#Expose
private String url;
#SerializedName("pubDate")
#Expose
private String pubDate;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
}
In your Activity class do coding like this :
public static final String TAG = DoctorHome.class.getSimpleName();
ArrayList<DoctorsCatPojo> doctorCatList = new ArrayList<>();
DoctorsCatAdapter doctorsCatAdapter;
RecyclerView recyclerView;
private void getDoctorCategory() {
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
String url = Constant.DOCTOR_CATEGORY;
Log.e("URL",""+url);
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("onResponse",""+response);
try {
status = response.getString("status");
if(status.equals("success")){
String info = response.getString("list");
JSONArray jsonArray = new JSONArray(info);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<DoctorsCatPojo>>() {
}.getType();
doctorCatList = gson.fromJson(jsonArray.toString(), listType);
if(doctorCatList!=null && doctorCatList.size()!=0){
doctorsCatAdapter = new DoctorsCatAdapter(DoctorHome.this,doctorCatList);
recyclerView.setAdapter(doctorsCatAdapter);
Log.d(TAG, response.toString());
}
}
else {
message = response.getString("message");
// Toast.makeText(getApplicationContext(),""+message,Toast.LENGTH_SHORT).show();
pDialog.hide();
}
} catch (Exception e) {
Log.e("Exception",""+e);
e.printStackTrace();
}
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error",""+error.getMessage());
pDialog.hide();
}
});
AppController.getInstance(DoctorHome.this).addToRequestQueue(request, "doctor_category");
}
your adapter class will be like this :
public class DoctorsCatAdapter extends RecyclerView.Adapter<DoctorsCatAdapter.MyViewHolder> {
ArrayList <DoctorsCatPojo> doctorCatList;
Context context;
public DoctorsCatAdapter( Context context,ArrayList<DoctorsCatPojo> doctorCatList) {
this.doctorCatList = doctorCatList;
this.context= context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctors_category_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DoctorsCatPojo doc = doctorCatList.get(position);
// holder.doctorsCatImg.setImageURI(doc.getCategory_img());
if(doc.getCategory_name()!=null){
holder.doctorsCatName.setText(doc.getCategory_name());
}
if(doc.getCategory_img()!=null){
Picasso.with(context)
.load(doc.getCategory_img().replace(" ", "%20").trim())
.placeholder(R.drawable.no_image)
.into(holder.doctorsCatImg);
}
}
#Override
public int getItemCount() {
return doctorCatList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView doctorsCatImg;
TextView doctorsCatName;
MyViewHolder(final View view) {
super(view);
itemView.setOnClickListener(this);
doctorsCatImg = (ImageView)view.findViewById(R.id.doctorsCatImg);
doctorsCatName = (TextView) view.findViewById(R.id.doctorsCatName);
}
#Override
public void onClick(View view) {
doctorCatList.get(getPosition()).getCategory_id();
((DoctorHome)context).callDoctorListActivity(doctorCatList.get(getPosition()).getCategory_id(),doctorCatList.get(getPosition()).getCategory_name());
}
}
}
I’ve been trying to get recycler view working with retrofit. I seem to be pulling in the JSON fine from within getRecipes() method, and my logs are showing me that the some data is there.
However, when I call my getRecipes() method from onCreate(), something seems to be going wrong. When I check to see if my recipeList array contains my JSON results within onCreate, it is telling me it is empty. Why is it doing this if my logs within my getRecipes() method are showing me that data is there...?
Not sure if it is an issue with my recycler view or what I am doing with retrofit, or something else. Been trying for days to figure out, so any advice would be greatly appreciated.
JSON
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
public class ItemListActivity extends AppCompatActivity {
private boolean mTwoPane;
public static final String LOG_TAG = "myLogs";
public static List<Recipe> recipeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getRecipes();
setContentView(R.layout.activity_item_list);
getRecipes();
//Logging to check that recipeList contains data
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.item_list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
}
public void getRecipes(){
String ROOT_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/";
Retrofit RETROFIT = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RecipeService service = RETROFIT.create(RecipeService.class);
Call<List<Recipe>> call = service.getMyJson();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {
Log.d(LOG_TAG, "Got here");
if (!response.isSuccessful()) {
Log.d(LOG_TAG, "No Success");
}
Log.d(LOG_TAG, "Got here");
recipeList = response.body();
//Logging to check data is there
Log.v(LOG_TAG, "LOGS" + recipeList.size());
for (int i = 0; i < recipeList.size(); i++) {
String newString = recipeList.get(i).getName();
Ingredients[] ingredients = recipeList.get(i).getIngredients();
for(int j = 0; j < ingredients.length; j++){
Log.d(LOG_TAG, ingredients[j].getIngredient());
}
Steps[] steps = recipeList.get(i).getSteps();
for(int k = 0; k < steps.length; k++){
Log.d(LOG_TAG, steps[k].getDescription());
}
Log.d(LOG_TAG, newString);
}
}
#Override
public void onFailure(Call<List<Recipe>> call, Throwable t) {
Log.e("getRecipes throwable: ", t.getMessage());
t.printStackTrace();
}
});
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<Recipe> mValues;
public SimpleItemRecyclerViewAdapter(List<Recipe> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View mView;
public TextView mContentView;
public Recipe mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
RecipeService
public interface RecipeService {
#GET("baking.json")
Call<List<Recipe>> getMyJson();}
Models
Recipe
public class Recipe{
private Ingredients[] ingredients;
private String id;
private String servings;
private String name;
private String image;
private Steps[] steps;
public Ingredients[] getIngredients ()
{
return ingredients;
}
public void setIngredients (Ingredients[] ingredients)
{
this.ingredients = ingredients;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getServings ()
{
return servings;
}
public void setServings (String servings)
{
this.servings = servings;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
public Steps[] getSteps ()
{
return steps;
}
public void setSteps (Steps[] steps)
{
this.steps = steps;
}
#Override
public String toString()
{
return "[ingredients = "+ingredients+", id = "+id+", servings = "+servings+", name = "+name+", image = "+image+", steps = "+steps+"]";
}}
Ingredients
public class Ingredients{
private String measure;
private String ingredient;
private String quantity;
public String getMeasure ()
{
return measure;
}
public void setMeasure (String measure)
{
this.measure = measure;
}
public String getIngredient ()
{
return ingredient;
}
public void setIngredient (String ingredient)
{
this.ingredient = ingredient;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
#Override
public String toString()
{
return "[measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]";
}}
Steps
public class Steps{
private String id;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getShortDescription ()
{
return shortDescription;
}
public void setShortDescription (String shortDescription)
{
this.shortDescription = shortDescription;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getVideoURL ()
{
return videoURL;
}
public void setVideoURL (String videoURL)
{
this.videoURL = videoURL;
}
public String getThumbnailURL ()
{
return thumbnailURL;
}
public void setThumbnailURL (String thumbnailURL)
{
this.thumbnailURL = thumbnailURL;
}
#Override
public String toString()
{
return "[id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]";
}}
Logs
https://gist.github.com/2triggers/12b6eeb32ed8909ab50bbadd4742d7f7
this will be empty always because this line will execute before getting the response from a server.
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Better call this after this line recipeList = response.body();
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
it is because you are sending the recipelist into the adapter before even it is populated , after you are sending the recipelist into the adapter which is empty you are populating your recipelist from getRecipes method, you might be wondering you have declared the getRecipes method before even you are assigning the recipelist to adapter so how come it is empty, yea but the fact is your getRecipes work on background thread so even before your recipelist gets populated your adapter assignment takes place on the main thread so you are basically assigning the empty list, one thing you can do is notify when the adapter when the data changes or when the the recipelist is filled with data that is from within the getRecipe method.
when you assign the recipelist = response.body right after this you can notify the adapter
or move this two lines
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
right after the
recipelist = response.body;
in getRecipes method
Try create the Constructor with all atributes from your Recipe.class
Like:
public Ingredients(String measure, String ingredients, String quantity ){
this.measure = measure;
this.ingredients = ingredients;
this.quantity = quantity
}
Do same in all class where make up your object of list.
I am using Retrofit for parsing data in recycler view. I am not knowledgable about Retrofit.
My Json Fromat:
[{"id":3106,"sku":"62974","name":"NESTLE CERELAC STG 1 WHEAT 300G","attribute_set_id":4,"price":164,"status":1,"visibility":4,"type_id":"simple","created_at":"2017-08-16 16:15:30","updated_at":"2017-09-14 06:54:36","extension_attributes":{"stock_item":{"item_id":5627,"product_id":3106,"stock_id":1,"qty":3,"is_in_stock":true,"is_qty_decimal":false,"show_default_notification_message":false,"use_config_min_qty":true,"min_qty":0,"use_config_min_sale_qty":1,"min_sale_qty":1,"use_config_max_sale_qty":true,"max_sale_qty":10000,"use_config_backorders":true,"backorders":0,"use_config_notify_stock_qty":true,"notify_stock_qty":1,"use_config_qty_increments":true,"qty_increments":0,"use_config_enable_qty_inc":true,"enable_qty_increments":false,"use_config_manage_stock":true,"manage_stock":true,"low_stock_date":null,"is_decimal_divided":false,"stock_status_changed_auto":0}},"product_links":[],"options":[],"media_gallery_entries":[{"id":1127,"media_type":"image","label":"","position":1,"disabled":false,"types":["image","small_image","thumbnail","swatch_image"],"file":"\/6\/2\/62974.png"}],"tier_prices":[],"custom_attributes":[{"attribute_code":"description","value":"
NESTLE CERELAC STG 1 WHEAT 300G<\/p>"},{"attribute_code":"short_description","value":"
NESTLE CERELAC STG 1 WHEAT 300G<\/p>"},{"attribute_code":"special_price","value":"160.7200"},{"attribute_code":"special_from_date","value":"2017-08-17 20:17:57"},{"attribute_code":"meta_title","value":"NESTLE CERELAC STG 1 WHEAT 300G"},{"attribute_code":"meta_description","value":"NESTLE CERELAC STG 1 WHEAT 300G"},{"attribute_code":"image","value":"\/6\/2\/62974.png"},{"attribute_code":"small_image","value":"\/6\/2\/62974.png"},{"attribute_code":"thumbnail","value":"\/6\/2\/62974.png"},{"attribute_code":"news_from_date","value":"2017-08-17 20:17:57"},{"attribute_code":"custom_design_from","value":"2017-08-17 20:17:57"},{"attribute_code":"category_ids","value":["56","631"]},{"attribute_code":"options_container","value":"container2"},{"attribute_code":"required_options","value":"0"},{"attribute_code":"has_options","value":"0"},{"attribute_code":"msrp_display_actual_price_type","value":"0"},{"attribute_code":"url_key","value":"nestle-cerelac-stg-1-wheat-300g"},{"attribute_code":"gift_message_available","value":"2"},{"attribute_code":"tax_class_id","value":"2"},{"attribute_code":"swatch_image","value":"\/6\/2\/62974.png"}]}
i have get the name, sku, id successfully using below code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private RecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_retrofit);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
// recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
requestJsonObject();
}
private void requestJsonObject(){
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://alagendransupermart.com/mageapi/cat_product.php?cid=83";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<ItemObject> posts = new ArrayList<ItemObject>();
posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
}
Adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_retrofit, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.songTitle.setText("Product Name: " + itemList.get(position).getSongTitle());
holder.songYear.setText("ID: " + itemList.get(position).getSongYear());
holder.songAuthor.setText("SKU: " + itemList.get(position).getSongAuthor());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
Getter and setter:
public class ItemObject {
#SerializedName("name")
private String songTitle;
#SerializedName("id")
private String songYear;
#SerializedName("sku")
private String songAuthor;
public ItemObject(String songTitle, String songYear, String songAuthor) {
this.songTitle = songTitle;
this.songYear = songYear;
this.songAuthor = songAuthor;
}
public String getSongTitle() {
return songTitle;
}
public String getSongYear() {
return songYear;
}
public String getSongAuthor() {
return songAuthor;
}
}
But how can I get the values inside the next array name like parameters and there are more than 5 attributes with same name but with different values.
You should add to ItemObject :
#SerializedName("extension_attributes")
private ExtensionAttributes extensionAttributes;
ExtensionAttributes.java:
public class ExtensionAttributes {
#SerializedName("stock_item")
#Expose
private StockItem stockItem;
public StockItem getStockItem() {
return stockItem;
}
public void setStockItem(StockItem stockItem) {
this.stockItem = stockItem;
}
}
StockItem.java:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StockItem {
#SerializedName("item_id")
#Expose
private Integer itemId;
#SerializedName("product_id")
#Expose
private Integer productId;
#SerializedName("stock_id")
#Expose
private Integer stockId;
#SerializedName("qty")
#Expose
private Integer qty;
#SerializedName("is_in_stock")
#Expose
private Boolean isInStock;
#SerializedName("is_qty_decimal")
#Expose
private Boolean isQtyDecimal;
#SerializedName("show_default_notification_message")
#Expose
private Boolean showDefaultNotificationMessage;
#SerializedName("use_config_min_qty")
#Expose
private Boolean useConfigMinQty;
#SerializedName("min_qty")
#Expose
private Integer minQty;
#SerializedName("use_config_min_sale_qty")
#Expose
private Integer useConfigMinSaleQty;
#SerializedName("min_sale_qty")
#Expose
private Integer minSaleQty;
#SerializedName("use_config_max_sale_qty")
#Expose
private Boolean useConfigMaxSaleQty;
#SerializedName("max_sale_qty")
#Expose
private Integer maxSaleQty;
#SerializedName("use_config_backorders")
#Expose
private Boolean useConfigBackorders;
#SerializedName("backorders")
#Expose
private Integer backorders;
#SerializedName("use_config_notify_stock_qty")
#Expose
private Boolean useConfigNotifyStockQty;
#SerializedName("notify_stock_qty")
#Expose
private Integer notifyStockQty;
#SerializedName("use_config_qty_increments")
#Expose
private Boolean useConfigQtyIncrements;
#SerializedName("qty_increments")
#Expose
private Integer qtyIncrements;
#SerializedName("use_config_enable_qty_inc")
#Expose
private Boolean useConfigEnableQtyInc;
#SerializedName("enable_qty_increments")
#Expose
private Boolean enableQtyIncrements;
#SerializedName("use_config_manage_stock")
#Expose
private Boolean useConfigManageStock;
#SerializedName("manage_stock")
#Expose
private Boolean manageStock;
#SerializedName("low_stock_date")
#Expose
private Object lowStockDate;
#SerializedName("is_decimal_divided")
#Expose
private Boolean isDecimalDivided;
#SerializedName("stock_status_changed_auto")
#Expose
private Integer stockStatusChangedAuto;
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getStockId() {
return stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
public Boolean getIsInStock() {
return isInStock;
}
public void setIsInStock(Boolean isInStock) {
this.isInStock = isInStock;
}
public Boolean getIsQtyDecimal() {
return isQtyDecimal;
}
public void setIsQtyDecimal(Boolean isQtyDecimal) {
this.isQtyDecimal = isQtyDecimal;
}
public Boolean getShowDefaultNotificationMessage() {
return showDefaultNotificationMessage;
}
public void setShowDefaultNotificationMessage(Boolean showDefaultNotificationMessage) {
this.showDefaultNotificationMessage = showDefaultNotificationMessage;
}
public Boolean getUseConfigMinQty() {
return useConfigMinQty;
}
public void setUseConfigMinQty(Boolean useConfigMinQty) {
this.useConfigMinQty = useConfigMinQty;
}
public Integer getMinQty() {
return minQty;
}
public void setMinQty(Integer minQty) {
this.minQty = minQty;
}
public Integer getUseConfigMinSaleQty() {
return useConfigMinSaleQty;
}
public void setUseConfigMinSaleQty(Integer useConfigMinSaleQty) {
this.useConfigMinSaleQty = useConfigMinSaleQty;
}
public Integer getMinSaleQty() {
return minSaleQty;
}
public void setMinSaleQty(Integer minSaleQty) {
this.minSaleQty = minSaleQty;
}
public Boolean getUseConfigMaxSaleQty() {
return useConfigMaxSaleQty;
}
public void setUseConfigMaxSaleQty(Boolean useConfigMaxSaleQty) {
this.useConfigMaxSaleQty = useConfigMaxSaleQty;
}
public Integer getMaxSaleQty() {
return maxSaleQty;
}
public void setMaxSaleQty(Integer maxSaleQty) {
this.maxSaleQty = maxSaleQty;
}
public Boolean getUseConfigBackorders() {
return useConfigBackorders;
}
public void setUseConfigBackorders(Boolean useConfigBackorders) {
this.useConfigBackorders = useConfigBackorders;
}
public Integer getBackorders() {
return backorders;
}
public void setBackorders(Integer backorders) {
this.backorders = backorders;
}
public Boolean getUseConfigNotifyStockQty() {
return useConfigNotifyStockQty;
}
public void setUseConfigNotifyStockQty(Boolean useConfigNotifyStockQty) {
this.useConfigNotifyStockQty = useConfigNotifyStockQty;
}
public Integer getNotifyStockQty() {
return notifyStockQty;
}
public void setNotifyStockQty(Integer notifyStockQty) {
this.notifyStockQty = notifyStockQty;
}
public Boolean getUseConfigQtyIncrements() {
return useConfigQtyIncrements;
}
public void setUseConfigQtyIncrements(Boolean useConfigQtyIncrements) {
this.useConfigQtyIncrements = useConfigQtyIncrements;
}
public Integer getQtyIncrements() {
return qtyIncrements;
}
public void setQtyIncrements(Integer qtyIncrements) {
this.qtyIncrements = qtyIncrements;
}
public Boolean getUseConfigEnableQtyInc() {
return useConfigEnableQtyInc;
}
public void setUseConfigEnableQtyInc(Boolean useConfigEnableQtyInc) {
this.useConfigEnableQtyInc = useConfigEnableQtyInc;
}
public Boolean getEnableQtyIncrements() {
return enableQtyIncrements;
}
public void setEnableQtyIncrements(Boolean enableQtyIncrements) {
this.enableQtyIncrements = enableQtyIncrements;
}
public Boolean getUseConfigManageStock() {
return useConfigManageStock;
}
public void setUseConfigManageStock(Boolean useConfigManageStock) {
this.useConfigManageStock = useConfigManageStock;
}
public Boolean getManageStock() {
return manageStock;
}
public void setManageStock(Boolean manageStock) {
this.manageStock = manageStock;
}
public Object getLowStockDate() {
return lowStockDate;
}
public void setLowStockDate(Object lowStockDate) {
this.lowStockDate = lowStockDate;
}
public Boolean getIsDecimalDivided() {
return isDecimalDivided;
}
public void setIsDecimalDivided(Boolean isDecimalDivided) {
this.isDecimalDivided = isDecimalDivided;
}
public Integer getStockStatusChangedAuto() {
return stockStatusChangedAuto;
}
public void setStockStatusChangedAuto(Integer stockStatusChangedAuto) {
this.stockStatusChangedAuto = stockStatusChangedAuto;
}
}
I hope you can use this instrument next time.