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 am using Retrofit for parsing data in recycler view. I am not knowledgable about Retrofit.
My Json Fromat:
[{"id":3106,"sku":"62974","name":"NESTLE CERELAC STG 1 WHEAT 300G","attribute_set_id":4,"price":164,"status":1,"visibility":4,"type_id":"simple","created_at":"2017-08-16 16:15:30","updated_at":"2017-09-14 06:54:36","extension_attributes":{"stock_item":{"item_id":5627,"product_id":3106,"stock_id":1,"qty":3,"is_in_stock":true,"is_qty_decimal":false,"show_default_notification_message":false,"use_config_min_qty":true,"min_qty":0,"use_config_min_sale_qty":1,"min_sale_qty":1,"use_config_max_sale_qty":true,"max_sale_qty":10000,"use_config_backorders":true,"backorders":0,"use_config_notify_stock_qty":true,"notify_stock_qty":1,"use_config_qty_increments":true,"qty_increments":0,"use_config_enable_qty_inc":true,"enable_qty_increments":false,"use_config_manage_stock":true,"manage_stock":true,"low_stock_date":null,"is_decimal_divided":false,"stock_status_changed_auto":0}},"product_links":[],"options":[],"media_gallery_entries":[{"id":1127,"media_type":"image","label":"","position":1,"disabled":false,"types":["image","small_image","thumbnail","swatch_image"],"file":"\/6\/2\/62974.png"}],"tier_prices":[],"custom_attributes":[{"attribute_code":"description","value":"
NESTLE CERELAC STG 1 WHEAT 300G<\/p>"},{"attribute_code":"short_description","value":"
NESTLE CERELAC STG 1 WHEAT 300G<\/p>"},{"attribute_code":"special_price","value":"160.7200"},{"attribute_code":"special_from_date","value":"2017-08-17 20:17:57"},{"attribute_code":"meta_title","value":"NESTLE CERELAC STG 1 WHEAT 300G"},{"attribute_code":"meta_description","value":"NESTLE CERELAC STG 1 WHEAT 300G"},{"attribute_code":"image","value":"\/6\/2\/62974.png"},{"attribute_code":"small_image","value":"\/6\/2\/62974.png"},{"attribute_code":"thumbnail","value":"\/6\/2\/62974.png"},{"attribute_code":"news_from_date","value":"2017-08-17 20:17:57"},{"attribute_code":"custom_design_from","value":"2017-08-17 20:17:57"},{"attribute_code":"category_ids","value":["56","631"]},{"attribute_code":"options_container","value":"container2"},{"attribute_code":"required_options","value":"0"},{"attribute_code":"has_options","value":"0"},{"attribute_code":"msrp_display_actual_price_type","value":"0"},{"attribute_code":"url_key","value":"nestle-cerelac-stg-1-wheat-300g"},{"attribute_code":"gift_message_available","value":"2"},{"attribute_code":"tax_class_id","value":"2"},{"attribute_code":"swatch_image","value":"\/6\/2\/62974.png"}]}
i have get the name, sku, id successfully using below code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private RecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_retrofit);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
// recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
requestJsonObject();
}
private void requestJsonObject(){
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://alagendransupermart.com/mageapi/cat_product.php?cid=83";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<ItemObject> posts = new ArrayList<ItemObject>();
posts = Arrays.asList(mGson.fromJson(response, ItemObject[].class));
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
}
});
queue.add(stringRequest);
}
}
Adapter:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_retrofit, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.songTitle.setText("Product Name: " + itemList.get(position).getSongTitle());
holder.songYear.setText("ID: " + itemList.get(position).getSongYear());
holder.songAuthor.setText("SKU: " + itemList.get(position).getSongAuthor());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
Getter and setter:
public class ItemObject {
#SerializedName("name")
private String songTitle;
#SerializedName("id")
private String songYear;
#SerializedName("sku")
private String songAuthor;
public ItemObject(String songTitle, String songYear, String songAuthor) {
this.songTitle = songTitle;
this.songYear = songYear;
this.songAuthor = songAuthor;
}
public String getSongTitle() {
return songTitle;
}
public String getSongYear() {
return songYear;
}
public String getSongAuthor() {
return songAuthor;
}
}
But how can I get the values inside the next array name like parameters and there are more than 5 attributes with same name but with different values.
You should add to ItemObject :
#SerializedName("extension_attributes")
private ExtensionAttributes extensionAttributes;
ExtensionAttributes.java:
public class ExtensionAttributes {
#SerializedName("stock_item")
#Expose
private StockItem stockItem;
public StockItem getStockItem() {
return stockItem;
}
public void setStockItem(StockItem stockItem) {
this.stockItem = stockItem;
}
}
StockItem.java:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class StockItem {
#SerializedName("item_id")
#Expose
private Integer itemId;
#SerializedName("product_id")
#Expose
private Integer productId;
#SerializedName("stock_id")
#Expose
private Integer stockId;
#SerializedName("qty")
#Expose
private Integer qty;
#SerializedName("is_in_stock")
#Expose
private Boolean isInStock;
#SerializedName("is_qty_decimal")
#Expose
private Boolean isQtyDecimal;
#SerializedName("show_default_notification_message")
#Expose
private Boolean showDefaultNotificationMessage;
#SerializedName("use_config_min_qty")
#Expose
private Boolean useConfigMinQty;
#SerializedName("min_qty")
#Expose
private Integer minQty;
#SerializedName("use_config_min_sale_qty")
#Expose
private Integer useConfigMinSaleQty;
#SerializedName("min_sale_qty")
#Expose
private Integer minSaleQty;
#SerializedName("use_config_max_sale_qty")
#Expose
private Boolean useConfigMaxSaleQty;
#SerializedName("max_sale_qty")
#Expose
private Integer maxSaleQty;
#SerializedName("use_config_backorders")
#Expose
private Boolean useConfigBackorders;
#SerializedName("backorders")
#Expose
private Integer backorders;
#SerializedName("use_config_notify_stock_qty")
#Expose
private Boolean useConfigNotifyStockQty;
#SerializedName("notify_stock_qty")
#Expose
private Integer notifyStockQty;
#SerializedName("use_config_qty_increments")
#Expose
private Boolean useConfigQtyIncrements;
#SerializedName("qty_increments")
#Expose
private Integer qtyIncrements;
#SerializedName("use_config_enable_qty_inc")
#Expose
private Boolean useConfigEnableQtyInc;
#SerializedName("enable_qty_increments")
#Expose
private Boolean enableQtyIncrements;
#SerializedName("use_config_manage_stock")
#Expose
private Boolean useConfigManageStock;
#SerializedName("manage_stock")
#Expose
private Boolean manageStock;
#SerializedName("low_stock_date")
#Expose
private Object lowStockDate;
#SerializedName("is_decimal_divided")
#Expose
private Boolean isDecimalDivided;
#SerializedName("stock_status_changed_auto")
#Expose
private Integer stockStatusChangedAuto;
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getStockId() {
return stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
public Boolean getIsInStock() {
return isInStock;
}
public void setIsInStock(Boolean isInStock) {
this.isInStock = isInStock;
}
public Boolean getIsQtyDecimal() {
return isQtyDecimal;
}
public void setIsQtyDecimal(Boolean isQtyDecimal) {
this.isQtyDecimal = isQtyDecimal;
}
public Boolean getShowDefaultNotificationMessage() {
return showDefaultNotificationMessage;
}
public void setShowDefaultNotificationMessage(Boolean showDefaultNotificationMessage) {
this.showDefaultNotificationMessage = showDefaultNotificationMessage;
}
public Boolean getUseConfigMinQty() {
return useConfigMinQty;
}
public void setUseConfigMinQty(Boolean useConfigMinQty) {
this.useConfigMinQty = useConfigMinQty;
}
public Integer getMinQty() {
return minQty;
}
public void setMinQty(Integer minQty) {
this.minQty = minQty;
}
public Integer getUseConfigMinSaleQty() {
return useConfigMinSaleQty;
}
public void setUseConfigMinSaleQty(Integer useConfigMinSaleQty) {
this.useConfigMinSaleQty = useConfigMinSaleQty;
}
public Integer getMinSaleQty() {
return minSaleQty;
}
public void setMinSaleQty(Integer minSaleQty) {
this.minSaleQty = minSaleQty;
}
public Boolean getUseConfigMaxSaleQty() {
return useConfigMaxSaleQty;
}
public void setUseConfigMaxSaleQty(Boolean useConfigMaxSaleQty) {
this.useConfigMaxSaleQty = useConfigMaxSaleQty;
}
public Integer getMaxSaleQty() {
return maxSaleQty;
}
public void setMaxSaleQty(Integer maxSaleQty) {
this.maxSaleQty = maxSaleQty;
}
public Boolean getUseConfigBackorders() {
return useConfigBackorders;
}
public void setUseConfigBackorders(Boolean useConfigBackorders) {
this.useConfigBackorders = useConfigBackorders;
}
public Integer getBackorders() {
return backorders;
}
public void setBackorders(Integer backorders) {
this.backorders = backorders;
}
public Boolean getUseConfigNotifyStockQty() {
return useConfigNotifyStockQty;
}
public void setUseConfigNotifyStockQty(Boolean useConfigNotifyStockQty) {
this.useConfigNotifyStockQty = useConfigNotifyStockQty;
}
public Integer getNotifyStockQty() {
return notifyStockQty;
}
public void setNotifyStockQty(Integer notifyStockQty) {
this.notifyStockQty = notifyStockQty;
}
public Boolean getUseConfigQtyIncrements() {
return useConfigQtyIncrements;
}
public void setUseConfigQtyIncrements(Boolean useConfigQtyIncrements) {
this.useConfigQtyIncrements = useConfigQtyIncrements;
}
public Integer getQtyIncrements() {
return qtyIncrements;
}
public void setQtyIncrements(Integer qtyIncrements) {
this.qtyIncrements = qtyIncrements;
}
public Boolean getUseConfigEnableQtyInc() {
return useConfigEnableQtyInc;
}
public void setUseConfigEnableQtyInc(Boolean useConfigEnableQtyInc) {
this.useConfigEnableQtyInc = useConfigEnableQtyInc;
}
public Boolean getEnableQtyIncrements() {
return enableQtyIncrements;
}
public void setEnableQtyIncrements(Boolean enableQtyIncrements) {
this.enableQtyIncrements = enableQtyIncrements;
}
public Boolean getUseConfigManageStock() {
return useConfigManageStock;
}
public void setUseConfigManageStock(Boolean useConfigManageStock) {
this.useConfigManageStock = useConfigManageStock;
}
public Boolean getManageStock() {
return manageStock;
}
public void setManageStock(Boolean manageStock) {
this.manageStock = manageStock;
}
public Object getLowStockDate() {
return lowStockDate;
}
public void setLowStockDate(Object lowStockDate) {
this.lowStockDate = lowStockDate;
}
public Boolean getIsDecimalDivided() {
return isDecimalDivided;
}
public void setIsDecimalDivided(Boolean isDecimalDivided) {
this.isDecimalDivided = isDecimalDivided;
}
public Integer getStockStatusChangedAuto() {
return stockStatusChangedAuto;
}
public void setStockStatusChangedAuto(Integer stockStatusChangedAuto) {
this.stockStatusChangedAuto = stockStatusChangedAuto;
}
}
I hope you can use this instrument next time.
So am working with retrofit and rxjava for my application.so am using the #GET annociation to pull my blog details from the server that include blog_title, blog_content, blog_thumbnail etc and all this parameter are within an array called blog_post.
I have my APIClient:
public class ApiClient {
private static final String STAGING_BASE_URL = "https://watchnollywood.ml/api/";
private static ApiClient instance;
private ApiService apiService;
private ApiClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
// TODO: 21/03/2017 when going live change the log level to NONE, to enhance performance
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line for logging requests!
final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
//final Retrofit retrofit = new Retrofit.Builder().baseUrl(STAGING_BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(STAGING_BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
}
public static ApiClient getInstance(){
if(instance == null){
instance = new ApiClient();
}
return instance;
}
//API CALL FOR LOGIN
public Observable<UserItem> login(String email, String password){
return apiService.signIn(email,password);
}
//API CALL FOR SIGNUP
public Observable<StatusItem> signup(String email, String password, String full_name, String phone){
return apiService.signUp(email, password,phone,full_name);
}
//API CALL FOR BLOG DETAILS
public Observable<BlogResponse> blog_post(){
return apiService.blog_post();
}
}
ApiService:
public interface ApiService {
#FormUrlEncoded
#POST("signin")
Observable<UserItem> signIn(#Field("email") String email, #Field("password") String password);
#FormUrlEncoded
#POST("signup")
Observable<StatusItem> signUp(#Field("full_name")String full_name, #Field("phone") String phone, #Field("email") String email, #Field("password") String password);
#GET("blog")
Observable<BlogResponse> blog_post();
}
pojo classes:
public class BlogItem {
private int thumbNail;
private String title;
private String summary;
public int getThumbNail() {
return thumbNail;
}
public void setThumbNail(#DrawableRes int thumbNail) {
this.thumbNail = thumbNail;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
public class BlogResponse {
private BlogItem[] blogItems;
public BlogItem[] getBlogItems() {
return blogItems;
}
public void setBlogItems(BlogItem[] blogItems) {
this.blogItems = blogItems;
}
}
I have a recyclerview that will hold all the information that will be coming from the server. But the problem is that when I run it I get a log response in my RUN terminal but nothing is showing on the app screen.
this is my FragmentClass that holds the information from the server:
BlogFragment:
public class BlogFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
private RecyclerView recyclerView;
private BlogAdapter adapter;
private List<BlogItem> blogItems;
private View view;
public BlogFragment() {
// Required empty public constructor
}
public static BlogFragment newInstance(String param1) {
BlogFragment fragment = new BlogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_blog, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = (RecyclerView) view.findViewById(R.id.blog_posts_list);
setUpViews();
}
private void setUpViews() {
blogItems = new ArrayList<>();
adapter = new BlogAdapter(blogItems);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
BlogPost();
// populateLists();
}
private void BlogPost() {
ApiClient.getInstance().blog_post().observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread()).subscribe(new DisposableObserver<BlogResponse>() {
#Override
public void onNext(BlogResponse value) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(blogItem.getTitle().toString());
blogItem.setSummary(blogItem.getSummary().toString());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
}
});
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
/*
private void populateLists() {
int dummyPostArraySize = 10;
for (int i = 0; i < dummyPostArraySize; i++) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("Post title " + i+1);
blogItem.setThumbNail(isEven(i) ? R.drawable.profile_image : 0);
blogItem.setSummary(getString(isEven(i) ? R.string.summary2 : R.string.summary1));
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}*/
private boolean isEven(int position) {
return (position & 1) == 0;
}
}
Adapter class
public class BlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
private List<BlogItem> blogItems;
public BlogAdapter(List<BlogItem> blogItems) {
this.blogItems = blogItems;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_post_item,
parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
BlogItem blogItem = blogItems.get(position);
holder.bindModel(blogItem);
}
#Override
public int getItemCount() {
return blogItems == null ? (0) : blogItems.size();
}
}
View Holder class
public class BlogViewHolder extends RecyclerView.ViewHolder {
private ImageView cover;
private TextView title;
private TextView summary;
public BlogViewHolder(View itemView) {
super(itemView);
cover = (ImageView) itemView.findViewById(R.id.post_thumbnail);
title = (TextView) itemView.findViewById(R.id.post_title);
summary = (TextView) itemView.findViewById(R.id.post_summary);
}
public void bindModel(BlogItem blogItem) {
if (blogItem.getThumbNail() == 0) {
cover.setVisibility(View.GONE);
} else {
cover.setImageResource(blogItem.getThumbNail());
}
title.setText(Html.fromHtml(blogItem.getTitle()));
summary.setText(blogItem.getSummary());
}
}
What am I not doing right. Someone Please Help!!!
In the private void BlogPost() { method, you create BlogItems but then don't do anything with it. You probably forgot to add them to the blogItems list.
In addition, the call to adapter.notifyItemRangeChanged in that method happens way before the sequence receives data but you don't call that after each blogItem or when all blog items have arrived - the observer is on a complete different execution path than the outer BlogPost() method.
Edit spelled out:
#Override
public void onNext(BlogResponse value) {
for (BlogItem responseItem : value.getBlogItems()) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(responseItem.getTitle().toString());
blogItem.setSummary(responseItem.getSummary().toString());
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
blogItems.add(blogItem);
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}