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