Android add json array to Pojo class - java

I have following JSON returned from server
{
"matches": [
{
"unique_id": 1122278,
"date": "2018-01-24T00:00:00.000Z",
"team-2": "India",
"team-1": "South Africa",
"type": "Test",
"dateTimeGMT": "2018-01-24T08:00:00.000Z",
"squad": true,
"toss_winner_team": "India",
"matchStarted": true
},
{
"unique_id": 1116929,
"team-2": "India Under-19s",
"team-1": "Bangladesh Under-19s",
"type": "YouthODI",
"date": "2018-01-25T00:00:00.000Z",
"dateTimeGMT": "2018-01-25T21:30:00.000Z",
"squad": true,
"toss_winner_team": "India Under-19s",
"winner_team": "India Under-19s",
"matchStarted": true
},
{
"unique_id": 1115781,
"team-2": "England",
"team-1": "New Zealand",
"type": "Test",
"date": "2018-03-29T00:00:00.000Z",
"dateTimeGMT": "2018-03-29T22:00:00.000Z",
"squad": false,
"matchStarted": false
}
],
"v": "1",
"ttl": 43,
"provider": {
"source": "Various",
"url": "https://cricapi.com/",
"pubDate": "2018-01-27T13:18:55.717Z"
},
"creditsLeft": 250
}
Using Volley library and gson.
I am trying to push JSON array match to Match Model(Pojo). I think I can insert it using a loop, but there any other way to add all JSON array to model?
public class Main2Activity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Match> matches;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recylcer_1);
recyclerView=(RecyclerView) findViewById(R.id.recyler);
myAdapter=new MyAdapter(matches);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAnimation(n);
recyclerView.setAdapter(myAdapter);
callCricket();
}
public void callCricket() {
CallApi callApi = new CallApi();
callApi.setVolleyInterface(new VolleyInterface() {
#Override
public void onSucess(String string) {
Log.d("ApiCall_success", string);
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Match>>(){}.getType();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("matches");
matches.addAll(gson.fromJson(jsonArray,type));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String string) {
}
});
}
}
I have tried using gson but I got an error.

Create pojo classes as below as per your JSON by using jsonschema2pojo:
There are No Need of loop in GSON to insert data in pojo classes.
Example.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
#SerializedName("v")
#Expose
private String v;
#SerializedName("ttl")
#Expose
private Integer ttl;
#SerializedName("provider")
#Expose
private Provider provider;
#SerializedName("creditsLeft")
#Expose
private Integer creditsLeft;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
public String getV() {
return v;
}
public void setV(String v) {
this.v = v;
}
public Integer getTtl() {
return ttl;
}
public void setTtl(Integer ttl) {
this.ttl = ttl;
}
public Provider getProvider() {
return provider;
}
public void setProvider(Provider provider) {
this.provider = provider;
}
public Integer getCreditsLeft() {
return creditsLeft;
}
public void setCreditsLeft(Integer creditsLeft) {
this.creditsLeft = creditsLeft;
}
}
Match.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Match {
#SerializedName("unique_id")
#Expose
private Integer uniqueId;
#SerializedName("date")
#Expose
private String date;
#SerializedName("team-2")
#Expose
private String team2;
#SerializedName("team-1")
#Expose
private String team1;
#SerializedName("type")
#Expose
private String type;
#SerializedName("dateTimeGMT")
#Expose
private String dateTimeGMT;
#SerializedName("squad")
#Expose
private Boolean squad;
#SerializedName("toss_winner_team")
#Expose
private String tossWinnerTeam;
#SerializedName("matchStarted")
#Expose
private Boolean matchStarted;
#SerializedName("winner_team")
#Expose
private String winnerTeam;
public Integer getUniqueId() {
return uniqueId;
}
public void setUniqueId(Integer uniqueId) {
this.uniqueId = uniqueId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDateTimeGMT() {
return dateTimeGMT;
}
public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}
public Boolean getSquad() {
return squad;
}
public void setSquad(Boolean squad) {
this.squad = squad;
}
public String getTossWinnerTeam() {
return tossWinnerTeam;
}
public void setTossWinnerTeam(String tossWinnerTeam) {
this.tossWinnerTeam = tossWinnerTeam;
}
public Boolean getMatchStarted() {
return matchStarted;
}
public void setMatchStarted(Boolean matchStarted) {
this.matchStarted = matchStarted;
}
public String getWinnerTeam() {
return winnerTeam;
}
public void setWinnerTeam(String winnerTeam) {
this.winnerTeam = winnerTeam;
}
}
Provider.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Provider {
#SerializedName("source")
#Expose
private String source;
#SerializedName("url")
#Expose
private String url;
#SerializedName("pubDate")
#Expose
private String pubDate;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
}
In your Activity class do coding like this :
public static final String TAG = DoctorHome.class.getSimpleName();
ArrayList<DoctorsCatPojo> doctorCatList = new ArrayList<>();
DoctorsCatAdapter doctorsCatAdapter;
RecyclerView recyclerView;
private void getDoctorCategory() {
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
String url = Constant.DOCTOR_CATEGORY;
Log.e("URL",""+url);
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("onResponse",""+response);
try {
status = response.getString("status");
if(status.equals("success")){
String info = response.getString("list");
JSONArray jsonArray = new JSONArray(info);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<DoctorsCatPojo>>() {
}.getType();
doctorCatList = gson.fromJson(jsonArray.toString(), listType);
if(doctorCatList!=null && doctorCatList.size()!=0){
doctorsCatAdapter = new DoctorsCatAdapter(DoctorHome.this,doctorCatList);
recyclerView.setAdapter(doctorsCatAdapter);
Log.d(TAG, response.toString());
}
}
else {
message = response.getString("message");
// Toast.makeText(getApplicationContext(),""+message,Toast.LENGTH_SHORT).show();
pDialog.hide();
}
} catch (Exception e) {
Log.e("Exception",""+e);
e.printStackTrace();
}
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error",""+error.getMessage());
pDialog.hide();
}
});
AppController.getInstance(DoctorHome.this).addToRequestQueue(request, "doctor_category");
}
your adapter class will be like this :
public class DoctorsCatAdapter extends RecyclerView.Adapter<DoctorsCatAdapter.MyViewHolder> {
ArrayList <DoctorsCatPojo> doctorCatList;
Context context;
public DoctorsCatAdapter( Context context,ArrayList<DoctorsCatPojo> doctorCatList) {
this.doctorCatList = doctorCatList;
this.context= context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctors_category_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DoctorsCatPojo doc = doctorCatList.get(position);
// holder.doctorsCatImg.setImageURI(doc.getCategory_img());
if(doc.getCategory_name()!=null){
holder.doctorsCatName.setText(doc.getCategory_name());
}
if(doc.getCategory_img()!=null){
Picasso.with(context)
.load(doc.getCategory_img().replace(" ", "%20").trim())
.placeholder(R.drawable.no_image)
.into(holder.doctorsCatImg);
}
}
#Override
public int getItemCount() {
return doctorCatList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView doctorsCatImg;
TextView doctorsCatName;
MyViewHolder(final View view) {
super(view);
itemView.setOnClickListener(this);
doctorsCatImg = (ImageView)view.findViewById(R.id.doctorsCatImg);
doctorsCatName = (TextView) view.findViewById(R.id.doctorsCatName);
}
#Override
public void onClick(View view) {
doctorCatList.get(getPosition()).getCategory_id();
((DoctorHome)context).callDoctorListActivity(doctorCatList.get(getPosition()).getCategory_id(),doctorCatList.get(getPosition()).getCategory_name());
}
}
}

Related

ListView is not showing all JSON data using Retrofit

I'm trying to get all the JSON result into my listview. I have successfully retrieved the data but it keeps only shows one data (example if JNE, only showing OKE result). I'm using Retrofit. Below is the example JSON data from the documentation that I want to show all in my listview. Please help me why it is not showing all the result. Thank you.
{
"rajaongkir":{
"query":{
"origin":"501",
"destination":"114",
"weight":1700,
"courier":"jne"
},
"status":{
"code":200,
"description":"OK"
},
"origin_details":{
"city_id":"501",
"province_id":"5",
"province":"DI Yogyakarta",
"type":"Kota",
"city_name":"Yogyakarta",
"postal_code":"55000"
},
"destination_details":{
"city_id":"114",
"province_id":"1",
"province":"Bali",
"type":"Kota",
"city_name":"Denpasar",
"postal_code":"80000"
},
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
}
}
My Call
public void getCoast(String origin,
String destination,
String weight,
String courier) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiUrl.URL_ROOT_HTTPS)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ItemCost> call = service.getCost(
"c5333cdcc37b3511c909088d99587fd8",
origin,
destination,
weight,
courier
);
call.enqueue(new Callback<ItemCost>() {
#Override
public void onResponse(Call<ItemCost> call, Response<ItemCost> response) {
Log.v("wow", "json : " + new Gson().toJson(response));
progressDialog.dismiss();
if (response.isSuccessful()) {
int statusCode = response.body().getRajaongkir().getStatus().getCode();
if (statusCode == 200) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = inflater.inflate(R.layout.custom_results, null);
alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Result Cost");
alert.setMessage("this result your search");
alert.setView(alertLayout);
alert.setCancelable(true);
ad = alert.show();
String originCity = response.body().getRajaongkir().getOriginDetails().getCityName();
String originPostalCode = response.body().getRajaongkir().getOriginDetails().getPostalCode();
String destinationCity = response.body().getRajaongkir().getDestinationDetails().getCityName();
String destinationPostalCode = response.body().getRajaongkir().getDestinationDetails().getPostalCode();
//results
List<com.bagicode.cekongkir.model.cost.Result> ListResults = response.body().getRajaongkir().getResults();
//costs
List<com.bagicode.cekongkir.model.cost.Cost> ListCosts = response.body().getRajaongkir().getResults().get(0).getCosts();
//cost
List<com.bagicode.cekongkir.model.cost.Cost_> ListCost = response.body().getRajaongkir().getResults().get(0).getCosts().get(0).getCost();
mListView = (ListView) alertLayout.findViewById(R.id.listItem);
adapter_results = new ResultsAdapter(MainActivity.this, originCity, originPostalCode, destinationCity, destinationPostalCode, ListResults, ListCosts, ListCost);
mListView.setAdapter(adapter_results);
mListView.setClickable(true);
adapter_results.notifyDataSetChanged();
} else {
String message = response.body().getRajaongkir().getStatus().getDescription();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
} else {
String error = "Error Retrive Data from Server !!!";
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ItemCost> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Message : Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Api Interface
// Cost
#FormUrlEncoded
#POST("cost")
Call<ItemCost> getCost (#Field("key") String Token,
#Field("origin") String origin,
#Field("destination") String destination,
#Field("weight") String weight,
#Field("courier") String courier);
Pojo
ItemCost
public class ItemCost {
#SerializedName("rajaongkir")
#Expose
private Rajaongkir rajaongkir;
public Rajaongkir getRajaongkir() {
return rajaongkir;
}
public void setRajaongkir(Rajaongkir rajaongkir) {
this.rajaongkir = rajaongkir;
}
}
rajaOngkir Pojo (List)
public class Rajaongkir {
#SerializedName("query")
#Expose
private Query query;
#SerializedName("status")
#Expose
private Status status;
#SerializedName("origin_details")
#Expose
private OriginDetails originDetails;
#SerializedName("destination_details")
#Expose
private DestinationDetails destinationDetails;
#SerializedName("results")
#Expose
private List<Result> results = null;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public OriginDetails getOriginDetails() {
return originDetails;
}
public void setOriginDetails(OriginDetails originDetails) {
this.originDetails = originDetails;
}
public DestinationDetails getDestinationDetails() {
return destinationDetails;
}
public void setDestinationDetails(DestinationDetails destinationDetails) {
this.destinationDetails = destinationDetails;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
Results List Pojo
public class Result {
#SerializedName("code")
#Expose
private String code;
#SerializedName("name")
#Expose
private String name;
#SerializedName("costs")
#Expose
private List<Cost> costs = null;
public Result(String code, String name, List<Cost> costs) {
this.code = code;
this.name = name;
this.costs = costs;
}
public Result(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Cost> getCosts() {
return costs;
}
public void setCosts(List<Cost> costs) {
this.costs = costs;
}
}
Costs List Pojo
public class Cost {
#SerializedName("service")
#Expose
private String service;
#SerializedName("description")
#Expose
private String description;
#SerializedName("cost")
#Expose
private List<Cost_> cost = null;
public Cost(String service, String description) {
this.service = service;
this.description = description;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Cost_> getCost() {
return cost;
}
public void setCost(List<Cost_> cost) {
this.cost = cost;
}
}
cost list Pojo
public class Cost_ {
#SerializedName("value")
#Expose
private Integer value;
#SerializedName("etd")
#Expose
private String etd;
#SerializedName("note")
#Expose
private String note;
public Cost_(Integer value, String etd, String note) {
this.value = value;
this.etd = etd;
this.note = note;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getEtd() {
return etd;
}
public void setEtd(String etd) {
this.etd = etd;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
ListView Adapter
public class ResultsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Result> resulsItems;
private List<Cost> costsItems;
private List<Cost_> costItems;
TextView tv_origin, tv_destination, tv_expedisi, tv_coast, tv_time;
private String originCity, destinationCity, originPostalCode, destinationPostalCode;
public ResultsAdapter(MainActivity mainActivity, String originCity, String originPostalCode, String destinationCity, String destinationPostalCode, List<Result> listResults, List<Cost> listCosts, List<Cost_> listCost) {
this.activity = mainActivity;
this.originCity = originCity;
this.originPostalCode = originPostalCode;
this.destinationCity = destinationCity;
this.destinationPostalCode = destinationPostalCode;
this.resulsItems = listResults;
this.costsItems = listCosts;
this.costItems = listCost;
}
#Override
public int getCount() {
return resulsItems.size();
}
#Override
public Object getItem(int location) {
return resulsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.item_results, null);
tv_origin = (TextView) convertView.findViewById(R.id.tv_origin);
tv_destination = (TextView) convertView.findViewById(R.id.tv_destination);
tv_expedisi = convertView.findViewById(R.id.tv_expedisi);
tv_coast = convertView.findViewById(R.id.tv_coast);
tv_time = convertView.findViewById(R.id.tv_time);
results = resulsItems.get(i);
costs = costsItems.get(i);
cost = costItems.get(i);
tv_origin.setText(originCity);
tv_destination.setText(destinationCity);
tv_expedisi.setText(results.getName());
tv_coast.setText(String.valueOf(cost.getValue()));
tv_time.setText(cost.getEtd());
return convertView;
}
}
ACtual Response Log
{"body":{"rajaongkir":{"destination_details":{"city_id":"114","city_name":"Denpasar","postal_code":"80227","province":"Bali","province_id":"1","type":"Kota"},"origin_details":{"city_id":"501","city_name":"Yogyakarta","postal_code":"55111","province":"DI Yogyakarta","province_id":"5","type":"Kota"},"query":{"courier":"jne","destination":"114","key":"c5333cdcc37b3511c909088d99587fd8","origin":"501","weight":1000},"results":[{"code":"jne","costs":[{"cost":[{"etd":"4-5","note":"","value":26000}],"description":"Ongkos Kirim Ekonomis","service":"OKE"},{"cost":[{"etd":"2-3","note":"","value":28000}],"description":"Layanan Reguler","service":"REG"},{"cost":[{"etd":"1-1","note":"","value":43000}],"description":"Yakin Esok Sampai","service":"YES"}],"name":"Jalur Nugraha Ekakurir (JNE)"}],"status":{"code":200,"description":"OK"}}},"rawResponse":{"body":{"contentLength":823,"contentType":{"mediaType":"application/json","subtype":"json","type":"application"}},"code":200,"handshake":{"cipherSuite":"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","localCertificates":[],"peerCertificates":[{"hash":-1,"type":"X.509"},{"hash":-1,"type":"X.509"}],"tlsVersion":"TLS_1_2"},"headers":{"namesAndValues":["Date","Thu, 02 May 2019 13:09:21 GMT","Server","Apache/2.4.7 (Ubuntu)","Content-Length","823","Keep-Alive","timeout\u003d15, max\u003d100","Connection","Keep-Alive","Content-Type","application/json"]},"message":"OK","networkResponse":{"code":200,"handshake":{"cipherSuite":"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","localCertificates":[],"peerCertificates":[{"hash":-1,"type":"X.509"},{"hash":-1,"type":"X.509"}],"tlsVersion":"TLS_1_2"},"headers":{"namesAndValues":["Date","Thu, 02 May 2019 13:09:21 GMT","Server","Apache/2.4.7 (Ubuntu)","Content-Length","823","Keep-Alive","timeout\u003d15, max\u003d100","Connection","Keep-Alive","Content-Type","application/json"]},"message":"OK","protocol":"HTTP_1_1","receivedResponseAtMillis":1556802600578,"request":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"cacheControl":{"isPrivate":false,"isPublic":false,"maxAgeSeconds":-1,"maxStaleSeconds":-1,"minFreshSeconds":-1,"mustRevalidate":false,"noCache":false,"noStore":false,"noTransform":false,"onlyIfCached":false,"sMaxAgeSeconds":-1},"headers":{"namesAndValues":["Content-Type","application/x-www-form-urlencoded","Content-Length","87","Host","api.rajaongkir.com","Connection","Keep-Alive","Accept-Encoding","gzip","User-Agent","okhttp/3.3.0"]},"method":"POST","tag":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"sentRequestAtMillis":1556802600415},"protocol":"HTTP_1_1","receivedResponseAtMillis":1556802600578,"request":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":["Content-Type","application/x-www-form-urlencoded","Content-Length","87"]},"method":"POST","tag":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"sentRequestAtMillis":1556802600415}}
public void getCoast(String origin,
String destination,
String weight,
String courier) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiUrl.URL_ROOT_HTTPS)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ItemCost> call = service.getCost(
"c5333cdcc37b3511c909088d99587fd8",
origin,
destination,
weight,
courier
);
call.enqueue(new Callback<ItemCost>() {
#Override
public void onResponse(Call<ItemCost> call, Response<ItemCost> response) {
Log.v("wow", "json : " + new Gson().toJson(response));
progressDialog.dismiss();
if (response.isSuccessful()) {
int statusCode = response.body().getRajaongkir().getStatus().getCode();
if (statusCode == 200) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = inflater.inflate(R.layout.custom_results, null);
alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Result Cost");
alert.setMessage("this result your search");
alert.setView(alertLayout);
alert.setCancelable(true);
ad = alert.show();
String originCity = response.body().getRajaongkir().getOriginDetails().getCityName();
String originPostalCode = response.body().getRajaongkir().getOriginDetails().getPostalCode();
String destinationCity = response.body().getRajaongkir().getDestinationDetails().getCityName();
String destinationPostalCode = response.body().getRajaongkir().getDestinationDetails().getPostalCode();
//results
List<com.bagicode.cekongkir.model.cost.Result> ListResults = response.body().getRajaongkir().getResults();
//costs
List<com.bagicode.cekongkir.model.cost.Cost> ListCosts = response.body().getRajaongkir().getResults().get(0).getCosts();
//cost
List<com.bagicode.cekongkir.model.cost.Cost_> ListCost = response.body().getRajaongkir().getResults().get(0).getCosts().get(0).getCost();
mListView = (ListView) alertLayout.findViewById(R.id.listItem);
adapter_results = new ResultsAdapter(MainActivity.this, originCity, originPostalCode, destinationCity, destinationPostalCode, ListResults, ListCosts, ListCost);
mListView.setAdapter(adapter_results);
mListView.setClickable(true);
adapter_results.notifyDataSetChanged();
} else {
String message = response.body().getRajaongkir().getStatus().getDescription();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
} else {
String error = "Error Retrive Data from Server !!!";
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ItemCost> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Message : Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

I want to fetch array values of users by calling API

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

Firebase model POJO getter returns null in FirebaseRecyclerAdapter

I have a FirebaseRecyclerAdapter fetching data from the firebase database but when I am trying to access firebase data the getter method of the POJO returns null. I am able to get the database reference key.
final Query beveragesQuery = mDatabaseReference.child(FirebaseValues.PRODUCTS)
.child(FirebaseValues.BEVERAGES);
FirebaseRecyclerOptions<GenericProductModel> beveragesOptions =
new FirebaseRecyclerOptions.Builder<GenericProductModel>()
.setQuery(beveragesQuery, GenericProductModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<GenericProductModel, Combos.MovieViewHolder>(
beveragesOptions
) {
#NonNull
#Override
public Combos.MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_cardview_layout, parent, false);
return new Combos.MovieViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Combos.MovieViewHolder viewHolder, int position, #NonNull GenericProductModel model) {
Log.d(TAG, "Item received:"+getRef(position).getKey());
String json = new Gson().toJson(model);
Log.d(TAG, "Item received:"+ json);
Log.d(TAG, "Item received:"+ model.toString());
if (tv_no_item.getVisibility() == View.VISIBLE) {
tv_no_item.setVisibility(View.GONE);
}
Log.d(TAG, "card name:"+model.getCardname());
viewHolder.cardname.setText(model.getCardname());
viewHolder.cardprice.setText("₹ " + Float.toString(model.getCardprice()));
Picasso.get().load(model.getCardimage()).into(viewHolder.cardimage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Beverages.this, IndividualProduct.class);
intent.putExtra("product", getItem(position));
startActivity(intent);
}
});
}
#Override
public void onError(DatabaseError e) {
Log.e(TAG, "RV Adapter, Error occurred: " + e.getMessage());
}
};
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
adapter.startListening();
mRecyclerView.setAdapter(adapter);
}
My POJO or model class is
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
I am implementing Serializable because I am sending this data as an intent to other activity.
Added some more log options for clearity
When I run the app the log output I am getting is:
03-17 15:05:55.200 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received, received:1
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:{"a":0,"e":0.0}
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:com.vdeveloper.chaisutta.b.a#63d3fc
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: card name:null
Database Screenshot:
I have found a solution myself. The problem was with my POJO. As this project was on androidx I need to add the annotation "#Keep" to stop the compiler from removing methods which it thinks are redundant.
import java.io.Serializable;
import androidx.annotation.Keep;
#Keep
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
Thanks, everyone for helping
You are getting null because all your values are null since you are returning in each getter this.fieldName instead of the fieldName. To solve this, please change your getters to:
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
See, there is no this anymore.

Attempt to invoke virtual method on a null object reference Error in my application.any suggestion wlcome.Thanks [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
REST API XML
posts[
{
"id": 16344,
"date": "2017-11-29T12:45:58",
"date_gmt": "2017-11-29T07:15:58",
"modified": "2017-11-29T12:45:58",
"modified_gmt": "2017-11-29T07:15:58",
"type": "post",
"title": {
"rendered": "This is post from example.com"
},
"content": {
"rendered": "This is post from example.com\n",
"protected": false
},
"excerpt": {
"rendered": "This is post from example.com \n",
"protected": false
},
"featured_media": 0,
"categories": [
1
],
"better_featured_image": {
"id": 16221,
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"media_details": {
"width": 1070,
"height": 286,
"sizes": {
"thumbnail": {
"file": "under_construction-e1509092603289-150x150.jpg",
"width": 150,
"height": 150,
"mime-type": "image/jpeg",
"source_url": "http://example.com/under_construction- e1509092603289-150x150.jpg"
}
}
}
}
}
]
public class PostList {
#SerializedName("date")
#Expose
private String date;
#SerializedName("title")
#Expose
private Title title;
#SerializedName("excerpt")
#Expose
private Excerpt excerpt;
#SerializedName("better_featured_image")
#Expose
private FeaturedImage betterFeaturedImage;
#SerializedName("categories")
#Expose
private List<Integer> categories = null;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Title getTitle() {
return title;
}
public void setTitle(Title title) {
this.title = title;
}
public Excerpt getExcerpt() {
return excerpt;
}
public void setExcerpt(Excerpt excerpt) {
this.excerpt = excerpt;
}
public FeaturedImage getBetterFeaturedImage() {
return betterFeaturedImage;
}
public void setBetterFeaturedImage(FeaturedImage betterFeaturedImage) {
this.betterFeaturedImage = betterFeaturedImage;
}
public List<Integer> getCategories() {
return categories;
}
public void setCategories(List<Integer> categories) {
this.categories = categories;
}
public class FeaturedImage {
#SerializedName("media_details")
#Expose
private MediaDetail media_details = null;
public MediaDetail getMedia_details() {
return media_details;
}
public void setMedia_details(MediaDetail media_details) {
this.media_details = media_details;
}
}
public class MediaDetail {
#SerializedName("sizes")
#Expose
private Sizes sizes = null;
public Sizes getSizes() {
return sizes;
}
public void setSizes(Sizes sizes) {
this.sizes = sizes;
}
}
public class Sizes {
#SerializedName("medium")
#Expose
private Medium medium = null;
public Medium getMedium() {
return medium;
}
public void setMedium(Medium medium) {
this.medium = medium;
}
}
public class Medium {
#SerializedName("source_url")
#Expose
private String source_url;
public String getSource_url() {
return source_url;
}
public void setSource_url(String source_url) {
this.source_url = source_url;
}
}
public class ProgramingAdapter extends RecyclerView.Adapter {
Context context;
private PostList[] data;
public ProgramingAdapter(Context context, PostList[] data) {
this.context = context;
this.data = data;
}
#Override
public ProgramingViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item, parent, false);
return new ProgramingViewHolder(view);
}
#Override
public void onBindViewHolder(ProgramingViewHolder holder, int position) {
PostList FImage = data[position];
final String Tit = FImage.getTitle().getRendered();
if (Tit.length() <= 70) {
holder.txtTitle.setText(Tit);
} else {
String TitNew = FImage.getTitle().getRendered().substring(0, 70);
holder.txtTitle.setText(TitNew + "...");
}
String Cat = FImage.getCategories().toString();
String Cat1 = Cat.replaceAll("\\[", "").replaceAll("\\]", "");
holder.txtCat.setText(Cat1);
String date = FImage.getDate().substring(0, 10);
holder.txtDate.setText(date);
String Exc = FImage.getExcerpt().getRendered();
if (Exc.length() <= 80) {
holder.txtExc.setText(Exc);
} else {
String ExcNew = FImage.getExcerpt().getRendered().substring(0, 80);
holder.txtExc.setText(ExcNew + "...");
}
Picasso.with(holder.ImgIcon.getContext()).load(FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()).into(holder.ImgIcon);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(context, Tit , Toast.LENGTH_SHORT).show();
return false;
}
});
}
#Override
public int getItemCount() {
return data.length;
}
public class ProgramingViewHolder extends RecyclerView.ViewHolder {
ImageView ImgIcon;
TextView txtTitle;
TextView txtDate;
TextView txtExc;
TextView txtCat;
public ProgramingViewHolder(View itemView) {
super(itemView);
ImgIcon = itemView.findViewById(R.id.Img);
txtTitle = itemView.findViewById(R.id.Title);
txtDate = itemView.findViewById(R.id.Date);
txtExc = itemView.findViewById(R.id.Exc);
txtCat = itemView.findViewById(R.id.Cat);
}
}
}
public class MainActivity extends AppCompatActivity {
ImageView imageView;
private static final String URL = "http://example.com/wp-json/wp/v2/posts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.Img);
final RecyclerView programingList = (RecyclerView) findViewById(R.id.progeramingList);
programingList.setLayoutManager(new LinearLayoutManager(this));
final StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("PostList", response);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
PostList[] post = gson.fromJson(response, PostList[].class);
programingList.setAdapter(new ProgramingAdapter(MainActivity.this, post));
Toast.makeText(MainActivity.this, "Ok", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
}
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dev.recycler_new, PID: 7965
java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.dev.recycler_new.MediaDetail com.example.dev.recycler_new.FeaturedImage.getMedia_details()' on a null object reference
at com.example.dev.recycler_new.ProgramingAdapter.onBindViewHolder(ProgramingAdapter.java:70)
at com.example.dev.recycler_new.ProgramingAdapter.onBindViewHolder(ProgramingAdapter.java:20)
your error comes from ProgramingAdapter class Picasso.with(holder.ImgIcon.getContext()).load(FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()).into(holder.ImgIcon);
this line you are loading wrong image data like
FImage.getBetterFeaturedImage().getMedia_details().getSizes().getMedium().toString()
so check this properly your picasso load image code like below
Picasso.with(context).load(my_data.get(position).getPhoto())
.into(holder.ImgIcon);
pass context instead holder.ImgIcon.getContext()

How to get the json data from server in recycler view in Android using Retrofit?

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.

Categories

Resources