How to create a retrofit2 array in android studio? - java

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

Related

ListView is not showing all JSON data using Retrofit

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

RecyclerView, wrong positioning of data

im making a program that can view data and image at the same time using recyclerview
MainActivity
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ArrayList<Upload> mUpload = new ArrayList<>();
String y = "report";
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
childcount = postSnapshot.child(userID).getChildrenCount() - 5;
String z = y+childcount;
Upload upload = postSnapshot.child(userID).child(z).getValue(Upload.class);
Upload uploads = postSnapshot.child(userID).getValue(Upload.class);
mUploads.add(upload);
mUploads.add(uploads);
mUpload.addAll(mUploads);
Log.d(TAG, "sampleData " + mUploads);
}
mAdapter = new ImageAdapter(getActivity(), mUpload);
mRecycleView.setAdapter(mAdapter);
}
ImageAdapter
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getiName());
holder.textViewDate.setText(uploadCurrent.getDate());
holder.textViewAddress.setText(uploadCurrent.getAddress());
holder.textViewPhone.setText(uploadCurrent.getPhone());
holder.textViewReport.setText(uploadCurrent.getReport());
Picasso.with(mContext)
.load(uploadCurrent.getImageUrl())
.fit()
.centerCrop()
.into(holder.imageView);
holder.setIsRecyclable(false);
holder.getLayoutPosition();
}
Upload Class
public class Upload {
private String mName;
private String mImageUrl;
private String date;
private String address;
private String phone;
private String iName;
private String report;
public Upload() {
//empty constructor needed
}
public Upload(String name, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
mName = name;
mImageUrl = imageUrl;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getiName() {
return iName;
}
public void setiName(String iName) {
this.iName = iName;
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public String getDate() { return date; }
public void setDate(String date) { this.date = date; }
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl = imageUrl;
}
}
xml file
enter image description here
output i get
enter image description here
as you can see i got wrong positioning of data, i also try to merge the 2 arraylist data which is upload and uploads but nothings change, can someone help me with this project. thank you so much

Expected a string but was begin_array at line 1 column 13 [duplicate]

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 4 years ago.
This is my JSON output:
{
"Message": [
{
"Emp_Id": 7,
"Emp_First_Name": "Mohammad",
"Emp_Last_Name": "Malek",
"Emp_Email": "malek#cloudester.com",
"Emp_Address": "A-82/2,Ahmed nagar Society, Manubar Road, Bharuch-392001",
"Emp_Phone_No": "8140717602",
"Emp_Password": "3f645aeff486fd9bda7ded484a43f701",
"Emp_Photo": "/Images/2018_07_02_05_30_24.jpg",
"Is_Resign": 0,
"Joining_Date": "2017-12-12T00:00:00.000Z",
"Resign_Date": "2017-12-12T00:00:00.000Z",
"sms_status": 0
}
]}
This is my pojo class:
public class Result {
#SerializedName("Message")
private String message;
#SerializedName("Emp_Id")
#Expose
private Integer empId;
#SerializedName("Emp_First_Name")
#Expose
private String empFirstName;
#SerializedName("Emp_Last_Name")
#Expose
private String empLastName;
#SerializedName("Emp_Email")
#Expose
private String empEmail;
#SerializedName("Emp_Address")
#Expose
private String empAddress;
#SerializedName("Emp_Phone_No")
#Expose
private String empPhoneNo;
#SerializedName("Emp_Password")
#Expose
private String empPassword;
#SerializedName("Emp_Photo")
#Expose
private String empPhoto;
#SerializedName("Is_Resign")
#Expose
private Integer isResign;
#SerializedName("Joining_Date")
#Expose
private String joiningDate;
#SerializedName("Resign_Date")
#Expose
private String resignDate;
#SerializedName("sms_status")
#Expose
private Integer smsStatus;
public Integer getEmpId() {
return empId;
}
public String getEmpFirstName() {
return empFirstName;
}
public String getEmpLastName() {
return empLastName;
}
public String getEmpEmail() {
return empEmail;
}
public String getEmpAddress() {
return empAddress;
}
public String getEmpPhoneNo() {
return empPhoneNo;
}
public String getEmpPassword() {
return empPassword;
}
public String getEmpPhoto() {
return empPhoto;
}
public Integer getIsResign() {
return isResign;
}
public String getJoiningDate() {
return joiningDate;
}
public String getResignDate() {
return resignDate;
}
public Integer getSmsStatus() {
return smsStatus;
}
#SerializedName("user")
private User user;
public Result(String message, User user,String empFirstName,String empLastName,String empEmail,String empAddress,String joiningDate) {
this.empFirstName = empFirstName;
this.message = message;
this.user = user;
this.empLastName=empLastName;
this.empEmail=empEmail;
this.empAddress=empAddress;
this.joiningDate=joiningDate;
}
public String getMessage() {
return message;
}
public User getUser() {
return user;
}}
When i run my activity onfailure is called i get a toast error message
"Expected a string but was begin_array at line 1 column 13"
This is My fragment activity class:
public class ProfileFragment extends Fragment implements View.OnClickListener {
public static final int PICK_IMAGE = 1;
public static final int REQUEST_CAMERA = 100;
public ImageView pick;
public Uri filePath;
ProgressDialog progressDialog;
EditText etfname,etlname,etemail,etaddress,etjoindt,etpos;
Context context;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
#Override public void onPermissionGranted(PermissionGrantedResponse response) {/* ... */}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {PermissionListener dialogPermissionListener =
DialogOnDeniedPermissionListener.Builder
.withContext(getContext())
.withTitle("Camera permission")
.withMessage("Camera permission is needed to take pictures")
.withButtonText(android.R.string.ok)
.withIcon(R.mipmap.ic_launcher)
.build();}
#Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
pick=view.findViewById(R.id.ivEditProfileImg);
pick.setOnClickListener(this);
etfname=view.findViewById(R.id.etfname);
etlname=view.findViewById(R.id.etlname);
etemail=view.findViewById(R.id.etemail);
etaddress=view.findViewById(R.id.etaddress);
etjoindt=view.findViewById(R.id.etjoindate);
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Fetching Data...");
progressDialog.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiClient.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Fetchemployeedetailsinterface service = retrofit.create(Fetchemployeedetailsinterface.class);//Result is our pojo class
SharedPreferences settings = getActivity().getSharedPreferences("PREFS_NAME", 0);
String emailtoken= settings.getString("email", "").toString();
Call<Result> call = service.Bind_Employee_Details_Based_On_Id(emailtoken);
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
//.getMessage is POJO method to listen for final json output
String fname=response.body().getEmpFirstName();
String lname=response.body().getEmpLastName();
String email=response.body().getEmpEmail();
String address=response.body().getEmpAddress();
String joindt=response.body().getJoiningDate();
etfname.setText(fname);
etlname.setText(lname);
etemail.setText(email);
etaddress.setText(address);
etjoindt.setText(joindt);
progressDialog.dismiss();
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_leave, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
PickImageDialog.build(new PickSetup()).show(getActivity());
PickSetup setup = new PickSetup();
PickImageDialog.build(setup)
.setOnClick(new IPickClick() {
#Override
public void onGalleryClick() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
#Override
public void onCameraClick() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_CAMERA);
}
}).show(getActivity());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
filePath = data.getData();
pick.setImageURI(filePath);
}
else if(requestCode == REQUEST_CAMERA && resultCode == Activity.RESULT_OK){
Bitmap photo = (Bitmap) data.getExtras().get("data");
pick.setImageBitmap(photo);
}
}}
When oncreateview is called it goes to onfailure and an message is toasted as shown above.
What am i doing wrong any help will appreciated.
Change your pojo class with this
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("Message")
#Expose
private List<Message> message = null;
public List<Message> getMessage() {
return message;
}
public void setMessage(List<Message> message) {
this.message = message;
}
}
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Message {
#SerializedName("Emp_Id")
#Expose
private Integer empId;
#SerializedName("Emp_First_Name")
#Expose
private String empFirstName;
#SerializedName("Emp_Last_Name")
#Expose
private String empLastName;
#SerializedName("Emp_Email")
#Expose
private String empEmail;
#SerializedName("Emp_Address")
#Expose
private String empAddress;
#SerializedName("Emp_Phone_No")
#Expose
private String empPhoneNo;
#SerializedName("Emp_Password")
#Expose
private String empPassword;
#SerializedName("Emp_Photo")
#Expose
private String empPhoto;
#SerializedName("Is_Resign")
#Expose
private Integer isResign;
#SerializedName("Joining_Date")
#Expose
private String joiningDate;
#SerializedName("Resign_Date")
#Expose
private String resignDate;
#SerializedName("sms_status")
#Expose
private Integer smsStatus;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpFirstName() {
return empFirstName;
}
public void setEmpFirstName(String empFirstName) {
this.empFirstName = empFirstName;
}
public String getEmpLastName() {
return empLastName;
}
public void setEmpLastName(String empLastName) {
this.empLastName = empLastName;
}
public String getEmpEmail() {
return empEmail;
}
public void setEmpEmail(String empEmail) {
this.empEmail = empEmail;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public String getEmpPhoneNo() {
return empPhoneNo;
}
public void setEmpPhoneNo(String empPhoneNo) {
this.empPhoneNo = empPhoneNo;
}
public String getEmpPassword() {
return empPassword;
}
public void setEmpPassword(String empPassword) {
this.empPassword = empPassword;
}
public String getEmpPhoto() {
return empPhoto;
}
public void setEmpPhoto(String empPhoto) {
this.empPhoto = empPhoto;
}
public Integer getIsResign() {
return isResign;
}
public void setIsResign(Integer isResign) {
this.isResign = isResign;
}
public String getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(String joiningDate) {
this.joiningDate = joiningDate;
}
public String getResignDate() {
return resignDate;
}
public void setResignDate(String resignDate) {
this.resignDate = resignDate;
}
public Integer getSmsStatus() {
return smsStatus;
}
public void setSmsStatus(Integer smsStatus) {
this.smsStatus = smsStatus;
}
}
than change your code with this
Call<Example> call = service.Bind_Employee_Details_Based_On_Id(emailtoken);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Result> response) {
//.getMessage is POJO method to listen for final json output
List<Example> listResponse =response.body().getMessage();
String fname=listResponse.get(0).getEmpFirstName();
String lname=listResponse.get(0).getEmpLastName();
String email=listResponse.get(0).getEmpEmail();
String address=listResponse.get(0).getEmpAddress();
String joindt=listResponse.get(0).getJoiningDate();
etfname.setText(fname);
etlname.setText(lname);
etemail.setText(email);
etaddress.setText(address);
etjoindt.setText(joindt);
progressDialog.dismiss();
}
Check your Result class. Message is Array, not a String.
To generate Object from Json, go to http://pojo.sodhanalibrary.com/ and paste your Json.
make this pojo class like ..
public class MessageItem{
#SerializedName("Emp_Id")
private int empId;
#SerializedName("Emp_Email")
private String empEmail;
#SerializedName("Emp_First_Name")
private String empFirstName;
#SerializedName("Emp_Address")
private String empAddress;
#SerializedName("Joining_Date")
private String joiningDate;
#SerializedName("Is_Resign")
private int isResign;
#SerializedName("Emp_Last_Name")
private String empLastName;
#SerializedName("Emp_Photo")
private String empPhoto;
#SerializedName("Resign_Date")
private String resignDate;
#SerializedName("Emp_Phone_No")
private String empPhoneNo;
#SerializedName("Emp_Password")
private String empPassword;
#SerializedName("sms_status")
private int smsStatus;
public void setEmpId(int empId){
this.empId = empId;
}
public int getEmpId(){
return empId;
}
public void setEmpEmail(String empEmail){
this.empEmail = empEmail;
}
public String getEmpEmail(){
return empEmail;
}
public void setEmpFirstName(String empFirstName){
this.empFirstName = empFirstName;
}
public String getEmpFirstName(){
return empFirstName;
}
public void setEmpAddress(String empAddress){
this.empAddress = empAddress;
}
public String getEmpAddress(){
return empAddress;
}
public void setJoiningDate(String joiningDate){
this.joiningDate = joiningDate;
}
public String getJoiningDate(){
return joiningDate;
}
public void setIsResign(int isResign){
this.isResign = isResign;
}
public int getIsResign(){
return isResign;
}
public void setEmpLastName(String empLastName){
this.empLastName = empLastName;
}
public String getEmpLastName(){
return empLastName;
}
public void setEmpPhoto(String empPhoto){
this.empPhoto = empPhoto;
}
public String getEmpPhoto(){
return empPhoto;
}
public void setResignDate(String resignDate){
this.resignDate = resignDate;
}
public String getResignDate(){
return resignDate;
}
public void setEmpPhoneNo(String empPhoneNo){
this.empPhoneNo = empPhoneNo;
}
public String getEmpPhoneNo(){
return empPhoneNo;
}
public void setEmpPassword(String empPassword){
this.empPassword = empPassword;
}
public String getEmpPassword(){
return empPassword;
}
public void setSmsStatus(int smsStatus){
this.smsStatus = smsStatus;
}
public int getSmsStatus(){
return smsStatus;
}
}
public class ResponseData {
#SerializedName("Message")
private List<MessageItem> message;
public void setMessage(List<MessageItem> message){
this.message = message;
}
public List<MessageItem> getMessage(){
return message;
}
}
after that ..
Call<ResponseData>
when you getting response like
call.enqueue(new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
//.getMessage is POJO method to listen for final json output
if (response.isSuccessful() && response!=null && response.body()!=null){
List<MessageItem> message=response.body().getMessage();
if (message!=null && !message.isEmpty()){
for(MessageItem messageItem:message){
etfname.setText(messageItem.getEmpFirstName());
etlname.setText(messageItem.getEmpLastName());
//same for others
}
}
}
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});

How to pass a class with an abstract class type as parameter in parcelable android studio java

I am trying to pass this class as a parcelable in android.
public class Outfit implements Parcelable {
private List<Item> itemList;
private String mName;
private String mImageUrl;
public Outfit() {}
public Outfit(String mName, String mImageUrl) {
this.mName = mName;
this.mImageUrl = mImageUrl;
}
protected Outfit(Parcel in) {
itemList = in.createTypedArrayList(Item.CREATOR);
mName = in.readString();
mImageUrl = in.readString();
}
public static final Creator<Outfit> CREATOR = new Creator<Outfit>() {
#Override
public Outfit createFromParcel(Parcel in) {
return new Outfit(in);
}
#Override
public Outfit[] newArray(int size) {
return new Outfit[size];
}
};
public String getmName() {
return mName;
}
public String getmImageUrl() {
return mImageUrl;
}
#Override
public String toString() {
return mName;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeTypedList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
}
the problem is that Item is abstract and itemList = in.creatTypedArrayList(Item.CREATOR) because Item does not have a CREATOR . Only its subclasses have this implementation.
Item.java
public abstract class Item implements Parcelable {
private String mName;
private String mColor;
private String mImageUrl;
private List<TagHolder> tags = new ArrayList<>();
private String mKey;
public Item(){
}
public Item(String mName, String mColor, String mImageUrl) {
this.mName = mName;
this.mColor = mColor;
this.mImageUrl = mImageUrl;
}
protected Item(Parcel in) {
mName = in.readString();
mColor = in.readString();
mImageUrl = in.readString();
tags = in.createTypedArrayList(TagHolder.CREATOR);
mKey = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mName);
dest.writeString(mColor);
dest.writeString(mImageUrl);
dest.writeTypedList(tags);
dest.writeString(mKey);
}
#Override
public int describeContents() {
return 0;
}
public void setmName(String mName) {
this.mName = mName;
}
public void setmImageUrl(String mImageUrl) {
this.mImageUrl = mImageUrl;
}
public List<TagHolder> getTags() {
return tags;
}
public String getmColor() {
return mColor;
}
public String getmImageUrl() {
return mImageUrl;
}
public void setmColor(String mColor) {
this.mColor = mColor;
}
public String getmName() {
return mName;
}
public void setTags(List<TagHolder> tags) {
this.tags = tags;
}
#Exclude // dont need this in our firebase database
public String getKey() {
return mKey;
}
#Exclude
public void setMkey(String key) {
mKey = key;
}
public abstract String getCategory();
}
I am able to parce a List as a parcelable array when I call put extra. But when I try to do so for outfit it gives error . Is there any way to pass Outfit as a parcelable?
Do you try using another method for the list?
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(itemList);
parcel.writeString(mName);
parcel.writeString(mImageUrl);
}
protected Outfit(Parcel in) {
in.readList(itemList, Item.class.getClassLoader());
mName = in.readString();
mImageUrl = in.readString();
}

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.

Categories

Resources