Nested object in Json - android

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

Related

Update certain item in List data from RecyclerView.Adapter class

Is there any way to update certain List data from RecyclerView.Adapter class
here is my List class:
public class Idea {
private String id, name, voted;
public Idea(String id, String name, String voted) {
this.id = id;
this.name = name;
this.voted = voted;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVoted() {
return voted;
}
}
my RecyclerView Adapter class:
public class IdeaListAdapter extends RecyclerView.Adapter<IdeaListAdapter.IdeaViewHolder> {
private Context mCtx;
private List<Idea> ideaList, idlst;
public IdeaListAdapter(Context mCtx, List<Idea> ideaList) {
this.mCtx = mCtx;
this.ideaList = ideaList;
}
#NonNull
#Override
public IdeaListAdapter.IdeaViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.idea_list_object_layout, null);
return new IdeaListAdapter.IdeaViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull IdeaListAdapter.IdeaViewHolder ideaViewHolder, int i) {
final Idea idea = ideaList.get(i);
if (idea.getVoted().equals("0")) {
ideaViewHolder.checkBoxLikeIdeaListFragment.setChecked(false);
} else if (idea.getVoted().equals("1")) {
ideaViewHolder.checkBoxLikeIdeaListFragment.setChecked(true);
}
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
*** Update my idea.getVoted() here ***
} else {
*** Update my idea.getVoted() here ***
}
}
});
ideaViewHolder.textViewNameIdeaListFragment.setText(idea.getName());
}
#Override
public int getItemCount() {
return ideaList.size();
}
class IdeaViewHolder extends RecyclerView.ViewHolder {
TextView textViewNameIdeaListFragment;
CheckBox checkBoxLikeIdeaListFragment;
public IdeaViewHolder(#NonNull View itemView) {
super(itemView);
textViewNameIdeaListFragment = (TextView) itemView.findViewById(R.id.textViewNameIdeaListFragment);
checkBoxLikeIdeaListFragment = (CheckBox) itemView.findViewById(R.id.checkBoxLikeIdeaListFragment);
}
}
}
i would like to update my idea.getVoted() when the user click the checkBoxLikeIdeaListFragment
im not quite sure how i will use the ideaList.set() at this part.
should i do it on my MainActivity ? if yes, please teach me.
Create Setter method on your Model class **Idea** and access setter method to update the data.
Like this.
public class Idea {
private String id, name, voted;
public Idea(String id, String name, String voted) {
this.id = id;
this.name = name;
this.voted = voted;
}
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 String getVoted() {
return voted;
}
public void setVoted(String voted) {
this.voted = voted;
}
}
Use setter method of setVoted in your adapter class.
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
i
ideaList.get(i).setVoted("set your data"); //here you have to upadte the vote value.
notifiyDatasetChanged();
}
});
Quickest way to do this is to pass a OnCheckedListener on your IdeaViewHolder constructor and assign it to your checkBoxLikeIdeaListFragment.
Or on your existing code you can:
ideaViewHolder.checkBoxLikeIdeaListFragment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
ideaList.get(i).setVoted(b); // i is the int index passed to onBindViewHolder(..)
IdeaListAdapter.this.notifyDatasetChanged(); //update list
}
});

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.

Retrofit Returns Null value

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.

Android List item displaying package name and # instead of string value

I implemented parceable class to pass some data from one activity to the other. I managed to get the rest of the items in the class. But that class has a list object i want to display in another fragment. i think the problem has to do with my adapter. kindly help me out. i have attached my fragment class and my adapter class as well.
Fragment Class
public class ForumDetailFragment extends Fragment {
private TextView titleTV;
private TextView timeTV;
private TextView dateTV;
private TextView detailsTV;
private ListView answerListView;
private LinearLayout themeLayout;
private ImageView themeIMG;
private StoredForum currentQuestion;
private AnswerAdapter adapter;
SimpleDateFormat formatDate = new SimpleDateFormat("MMM-dd-yyyy");
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm aaa");
public ForumDetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_forum_detail, container, false);
currentQuestion = getArguments().getParcelable(StoredForum.QUESTION_CLASS);
titleTV = (TextView) rootView.findViewById(R.id.titleTV);
timeTV = (TextView) rootView.findViewById(R.id.timeTV);
detailsTV = (TextView) rootView.findViewById(R.id.detailsTV);
answerListView = (ListView) rootView.findViewById(R.id.answerListView);
themeLayout = (LinearLayout) rootView.findViewById(R.id.eventTypeThemeLayout);
themeIMG = (ImageView) rootView.findViewById(R.id.eventTypeThemeIMG);
dateTV = (TextView) rootView.findViewById(R.id.dateTV);
titleTV.setText(currentQuestion.getTitle());
detailsTV.setText(currentQuestion.getDescription());
timeTV.setText(formatTime.format(currentQuestion.getQuestionDate()));
dateTV.setText(formatDate.format(currentQuestion.getQuestionDate()));
setupTheme();
setUpListView(rootView);
updateAnswer();
return rootView;
}
public void setUpListView(View rootView) {
answerListView = (ListView) rootView.findViewById(R.id.answerListView);
adapter = new AnswerAdapter(getActivity(), new ArrayList<Question>());
answerListView.setAdapter(adapter);
}
private void setupTheme() {
if (currentQuestion.getDescription().equals(StoredForum.FORUM_QUESTION)) {
themeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.pink));
themeIMG.setImageResource(R.drawable.abc_ic_menu_copy_mtrl_am_alpha);
} else {
themeLayout.setBackgroundColor(getActivity().getResources().getColor(R.color.orange));
themeIMG.setImageResource(R.drawable.abc_ic_menu_paste_mtrl_am_alpha);
}
}
public void updateAnswer() {
AuthUser user = AuthUser.getInstance(getActivity());
Retrofit retrofit = ApiHandle.getRetrofit(user.getToken());
QuestionService service = retrofit.create(QuestionService.class);
service.getQuestions().enqueue(new Callback<List<com.apps233.moja.packages.forum.Question>>() {
#Override
public void onResponse(Response<List<com.apps233.moja.packages.forum.Question>> response, Retrofit retrofit) {
if (response.isSuccess()) {
adapter.clear();
adapter.addAll(response.body());
adapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Throwable t) {
}
});
}
}
Adapter Class
public class AnswerAdapter extends ArrayAdapter<Question> {
List<Question> answers = new ArrayList<Question>();
public AnswerAdapter(Context context, List<Question> answers) {
super(context, R.layout.item_answer, answers);
this.answers = answers;
}
public static class ViewHolder {
private TextView titleTV;
private TextView descriptionTV;
public ViewHolder(View view) {
titleTV = (TextView) view.findViewById(R.id.titleTV);
descriptionTV = (TextView) view.findViewById(R.id.descriptionTV);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Question question = answers.get(position);
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_answer, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTV.setText("Doctor");
holder.descriptionTV.setText(question.getAnswers().toString());
return convertView;
}
}
The list is displayed in the activity below
the list is displaying the package name # some list of numbers
Question Class
public class Question {
private Long id;
private String title;
private Long userId;
private String description;
private Date questionDate;
private List<Answer> answers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getQuestionDate() {
return questionDate;
}
public void setQuestionDate(Date questionDate) {
this.questionDate = questionDate;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers (List<Answer> answers){
this.answers = answers;
}
}
Parceable Class
public class StoredForum implements Parcelable {
public static final String QUESTION_ID = "QUESTION_ID";
public static final String QUESTION_CLASS = "QUESTION";
public static final String FORUM_QUESTION = "forum-chat";
Long id;
Long userId;
String title;
String description;
Date questionDate;
List<Answer> answers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getQuestionDate() {
return questionDate;
}
public void setQuestionDate(Date questionDate) {
this.questionDate = questionDate;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers){
this.answers = answers;
}
private StoredForum() {
}
public static StoredForum fromQuestion(Question question) {
StoredForum storedForum = new StoredForum();
storedForum.setId(question.getId());
storedForum.setUserId(question.getUserId());
storedForum.setTitle(question.getTitle());
storedForum.setDescription(question.getDescription());
storedForum.setQuestionDate(question.getQuestionDate());
storedForum.setAnswers(question.getAnswers());
return storedForum;
}
protected StoredForum(Parcel in) {
id = in.readByte() == 0x00 ? null : in.readLong();
userId = in.readByte() == 0x00 ? null : in.readLong();
title = in.readString();
description = in.readString();
questionDate = new Date(in.readString());
answers = new ArrayList<Answer>();
answers = in.readArrayList(Answer.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (id == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeLong(id);
}
if (userId == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeLong(userId);
}
dest.writeString(title);
dest.writeString(description);
if(questionDate != null){
dest.writeString(questionDate.toString());
} else {
dest.writeString("0");
}
answers = new ArrayList<Answer>();
dest.writeList(answers);
}
public static final Parcelable.Creator<StoredForum> CREATOR = new Parcelable.Creator<StoredForum>() {
#Override
public StoredForum createFromParcel(Parcel in) {
return new StoredForum(in);
}
#Override
public StoredForum[] newArray(int size) {
return new StoredForum[size];
}
};
}
Answer Class
public class Answer {
Long id;
Long userId;
Long questionId;
String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getQuestionId() {
return questionId;
}
public void setQuestionId(Long questionId) {
this.questionId = questionId;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
}
You need to implement/override public String toString() method in Answer class.
#Override
public String toString() {
return description;
}

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