ListView is not showing all JSON data using Retrofit - java

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();
}
});
}

Related

How to create a retrofit2 array in android studio?

I took this information out of a JSON and initialized it, but I don't understand how I can get the data out of the form to pass them to the cardView afterward. Or is there an easier way?
MainActivity
public class MainActivity extends AppCompatActivity {
Context context;
Example example;
Response responses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rv = (RecyclerView)findViewById(R.id.cartView);
LinearLayoutManager llm = new LinearLayoutManager(context);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("Secret Url") // For some reason I cannot show the url
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
ArrayList arrayList = new ArrayList();
Call<Example> call = api.getRespon();
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
if(response.code() != 200){
Toast.makeText(MainActivity.this, "Connect",Toast.LENGTH_SHORT).show();
return;
}
Example examples = response.body();
for(int i=0; i<examples.getResponse().size(); i++){
String f_name = response.body().getResponse().iterator().next().getfName();
String l_name = response.body().getResponse().iterator().next().getlName();
String birthday = response.body().getResponse().iterator().next().getBirthday();
String SpecName = response.body().getResponse().iterator().next().getSpecialty()
.iterator().next().getName();
int SpecId = response.body().getResponse().iterator().next().getSpecialty()
.iterator().next().getSpecialtyId();
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
Toast.makeText(MainActivity.this, "Fail",Toast.LENGTH_SHORT).show();
}
});
}
}
At the moment I have not finished the class because I can not specify the data that have been implemented
PersonaAdapter
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
Context context;
Example example;
MainActivity mainActivity;
public static class PersonViewHolder extends RecyclerView.ViewHolder{
CardView cv;
TextView l_name, f_name, birthday, SpecName, Age;
ImageView avatar;
public PersonViewHolder(View itemView) {
super(itemView);
cv = itemView.findViewById(R.id.cartView);
l_name = itemView.findViewById(R.id.textLName);
f_name = itemView.findViewById(R.id.textFName);
birthday = itemView.findViewById(R.id.textBirthday);
SpecName = itemView.findViewById(R.id.textSpecName);
Age = itemView.findViewById(R.id.textAge);
}
}
// иницилизация
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
PersonViewHolder phv = new PersonViewHolder(v);
return phv;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
//***
}
#Override
public int getItemCount() {
return example.getResponse().size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Handler itself
Response
public class Response {
#SerializedName("f_name")
#Expose
private String fName;
#SerializedName("l_name")
#Expose
private String lName;
#SerializedName("birthday")
#Expose
private String birthday;
#SerializedName("avatr_url")
#Expose
private String avatrUrl;
#SerializedName("specialty")
#Expose
private List<Specialty> specialty = null;
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public Response withfName(String fName) {
this.fName = fName;
return this;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Response withlName(String lName) {
this.lName = lName;
return this;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public Response withBirthday(String birthday) {
this.birthday = birthday;
return this;
}
public String getAvatrUrl() {
return avatrUrl;
}
public void setAvatrUrl(String avatrUrl) {
this.avatrUrl = avatrUrl;
}
public Response withAvatrUrl(String avatrUrl) {
this.avatrUrl = avatrUrl;
return this;
}
public List<Specialty> getSpecialty() {
return specialty;
}
public void setSpecialty(List<Specialty> specialty) {
this.specialty = specialty;
}
public Response withSpecialty(List<Specialty> specialty) {
this.specialty = specialty;
return this;
}
}
Specialty
public class Specialty {
#SerializedName("specialty_id")
#Expose
private Integer specialtyId;
#SerializedName("name")
#Expose
private String name;
public Integer getSpecialtyId() {
return specialtyId;
}
public void setSpecialtyId(Integer specialtyId) {
this.specialtyId = specialtyId;
}
public Specialty withSpecialtyId(Integer specialtyId) {
this.specialtyId = specialtyId;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Specialty withName(String name) {
this.name = name;
return this;
}
}
I solved the problem by creating a list and putting the data into an array
List<Worker> workerList = new ArrayList<>();
for(int i = 0; i < examples.getResponse().size(); i++){
String f_name = response.body().getResponse().get(i).getfName();
String l_name = response.body().getResponse().get(i).getlName();
String birthday = response.body().getResponse().get(i).getBirthday();
String SpecName = response.body().getResponse().get(i).getSpecialty()
.iterator().next().getName();
String SpecId = response.body().getResponse().iterator().next().getSpecialty()
.iterator().next().getSpecialtyId().toString();
String AvatarUrl = response.body().getResponse().get(i).getAvatrUrl();
workerList.add(new Worker(f_name, l_name, birthday, SpecName, SpecId, AvatarUrl));
In Worker has a constructor and getter

I want to fetch array values of users by calling API

I want to fetch the array list of users. I have three POGO classes i.e Root(Parent class), ContactFamilyDetails(Child class), DataModelFamilyDetails(GrandChild class).
The problem that I have faced all the time that when I run the application at that time I only get the first array value, unfortunately, I didn't get the rest of the values. So I am going to share my whole code so please go through it and help me out of it !! Thank You!!
AddUserActivity (Act as MainActivity)
public class AddUserActivity extends AppCompatActivity {
SharedPreferences prefs;
String FirstName;
String ContactNo,Authentication,ID;
FloatingActionButton FAB;
private DataModelFamilyDetails dataModelFamDetails;
ArrayList<DataModelFamilyDetails> dataModelFamilyDetails;
RecyclerViewAdapter adapter;
RecyclerView myrv;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
// Initialize FloatingAction button
FAB=findViewById(R.id.fab_id);
//SharedPreference Login details
prefs = this.getSharedPreferences("logindata", MODE_PRIVATE);
FirstName = prefs.getString("fname", "");
ContactNo = prefs.getString("contact_no1", "");
Authentication=prefs.getString("Authentication","");
ID=prefs.getString("id","");
//Setting RecyclerView
myrv = findViewById(R.id.recyclerview_id);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(AddUserActivity.this);
myrv.setLayoutManager(mLayoutManager);
dataModelFamilyDetails=new ArrayList<DataModelFamilyDetails>();
//Set Click listener on Floating Action Button
FAB.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent=new Intent(AddUserActivity.this,AddNewUserActivity.class);
startActivity(intent);
}
});
//Call the Retrofit Class data
getResult1();
}
//Fetching Family Details using Retrofit
private void getResult1()
{
RequestBody requestBody=new FormBody.Builder()
.add("id",ID)
.add("Authentication",Authentication)
.build();
//Below, API call by a Retrofit Class to the java Interface
try
{
Retrofit_Class.getDefault().apiInterface().getFamilyDetails(requestBody).enqueue(new Callback<Root<ContactFamilyDetails>>()
{
#Override
public void onResponse(Call<Root<ContactFamilyDetails>> call, retrofit2.Response<Root<ContactFamilyDetails>> response)
{
ContactFamilyDetails contactFamilyDetails=response.body().getRoot();
String Status=contactFamilyDetails.getStatus();
if(Status.equals("true"))
{
dataModelFamilyDetails=contactFamilyDetails.getData();
myrv.setAdapter(new RecyclerViewAdapter(getApplicationContext(),dataModelFamilyDetails));
RecyclerViewAdapter(getApplicationContext(),dataModelFamilyDetails);
}else
{
Toast.makeText(context, "You haven't added any family member yet !!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Root<ContactFamilyDetails>> call, Throwable t)
{
Log.d("Error",t.getMessage());
Toast.makeText(context, "Error fetching data", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e)
{
Log.d("Error",e.getMessage());
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
RecyclerViewAdapter Class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
ArrayList<DataModelFamilyDetails> dataModelFamilyDetails=new ArrayList<DataModelFamilyDetails>();
Context mContext;
public RecyclerViewAdapter(Context mContext, ArrayList<DataModelFamilyDetails> dataModelFamilyDetails) {
this.mContext=mContext;
this.dataModelFamilyDetails=dataModelFamilyDetails;
}
//3 Implemented methods of RecyclerView.Adapter
#NonNull
#Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_user_details, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder( RecyclerViewAdapter.MyViewHolder holder, int position)
{
holder.Name.setText(dataModelFamilyDetails.get(position).getName());
holder.Contact.setText(dataModelFamilyDetails.get(position).getContact_no());
}
#Override
public int getItemCount()
{
return dataModelFamilyDetails.size();
}
//Inner Class of RecyclerViewAdapter
public static class MyViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Download,Contact;
ImageView DeleteDustbin,Call;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
//Initialize the variables
Name=itemView.findViewById(R.id.tv1_id);
Download=itemView.findViewById(R.id.tv2_id);
Contact=itemView.findViewById(R.id.tv_contact_id);
cardView=itemView.findViewById(R.id.cardview_id);
DeleteDustbin=itemView.findViewById(R.id.delete_img_id);
Call=itemView.findViewById(R.id.call_img_id);
}
}
}
Root (POGO Class(Parent class))
public class Root<T> {
private T root;
public T getRoot()
{
return root;
}
}
ContactFamilyDetails (POGO Class(Child class))
public class ContactFamilyDetails {
#SerializedName("status")
private String Status;
#SerializedName("message")
private String Message;
#SerializedName("data")
private ArrayList<DataModelFamilyDetails> data;
public String getStatus() {
return Status;
}
public String getMessage() {
return Message;
}
public ArrayList<DataModelFamilyDetails> getData() {
return data;
}
}
DataModelFamilyDetails (POGO Class (GrandChild class))
public class DataModelFamilyDetails {
#SerializedName("id")
private String id;
#SerializedName("parentId")
private String parentId;
#SerializedName("name")
private String name;
#SerializedName("age")
private String age;
#SerializedName("sex")
private String sex;
#SerializedName("relation")
private String relation;
#SerializedName("contact_no")
private String contact_no;
#SerializedName("email")
private String email;
#SerializedName("description")
private String description;
#SerializedName("status")
private String status;
#SerializedName("image")
private String image;
#SerializedName("regDateTime")
private String regDateTime;
public DataModelFamilyDetails(String name, String contact_no) {
this.name = name;
this.contact_no = contact_no;
}
public String getId() {
return id;
}
public String getParentId() {
return parentId;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getSex() {
return sex;
}
public String getRelation() {
return relation;
}
public String getContact_no() {
return contact_no;
}
public String getEmail() {
return email;
}
public String getDescription() {
return description;
}
public String getStatus() {
return status;
}
public String getImage() {
return image;
}
public String getRegDateTime() {
return regDateTime;
}
}
Retrofit Class
public class Retrofit_Class {
//set an Url here
public static final String API_BASE_URL = "http://www.hawktechnologies.in/society-management/appservices/";
//Create a reference of the class here
private static Retrofit_Class mInstance;
//Object creation of Retrofit.builder
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(Retrofit_Class.getDefault().getGsonParser()));
private ApiInterface apiInterface;
private OkHttpClient okHttpClient;
private Gson gson;
//Constructor
private Retrofit_Class() {
//No External Instances
}
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(Retrofit_Class.getDefault().getOkHttpClient()).build();
return retrofit.create(serviceClass);
}
//Retrofit class method
public static Retrofit_Class getDefault() {
if (mInstance == null) {
mInstance = new Retrofit_Class();
}
return mInstance;
}
//Interface class method
public ApiInterface apiInterface() {
if (apiInterface == null) {
apiInterface = createService(ApiInterface.class);
}
return apiInterface;
}
//Method type Gson
public Gson getGsonParser() {
if (gson == null) {
gson = new Gson();
}
return gson;
}
//Use of HTTP
public OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
#Override
public void log(String message) {
Timber.tag("OkHttp").d(message);
}
});
if (BuildConfig.DEBUG) {
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build();
}
return okHttpClient;
}
}
Interface
public interface ApiInterface
{
#POST("user-login.php")
Call<Root<Contact>> getLogin(#Body RequestBody requestBody);
#POST("get_familymembers.php")
Call<Root<ContactFamilyDetails>> getFamilyDetails(#Body RequestBody requestBody);
}
Instead of getting 4 results I am getting only one, please click on the link to see the Picture.
Picture Link

Android add json array to Pojo class

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());
}
}
}

Issue with ArrayList from JSON using Retrofit and populating RecyclerView

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.

How to parse RSS xml feed using Retrofit lib

I am trying to parse an XML feed with Retrofit API but I was blocked, I don't know how to access those attributes I think the problem is the Root RSS!
This is the feed : http://www.ka-news.de/storage/rss/rss/karlsruhe.xml
The main activity is where I will pass the data (list of items) to the adapter.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.ka-news.de")
.setConverter(new SimpleXmlConverter())
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
api apiService = restAdapter.create(api.class);
Rss rss = apiService.getRss();
List<Item> items = rss.getChannel().getItemList();
// Obtener el Recycler
recycler = (RecyclerView) rootView.findViewById(R.id.reciclador);
recycler.setHasFixedSize(true);
// Usar un administrador para LinearLayout
lManager = new LinearLayoutManager(getContext());
recycler.setLayoutManager(lManager);
// Crear un nuevo adaptador
adapter = new AnimeAdapter(items);
recycler.setAdapter(adapter);
rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));
return rootView;
}
api interface :
public interface api {
#GET("/storage/rss/rss/karlsruhe.xml")
public Rss getRss();
}
I have created three entities :
Channel :
#Root(strict = false)
public class Channel {
#ElementList(name = "item", required = true, inline = true)
public List<Item> itemList;
public List<Item> getItemList() {
return itemList;
}
public void setItemList(List<Item> itemList) {
this.itemList = itemList;
}
}
Item:
#Root(name = "item", strict = false)
public class Item {
#Element(name = "title", required = true)
String title;
#Element(name = "link", required = true)
String link;
#Element(name = "description", required = true)
String description;
#Element(name = "pubDate", required = false)
String pubDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
#Override
public String toString() {
return "Item{" +
"title='" + title + '\'' +
", link='" + link + '\'' +
", description='" + description + '\'' +
", pubDate='" + pubDate + '\'' +
'}';
}
}
Rss:
#Root
public class Rss {
#Attribute
String version;
#Element
Channel channel;
public Channel getChannel() {
return channel;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
#Override
public String toString() {
return "RSS{" +
"version='" + version + '\'' +
", channel=" + channel +
'}';
}
}
the problem showing in log is :
FATAL EXCEPTION: main
retrofit.RetrofitError
at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:394)
at retrofit.RestAdapter$RestHandler.invoke(RestAdapter.java:240)
at $Proxy1.getRss(Native Method)
at br.liveo.ndrawer.ui.fragment.MainFragment.onCreateView(MainFragment.java:109)
this line :
Rss rss = apiService.getRss();
I have find the solution inspired from those post in stackoverflow.com:
First link and Second link
have already create new api and entities :
The api interface :
public interface RssAdapter{
#GET("/storage/rss/rss/karlsruhe.xml")
void getItems(Callback<Feed> callback);
}
Feed class :
#Root(name = "rss", strict = false)
public class Feed implements Serializable {
#Element(name = "channel")
private Channel mChannel;
public Channel getmChannel() {
return mChannel;
}
public Feed() {
}
public Feed(Channel mChannel) {
this.mChannel = mChannel;
}
}
and channel class:
#Root(name = "channel", strict = false)
public class Channel implements Serializable {
#ElementList(inline = true, name="item")
private List<FeedItem> mFeedItems;
public List<FeedItem> getFeedItems() {
return mFeedItems;
}
public Channel() {
}
public Channel(List<FeedItem> mFeedItems) {
this.mFeedItems = mFeedItems;
}
}
and the last one it's item:
#Root(name = "item", strict = false)
public class FeedItem implements Serializable {
#Element(name = "pubDate")
private String mpubDate;
#Element(name = "title")
private String mtitle;
#Element(name = "link")
private String mlink;
#Element(name = "description")
private String mdescription;
public FeedItem() {
}
public FeedItem(String mdescription, String mlink, String mtitle, String mpubDate) {
this.mdescription = mdescription;
this.mlink = mlink;
this.mtitle = mtitle;
this.mpubDate = mpubDate;
}
public String getMpubDate() {
return mpubDate;
}
public void setMpubDate(String mpubDate) {
this.mpubDate = mpubDate;
}
public String getMtitle() {
return mtitle;
}
public void setMtitle(String mtitle) {
this.mtitle = mtitle;
}
public String getMlink() {
return mlink;
}
public void setMlink(String mlink) {
this.mlink = mlink;
}
public String getMdescription() {
return mdescription;
}
public void setMdescription(String mdescription) {
this.mdescription = mdescription;
}
}
of course in my main activity i will put that :
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.ka-news.de")
.setConverter(new SimpleXmlConverter())
.build();
RssAdapter rssAdapter = restAdapter.create(RssAdapter.class);
rssAdapter.getItems(new Callback<Feed>() {
#Override
public void success(Feed newsitems, Response response) {
Toast.makeText(getContext(), "oki", Toast.LENGTH_LONG).show();
List<FeedItem> mItems = new ArrayList<>();
mItems = newsitems.getmChannel().getFeedItems();
// Crear un nuevo adaptador
adapter = new AnimeAdapter(mItems);
recycler.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
System.out.println(error);
Toast.makeText(getContext(), "Error" + error.getMessage(), Toast.LENGTH_LONG).show();
}
});
and the items getting from the parsing using the retrofit api i will set on the adapter constructor to show that in the listview or RecyclerView.
Good Luck

Categories

Resources