Retrofit Returns Null value - android

I'm new to Android networking. I'm unable to figure out why I'm getting null value for the phonone
This is a sample of JSON data:
{
"columns":{ <some data here> },
"rows":[
{
"timestamp":"28/08/2016 14:11:46",
"name":"Mohammed Sohail",
"phoneno.":8142629002,
"event-name":"Roadies",
"branch":"IT",
"year":3
},
{
"timestamp":"28/08/2016 14:13:03",
"name":"Shaik Asaduddin",
"phoneno.":8143026049,
"event-name":"Ted talk",
"branch":"IT",
"year":3
}
}
I'm able to get every value inside row array except "phoneno" it gives me null value
Here are my classes
Registration class:
public class Registration {
private Columns columns;
private List<Row> rows = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public Columns getColumns() {
return columns;
}
public void setColumns(Columns columns) {
this.columns = columns;
}
public List<Row> getRows() {
return rows;
}
public void setRows(List<Row> rows) {
this.rows = rows;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Row class:
public class Row {
private String timestamp;
private String name;
private String phoneno;
private String eventName;
private String branch;
private String year;
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
and here is the adapter I'm using to set the text view's
public class RegistrationAdapter extends RecyclerView.Adapter<RegistrationAdapter.RegistrationViewHolder> {
private List<Row> rows;
private Context context;
private int rowLayout;
public RegistrationAdapter(List<Row> rows) {
this.rows=rows;
}
#Override
public RegistrationAdapter.RegistrationViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.registration_item_view, parent, false);
return new RegistrationViewHolder(view);
}
#Override
public void onBindViewHolder(RegistrationViewHolder holder, int position) {
holder.studentName.setText(rows.get(position).getName());
holder.studentPhone.setText(String.valueOf(rows.get(position).getPhoneno()));
holder.studentBranch.setText(rows.get(position).getBranch());
holder.studentYear.setText(rows.get(position).getYear());
}
#Override
public int getItemCount() {
return rows.size();
}
public class RegistrationViewHolder extends RecyclerView.ViewHolder {
LinearLayout studentLayout;
TextView studentName;
TextView studentPhone;
TextView studentBranch;
TextView studentYear;
public RegistrationViewHolder(View itemView) {
super(itemView);
studentLayout=(LinearLayout)itemView.findViewById(R.id.studentLayout);
studentName=(TextView)itemView.findViewById(R.id.studentName);
studentPhone=(TextView)itemView.findViewById(R.id.studentPhoneNumber);
studentBranch=(TextView)itemView.findViewById(R.id.studentBranch);
studentYear=(TextView)itemView.findViewById(R.id.studentYear);
}
}
public RegistrationAdapter( List<Row> rows, int rowLayout,Context context) {
this.rows = rows;
this.rowLayout = rowLayout;
this.context = context;
}
}

Maybe is a typo but in your json you have "phoneno." and your row class specifies phoneno.

you can you use jsonschema2pojo to genenare class from json object.

Related

How to insert RealmList to RealmDB

I am trying to insert realm lists to my realmdb in my first insert there is no problem but when I insert another realmList with a different class, my old values are deleted. So how can I insert a realmlist to DB? inserts are done separately.
RealmList<Product> insertedProduct = new RealmList<Product>();
RealmList<ProductSubCategory> insertedSubCategory = new RealmList<ProductSubCategory>();
RealmList<ProductMainCategory> insertedMainCategory = new RealmList<ProductMainCategory>();
... inserting to realm list firt time ...
insertRealmList(insertedProduct); //inserting to realmDB first time
insertRealmList(insertedSubCategory); //inserting to realmDB first time
insertRealmList(insertedMainCategory); //inserting to realmDB first time
first insert to realmDB
RealmList insert function
private void insertRealmList(final RealmList realmObject) {
mRealm = Realm.getDefaultInstance();
realmTask = mRealm.executeTransactionAsync(
new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.copyToRealmOrUpdate(realmObject);
}
},
new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Log.i(TAG, "onSuccess: successfully inserted data");
}
},
new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "onError: error while inserting " + "error: " + error);
}
}
);
}
... inserting to realm list second time...
insertRealmList(insertedLanguages); //insert realmDB second time
second insert to realmDB
PRODUCT MODEL
package Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.Ignore;
import io.realm.annotations.Index;
import io.realm.annotations.PrimaryKey;
public class Product extends RealmObject {
#PrimaryKey
#Index
private int ID;
#Index
private int PLU_NO;
private String PRODUCT_NAME;
private String MAIN_CATEGORY;
private String SUB_CATEGORY;
private String TYPE;
private String TUS;
private Double PRICE;
private String CALORIE;
private String COOKING_TIME;
private RealmList<String> PRODUCT_NAME_LANGUAGES;
private RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES;
private String IMAGE_BASE_HORIZONTAL; //4/3
private String IMAGE_BASE_VERTICAL; //16/9
private String VIDEO_NAME; //video name
#Ignore
private int AMOUNT;
#Ignore
private int WINDOW_AMOUNT = 1;
public Product(int ID, int PLU_NO, String PRODUCT_NAME, String MAIN_CATEGORY, String SUB_CATEGORY, String TYPE, String TUS, Double PRICE, String CALORIE, String COOKING_TIME, RealmList<String> PRODUCT_NAME_LANGUAGES, RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES, String IMAGE_BASE_HORIZONTAL, String IMAGE_BASE_VERTICAL, String VIDEO_NAME) {
this.ID = ID;
this.PLU_NO = PLU_NO;
this.PRODUCT_NAME = PRODUCT_NAME;
this.MAIN_CATEGORY = MAIN_CATEGORY;
this.SUB_CATEGORY = SUB_CATEGORY;
this.TYPE = TYPE;
this.TUS = TUS;
this.PRICE = PRICE;
this.CALORIE = CALORIE;
this.COOKING_TIME = COOKING_TIME;
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
this.VIDEO_NAME = VIDEO_NAME;
}
public Product() {
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getPLU_NO() {
return PLU_NO;
}
public void setPLU_NO(int PLU_NO) {
this.PLU_NO = PLU_NO;
}
public String getPRODUCT_NAME() {
return PRODUCT_NAME;
}
public void setPRODUCT_NAME(String PRODUCT_NAME) {
this.PRODUCT_NAME = PRODUCT_NAME;
}
public String getMAIN_CATEGORY() {
return MAIN_CATEGORY;
}
public void setMAIN_CATEGORY(String MAIN_CATEGORY) {
this.MAIN_CATEGORY = MAIN_CATEGORY;
}
public String getSUB_CATEGORY() {
return SUB_CATEGORY;
}
public void setSUB_CATEGORY(String SUB_CATEGORY) {
this.SUB_CATEGORY = SUB_CATEGORY;
}
public String getTYPE() {
return TYPE;
}
public void setTYPE(String TYPE) {
this.TYPE = TYPE;
}
public String getTUS() {
return TUS;
}
public void setTUS(String TUS) {
this.TUS = TUS;
}
public Double getPRICE() {
return PRICE;
}
public void setPRICE(Double PRICE) {
this.PRICE = PRICE;
}
public String getCALORIE() {
return CALORIE;
}
public void setCALORIE(String CALORIE) {
this.CALORIE = CALORIE;
}
public String getCOOKING_TIME() {
return COOKING_TIME;
}
public void setCOOKING_TIME(String COOKING_TIME) {
this.COOKING_TIME = COOKING_TIME;
}
public RealmList<String> getPRODUCT_NAME_LANGUAGES() {
return PRODUCT_NAME_LANGUAGES;
}
public void setPRODUCT_NAME_LANGUAGES(RealmList<String> PRODUCT_NAME_LANGUAGES) {
this.PRODUCT_NAME_LANGUAGES = PRODUCT_NAME_LANGUAGES;
}
public RealmList<String> getPRODUCT_DESCRIPTION_LANGUAGES() {
return PRODUCT_DESCRIPTION_LANGUAGES;
}
public void setPRODUCT_DESCRIPTION_LANGUAGES(RealmList<String> PRODUCT_DESCRIPTION_LANGUAGES) {
this.PRODUCT_DESCRIPTION_LANGUAGES = PRODUCT_DESCRIPTION_LANGUAGES;
}
public String getIMAGE_BASE_HORIZONTAL() {
return IMAGE_BASE_HORIZONTAL;
}
public void setIMAGE_BASE_HORIZONTAL(String IMAGE_BASE_HORIZONTAL) {
this.IMAGE_BASE_HORIZONTAL = IMAGE_BASE_HORIZONTAL;
}
public String getIMAGE_BASE_VERTICAL() {
return IMAGE_BASE_VERTICAL;
}
public void setIMAGE_BASE_VERTICAL(String IMAGE_BASE_VERTICAL) {
this.IMAGE_BASE_VERTICAL = IMAGE_BASE_VERTICAL;
}
public String getVIDEO_NAME() {
return VIDEO_NAME;
}
public void setVIDEO_NAME(String VIDEO_NAME) {
this.VIDEO_NAME = VIDEO_NAME;
}
public int getAMOUNT() {
return AMOUNT;
}
public void setAMOUNT(int AMOUNT) {
this.AMOUNT = AMOUNT;
}
public int getWINDOW_AMOUNT() {
return WINDOW_AMOUNT;
}
public void setWINDOW_AMOUNT(int WINDOW_AMOUNT) {
this.WINDOW_AMOUNT = WINDOW_AMOUNT;
}
public void setDEFAULT_WINDOW_AMOUNT() {
this.WINDOW_AMOUNT = 1;
}
}
LANGUAGE MODEL
package Model;
import io.realm.RealmObject;
public class Language extends RealmObject {
#PrimaryKey
#Index
private int ID;
private String ICON;
private String NAME;
public Language(){
}
public Language(int ID, String ICON, String NAME) {
this.ID = ID;
this.ICON = ICON;
this.NAME = NAME;
}
public int getId() {
return ID;
}
public void setId(int id) {
this.ID = id;
}
public String getICON() {
return ICON;
}
public void setICON(String ICON) {
this.ICON = ICON;
}
public String getName() {
return NAME;
}
public void setName(String name) {
this.NAME = name;
}
}
Other two models are similar with product.
Please try the following method:
private <T extends RealmModel> void insertRealmList(final List<T> objects) {
try (Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction(realm -> {
for (T object : objects) {
realmInstance.insertOrUpdate(object);
}
});
}
}
Hope this helps!

Android Nested Objects and Retrofit2

I am reading a JSON like this:
{
"matches": [{
"id": 246119,
"utcDate": "2018-08-17T18:15:00Z",
"status": "FINISHED",
"homeTeam": {
"id": 298,
"name": "Girona FC"
},
"awayTeam": {
"id": 250,
"name": "Real Valladolid CF"
},
"score": {
"winner": "DRAW",
"duration": "REGULAR"
}
}]
}
I must say that the JSON is valid. I am consuming this JSON through an API. I can correctly read the properties "id", "utc" and "status", but I could not with "score", "awayTeam" and "homeTeam". I don't really know how to work those properties. I'd like to handle each propertie of score, awayTeam, and homeTeam individually, for example, I want to get just the name of awayTeam and homeTeam and the 2 properties of score.
This, is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private static final String TAG = "Football";
private RecyclerView recyclerView;
private ListaPartidosAdapter listaPartidosAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
listaPartidosAdapter = new ListaPartidosAdapter(this);
recyclerView.setAdapter(listaPartidosAdapter);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, VERTICAL, true);
recyclerView.setLayoutManager(layoutManager);
retrofit = new Retrofit.Builder()
.baseUrl("http://api.football-data.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
obtenerDatos();
}
private void obtenerDatos() {
footballdataService service = retrofit.create(footballdataService.class);
Call<PartidosRespuesta> partidosRespuestaCall = service.obtenerlistaPartidos();
partidosRespuestaCall.enqueue(new Callback<PartidosRespuesta>() {
#Override
public void onResponse(Call<PartidosRespuesta> call, Response<PartidosRespuesta> response) {
if(response.isSuccessful()) {
PartidosRespuesta partidosRespuesta = response.body();
ArrayList<Partido> listaPartidos = partidosRespuesta.getMatches();
listaPartidosAdapter.adicionarListaPartidos(listaPartidos);
}
else {
Log.e(TAG, "onResponse: " + response.errorBody());
}
}
#Override
public void onFailure(Call<PartidosRespuesta> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Now this is my interface. footballdataService
public interface footballdataService {
#GET("competitions/2014/matches")
Call<PartidosRespuesta> obtenerlistaPartidos();
}
This is PartidosRespuestas class
public class PartidosRespuesta {
private ArrayList<Partido> matches;
public ArrayList<Partido> getMatches() {
return matches;
}
public void setMatches(ArrayList<Partido> matches) {
this.matches = matches;
}
}
This, is the adapter.
public class ListaPartidosAdapter extends RecyclerView.Adapter<ListaPartidosAdapter.ViewHolder> {
private static final String TAG = "Football_Adapter";
private ArrayList<Partido> dataset;
private Context context;
public ListaPartidosAdapter(Context context) {
this.context = context;
dataset = new ArrayList<Partido>();
}
#Override
public ListaPartidosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_partidos, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
holder.status.setText(p.getId());
}
#Override
public int getItemCount() {
return dataset.size();
}
public void adicionarListaPartidos(ArrayList<Partido> listaPartidos){
dataset.addAll(listaPartidos);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView status;
public ViewHolder(View itemView) {
super(itemView);
status = (TextView) itemView.findViewById(R.id.status);
}
}
}
And this.., is Partido class
public class Partido {
private String id;
private String utcDate;
private String status;
private EquipoCasa homeTeam;
private EquipoVisita AwayTeam;
private Puntaje score;
public String getId() {
return id;
}
public String getUtcDate() {
return utcDate;
}
public String getStatus() {
return status;
}
public EquipoCasa getHomeTeam() {
return homeTeam;
}
public EquipoVisita getAwayTeam() {
return AwayTeam;
}
public Puntaje getScore() {
return score;
}
public void setId(String id) {
this.id = id;
}
public void setUtcDate(String utcDate) {
this.utcDate = utcDate;
}
public void setStatus(String status) {
this.status = status;
}
public void setHomeTeam(EquipoCasa homeTeam) {
this.homeTeam = homeTeam;
}
public void setAwayTeam(EquipoVisita awayTeam) {
AwayTeam = awayTeam;
}
public void setScore(Puntaje score) {
this.score = score;
}
public class EquipoCasa {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class EquipoVisita {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Puntaje {
private String winner;
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
}
POJO classes of your code should this:
AwayTeam.java
//AwayTeam
public class AwayTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PartidosRespuesta.java
//Object response
public class PartidosRespuesta {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
HomeTeam.java
//HomeTeam
public class HomeTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Score.java
//Score
public class Score {
#SerializedName("winner")
#Expose
private String winner;
#SerializedName("duration")
#Expose
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Edit:
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
HomeTeam homeTeam = p.getHomeTeam();
String nameHomeTeam = homeTeam.getName();
}
And tool convert json to java code: http://www.jsonschema2pojo.org/
try
public class Puntaje {
public String winner;
public String duration;
}
It's seems like you've problems with your models. Use this link to convert your json to java object.

RecyclerView adapter gets string from model as a memory object

I have pretty normal recyclerview adapter. I pass the list of array to the adapter and trying set images from link as needed with Glide.
Problem is, when I try to get images link with loggin they seem normal, but when I pass data list to adapter they are not working. And giving memory object instead of String.
I should get this:
http://somelin.com/image.jpg
Instead I get this:
package.name.models.responses.chain.Logo_#c170923
What should I do? My adapter works normally as I am using this adapter in other places in the same way and it works.
My adapter
public class ChainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<Restaurant> modelList;
private OnItemClickListener mItemClickListener;
public ChainAdapter(Context context, ArrayList<Restaurant> modelList) {
this.mContext = context;
this.modelList = modelList;
}
public void updateList(ArrayList<Restaurant> modelList) {
this.modelList = modelList;
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_chain_list, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
//Here you can fill your row view
if (holder instanceof ViewHolder) {
final Restaurant model = getItem(position);
ViewHolder genericViewHolder = (ViewHolder) holder;
String link = "http://cdn.link.in/unsafe/" + model.getLogo();
System.out.println("chainAdapter " + link);
Glide.with(mContext).load(link).into(genericViewHolder.rest_logo);
CenteredImageSpan imagespan = new CenteredImageSpan(mContext, R.drawable.verified_account);
Spannable text = new SpannableString(model.getName() + " ");
text.setSpan(imagespan, model.getName().length(), model.getName().length() + 1, 0); //text is an object of TextView
if (model.getVerified()) {
genericViewHolder.rest_name.setText(text);
} else {
genericViewHolder.rest_name.setText(model.getName());
}
Calendar today = Calendar.getInstance();
List<Today> hours = model.getToday();
for (Today hour : hours) {
if (hour.getWeekday() == today.get(Calendar.DAY_OF_WEEK) - 1) {
genericViewHolder.restCloseNowIcon.setImageResource(R.drawable.ic_open_now);
genericViewHolder.restCloseNowText.setText(mContext.getString(R.string.open_now));
genericViewHolder.restCloseNowText.setTextColor(mContext.getResources().getColor(R.color.open_now));
} else {
genericViewHolder.restCloseNowIcon.setImageResource(R.drawable.ic_close_now);
genericViewHolder.restCloseNowText.setText(mContext.getString(R.string.close_now));
genericViewHolder.restCloseNowText.setTextColor(mContext.getResources().getColor(R.color.close_now));
}
}
int totalRatings = model.getTotalRatings();
if (totalRatings != 0)
genericViewHolder.restStars.setText((int) totalRatings + "");
}
}
#Override
public int getItemCount() {
return modelList.size();
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
private Restaurant getItem(int position) {
return modelList.get(position);
}
public interface OnItemClickListener {
void onItemClick(View view, int position, Restaurant model);
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.imageView8)
ImageView rest_logo;
#BindView(R.id.textView3)
TextView rest_name;
#BindView(R.id.isVerified)
ImageView isVerified;
#BindView(R.id.rest_close_now_icon)
ImageView restCloseNowIcon;
#BindView(R.id.rest_close_now_text)
TextView restCloseNowText;
#BindView(R.id.rest_stars)
TextView restStars;
public ViewHolder(final View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(view -> mItemClickListener.onItemClick(itemView, getAdapterPosition(), modelList.get(getAdapterPosition())));
}
}
}
Model
public class Restaurant implements Parcelable
{
#SerializedName("username")
#Expose
private String username;
#SerializedName("total_ratings")
#Expose
private Integer totalRatings;
#SerializedName("verified")
#Expose
private Boolean verified;
#SerializedName("name")
#Expose
private String name;
#SerializedName("logo")
#Expose
private Logo_ logo;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("today")
#Expose
private List<Today> today = null;
#SerializedName("thumbnail")
#Expose
private Thumbnail thumbnail;
public final static Creator<Restaurant> CREATOR = new Creator<Restaurant>() {
#SuppressWarnings({
"unchecked"
})
public Restaurant createFromParcel(Parcel in) {
return new Restaurant(in);
}
public Restaurant[] newArray(int size) {
return (new Restaurant[size]);
}
}
;
protected Restaurant(Parcel in) {
this.username = ((String) in.readValue((String.class.getClassLoader())));
this.totalRatings = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.verified = ((Boolean) in.readValue((Boolean.class.getClassLoader())));
this.name = ((String) in.readValue((String.class.getClassLoader())));
this.logo = ((Logo_) in.readValue((Logo_.class.getClassLoader())));
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
in.readList(this.today, (Today.class.getClassLoader()));
this.thumbnail = ((Thumbnail) in.readValue((Thumbnail.class.getClassLoader())));
}
/**
* No args constructor for use in serialization
*
*/
public Restaurant() {
}
/**
*
* #param id
* #param logo
* #param username
* #param thumbnail
* #param verified
* #param name
* #param today
* #param totalRatings
*/
public Restaurant(String username, Integer totalRatings, Boolean verified, String name, Logo_ logo, Integer id, List<Today> today, Thumbnail thumbnail) {
super();
this.username = username;
this.totalRatings = totalRatings;
this.verified = verified;
this.name = name;
this.logo = logo;
this.id = id;
this.today = today;
this.thumbnail = thumbnail;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getTotalRatings() {
return totalRatings;
}
public void setTotalRatings(Integer totalRatings) {
this.totalRatings = totalRatings;
}
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Logo_ getLogo() {
return logo;
}
public void setLogo(Logo_ logo) {
this.logo = logo;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Today> getToday() {
return today;
}
public void setToday(List<Today> today) {
this.today = today;
}
public Thumbnail getThumbnail() {
return thumbnail;
}
public void setThumbnail(Thumbnail thumbnail) {
this.thumbnail = thumbnail;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(username);
dest.writeValue(totalRatings);
dest.writeValue(verified);
dest.writeValue(name);
dest.writeValue(logo);
dest.writeValue(id);
dest.writeList(today);
dest.writeValue(thumbnail);
}
public int describeContents() {
return 0;
}
}
Model Logo_
public class Logo_ implements Parcelable {
#SerializedName("path")
#Expose
private String path;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("caption")
#Expose
private String caption;
public final static Creator<Logo_> CREATOR = new Creator<Logo_>() {
#SuppressWarnings({
"unchecked"
})
public Logo_ createFromParcel(Parcel in) {
return new Logo_(in);
}
public Logo_[] newArray(int size) {
return (new Logo_[size]);
}
}
;
protected Logo_(Parcel in) {
this.path = ((String) in.readValue((String.class.getClassLoader())));
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.caption = ((String) in.readValue((String.class.getClassLoader())));
}
/**
* No args constructor for use in serialization
*
*/
public Logo_() {
}
/**
*
* #param id
* #param path
* #param caption
*/
public Logo_(String path, Integer id, String caption) {
super();
this.path = path;
this.id = id;
this.caption = caption;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(path);
dest.writeValue(id);
dest.writeValue(caption);
}
public int describeContents() {
return 0;
}
}
As you've discovered the problem is in this line:
String link = "YOUR_URL" + model.getLogo();
Your method getLogo() does not return a string to be appended here, but rather an object of type Logo_. You have 3 options:
Change the method getLogo in your model to return a String (probably the logo filename).
In the Logo object, create another method to return the name and call it like this:
String link = "YOUR_URL" + model.getLogo().getFilename();
3.Override the toString method in your Logo object to return the filename.
#Override
public String toString(){
return this.filename;
}
Edit: You can use the getPath() in your logo POJO:
String link = "YOUR_URL" + model.getLogo().getPath();

Nested object in Json

This is my JSON:
I need to access to extra_services and get the service_name.
I know I can do it directly using Gson but the problem is that I need to use getters and setters because I'm using an adapter inside of a recycler, how can I do that?
here is my adapter class where I need to get the service name
public class ExtraServicesAdapter extends RecyclerView.Adapter<ExtraServicesAdapter.ViewHolder> implements View.OnClickListener
{
private ArrayList<Business> businessList;
private Activity activity;
private int layoutMolde,idb;
public ExtraServicesAdapter(Activity activity, ArrayList<Business> list, int layout)
{
this.activity = activity;
this.businessList = list;
layoutMolde = layout;
}
#Override
public ExtraServicesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_services_basic, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
if(businessList.get(position).getExtra_services()==null)
{
holder.txtNameServiceBasic.setText("There's nothing to show");
}
holder.txtNameServiceBasic.setText(businessList.get(position).getExtra_services());
}
#Override
public int getItemCount()
{
return businessList.size();
}
#Override
public void onClick(View v)
{
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView txtNameServiceBasic;
public ViewHolder( View itemView)
{
super(itemView);
txtNameServiceBasic = (TextView) itemView.findViewById(R.id.txtNameServiceBasic);
}
}
}
and this is my class where are the getters and setters that I'm using
public class Business {
private Integer id,rating;
private String name, description, cover_url_string, logo_url_string, icon_default,business_name,cover_default,extra_services;
private Boolean status;
public Business(){}
public Business(Integer id,Integer rating,String business_name, String name, String description, String logo_url_string, String cover_default, String icon_default,String cover_url_string,String extra_services) {
this.id = id;
this.name = name;
this.business_name=business_name;
this.description = description;
this.logo_url_string = logo_url_string;
this.cover_url_string = cover_url_string;
this.rating=rating;
this.icon_default=icon_default;
this.cover_default=cover_default;
this.extra_services=extra_services;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRating() {
return rating;
}
public String getBusiness_name() {
return business_name;
}
public void setBusiness_name(String business_name) {
this.business_name = business_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogo_url_string() {
return logo_url_string;
}
public void setLogo_url_string(String logo_url_string) {
this.logo_url_string = logo_url_string;
}
public String getIcon_default() {
return icon_default;
}
public String getCover_default() {
return cover_default;
}
public String getCover_url_string() {
return cover_url_string;
}
public String getExtra_services() {
return extra_services;
}
public void setExtra_services() {
this.extra_services=extra_services;
}
}
You can add an ExtraServices class that contains a list of ExtraService
ExtraService
public class ExtraService {
private String Id;
private String ServiceName;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String ServiceName) {
this.ServiceName = ServiceName;
}
ExtraServices
public class ExtraServices {
private List<ExtraService> extraServicesList;
public List<ExtraService> getExtraServicesList() {
return extraServicesList;
}
public void setExtraServicesList(List<ExtraService> extraServicesList) {
this.extraServicesList = extraServicesList;
}
public void add(ExtraService extraService){
if(extraServicesList == null){
extraServicesList = new ArrayList<>();
}
extraServicesList.add(extraService);
}
And in your Business class add getters and setters of ExtraServices
private ExtraServices extraServices;
public ExtraServices getExtraServices () {
return extraServices;
}
public void setExtraServices (ExtraServices extraServices) {
this.extraServices = extraServices;
}
After you have to do the setter process and in your Adapter you should do something like this:
holder.txtNameServiceBasic.setText(businessList.get(position).getExtraServices().getExtraServicesList().get(posistion).getServiceName());

RoboSpice-Retrofit POJO

I have a JSON like this:
{"meta": {...}, "objects": [{...}, {...}]}
But the problem is how to construct the POJO class. From the samples there is only one example with simple JSON.
I tried with something like this:
class Test {
public ArrayList<String> meta;
public static class Object {
public String testField;
}
public static class Objects extends ArrayList<Object>{}
}
And in the RetrofitRequest class I use Test.Objects.class
Any help will be appreciated!
I've fixed it with creating classes for meta and object where objects are in ArrayList<Object>
Thanks!
These are the POJO class to hold and parse the json
1)Meta.java
public class Meta {
private int limit;
private String next;
private int offset;
private String previous;
private int total_count;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public String getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public int getTotal_count() {
return total_count;
}
public void setTotal_count(int total_count) {
this.total_count = total_count;
}
}
2)Objects.java
public class Objects {
private String description;
private int downloads;
private int family_filter;
private int id;
private String image_url;
private int rating;
private String resource_uri;
private int size;
private String tags;
private String title;
private String uploaded_date;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getDownloads() {
return downloads;
}
public void setDownloads(int downloads) {
this.downloads = downloads;
}
public int getFamily_filter() {
return family_filter;
}
public void setFamily_filter(int family_filter) {
this.family_filter = family_filter;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getResource_uri() {
return resource_uri;
}
public void setResource_uri(String resource_uri) {
this.resource_uri = resource_uri;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUploaded_date() {
return uploaded_date;
}
public void setUploaded_date(String uploaded_date) {
this.uploaded_date = uploaded_date;
}
}
3) Finally your Test.java
public class Test {
private Meta meta;
private List<Objects> objects;
public Meta getMeta() {
return meta;
}
public void setMeta(Meta meta) {
this.meta = meta;
}
public List<Objects> getObjects() {
return objects;
}
public void setObjects(List<Objects> objects) {
this.objects = objects;
}
}
Try like this.
This is complete POJO class which will hold the parsed json.

Categories

Resources