How to use Pojo to get the fields? - android

Guys recently i switched to Retrofit from volley.
there is a Pojo file which is converted from json.
public class JobModel {
private int status;
private List<JobsBean> jobs;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public List<JobsBean> getJobs() {
return jobs;
}
public void setJobs(List<JobsBean> jobs) {
this.jobs = jobs;
}
public static class JobsBean {
private String job_city;
public String getJob_city() {
return job_city;
}
}
}
but i don't know how to use this pojo file to extract the job_city from JobsBean class
As you can see there is an JsonArray jobs which is converted to
List<JobsBean>
having JsonObjects and the
JobsBean class
is containing all the job_city name.
How can i retrieve these job_city name in an array.
so that i can use them in my arrayadapter.

Change the POJO structure as follow:
public class JobModel {
private int status;
private List<JobsBean> jobs;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public List<JobsBean> getJobs() {
return jobs;
}
public void setJobs(List<JobsBean> jobs) {
this.jobs = jobs;
}
}
public class JobsBean {
private String job_city;
public String getJob_city() {
return job_city;
}
public void setJob_city(String job_city) {
this.job_city = job_city;
}
}
The default GsonConverterFactory should be more than enough to handle this nested POJO. And you should be able to get the result like:
JobModel.getJobs().get(index).getJob_city();

Use ArrayAdapter<JobsBean> and it will take a JobsBean list as a parameter for the model data.
You will need to override getView() to read the data from the JobsBean item and put it into the list item view.

Related

GSON Array to go

I'm thinking about it, but I can't print the name and age of the json Crospromotion on the console. I'm using the GSON library, but I'm stuck right now and I don't know how to move forward.
I have my JSON
{
"crospromotion": [
{
"name": "Orus",
"age":14
},
{
"name": "Michelle",
"age":29
},
{
"name": "Jack",
"age":29
}
],
"totalAccessorios": 20,
"totalCaras": 20
}
My JSon controller class:
public class Data {
private Crospromotion crospromotion;
private int totalAccessorios, totalCaras;
public int getTotalAccessorios() {
return totalAccessorios;
}
public int getTotalCaras() {
return totalCaras;
}
}
Class Crospromotion:
public class Crospromotion {
private String nombre;
private int edad;
public String getNombre() {
return nombre;
}
public int getEdad() {
return edad;
}
}
MainActivity:
Gson gson = new Gson();
final Data data = gson.fromJson(myResponse, Data.class);
Log.d("MEN: ", data.getTotalAccessorios());
// I want to print in Log, the fields Crospromotion: name and age. But I don't know how to continue.
The attributes in the json string have different names than in the class Crospromotion. So you can just change the property names of the Crospromotion class like this:
public class Crospromotion {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Also in the json string you have an array of Crospromotion instances, but in the data class you only have one instance. That means you have to change the json string or write the class like this.
import java.util.List;
public class Data {
private List<Crospromotion> crospromotions;
private int totalAccessorios, totalCaras;
public int getTotalAccessorios() {
return totalAccessorios;
}
public int getTotalCaras() {
return totalCaras;
}
public List<Crospromotion> getCrospromotions() {
return crospromotions;
}
}
You also didn't have a getter for the Crospromotion List. Therefore you couldn't access it, because the property was private. With this code you should be able to access the data that you want to access.
It looks like you just forgot to add a getter for your Crospromotion field in your Data class?
public class Data {
private List<Crospromotion> crospromotion;
private int totalAccessorios, totalCaras;
public int getTotalAccessorios() {
return totalAccessorios;
}
public int getTotalCaras() {
return totalCaras;
}
public Crospromotion getCrospromotion() {
return crospromotion;
}
}
...
Log.d("MEN: ", data.getCrospromotion().getAge());
Btw, it looks like the fields in your JSON don't match your Crospromotion class. GSON uses reflection to match json fields to members of a class. You can use #SerializedName() to map JSON field names to member fields if the names differ.
For example:
public class Crospromotion {
#SerializedName("name") private String nombre;
#SerializedName("age") private int edad;
public String getNombre() {
return nombre;
}
public int getEdad() {
return edad;
}
}

How to structure data model for a correct deserialisation?

I am using Retrofit 2.0 to make call to currency conversion API.
I am calling:
https://free.currencyconverterapi.com/api/v6/convert?q=USD_PLN
To receive this response:
{
"query": {
"count": 1
},
"results": {
"USD_PLN": {
"id": "USD_PLN",
"val": 3.763304,
"to": "PLN",
"fr": "USD"
}
}
}
Now I am trying to build data model so that Gson can correctly deserialise this response. I have ResponseWrapper.class
public class ResponseWrapper {
private Query query;
private ConversionPair results;
}
Query.class
public class Query {
private int count;
}
ConversionPair.class
public class ConversionPair {
private String id;
private Currency from;
private Currency to;
private float value;
}
What should I do about USD_PLN object that is in the response body? I want to be able to make different calls with different pairs. I obviously I will not create separate class for every possible pair? What is the proper way of dealing with that?
Best way is to ask API team to change the field and make that generic
{
"query":{
"count":1
},
"results":{
"currency":{ // Currency should be fixed
"id":"USD_PLN",
"val":3.763304,
"to":"PLN",
"fr":"USD"
}
}
}
Use JsonToPojoConverter
public class Example {
#SerializedName("query")
private Query query;
#SerializedName("results")
private Results results;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
public Results getResults() {
return results;
}
public void setResults(Results results) {
this.results = results;
}
}
public class Query {
#SerializedName("count")
private Integer count;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
public class Results {
#SerializedName("USD_PLN")
private USDPLN uSDPLN;
public USDPLN getUSDPLN() {
return uSDPLN;
}
public void setUSDPLN(USDPLN uSDPLN) {
this.uSDPLN = uSDPLN;
}
}
public class USDPLN {
#SerializedName("id")
private String id;
#SerializedName("val")
private Double val;
#SerializedName("to")
private String to;
#SerializedName("fr")
private String fr;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Double getVal() {
return val;
}
public void setVal(Double val) {
this.val = val;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
Use JsonElement as results type: JsonElement results; and manually convert it to a Map:
final Type type = new TypeToken<Map<String, ConversionPair>>(){}.getType();
final Map<String, ConversionPair> objects = new Gson().fromJson(results, type);
Now you can loop through objects

Content not visible in Android fragment

Ps.: JSON data is not parsed in the CardView.
Main Fragment
I used a fragment for viewing the data on every item click and these are identified by slider menu. I wrote the code for parsing JSON data using Retrofit web service.
public class Physical_Geography_Activity extends Fragment{
View viewOne;
private RecyclerView recyclerView;
private ArrayList<QAModel> dataArray;
private DataAdapter adapter;
private ProgressDialog dialog;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
viewOne=inflater.inflate(R.layout.geo_physical_layout,container,false);
recyclerView=(RecyclerView)viewOne.findViewById(R.id.card_recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(viewOne.getContext());
recyclerView.setLayoutManager(layoutManager);
loadJSON();
return viewOne;
}
private void loadJSON() {
dialog = ProgressDialog.show(getContext(),"Please wait","Loading..",true);
dialog.show();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.myjson.com").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = requestInterface.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
dialog.dismiss();
JSONResponse jsonResponse=response.body();
dataArray = new ArrayList<QAModel>(Arrays.asList(jsonResponse.getPhysiography()));
adapter= new DataAdapter(dataArray);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
}
Adapter
Custom ListView to view the data and wrote a holder class to hold the data, I used two TextViews to view the text, that is question and answer. The question and answer are dynamically changing whenever I am adding data in my remote server.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<QAModel> arrayList;
public DataAdapter(ArrayList<QAModel> arrayList) {
this.arrayList = arrayList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.physical_card_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.question.setText(arrayList.get(position).getQuestion());
holder.answer.setText(arrayList.get(position).getAnswer());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView question,answer;
public ViewHolder(View itemView) {
super(itemView);
question=(TextView)itemView.findViewById(R.id.tv_question);
answer=(TextView)itemView.findViewById(R.id.tv_answer);
}
}
}
Model
Model has one constructor and two private string variables. And I have created the setters and getters methods for getting and setting the JSON data from the remote server.
public class QAModel {
private String Question;
private String Answer;
public QAModel(String question, String answer) {
Question = question;
Answer = answer;
}
public String getQuestion() {
return Question;
}
public void setQuestion(String question) {
Question = question;
}
public String getAnswer() {
return Answer;
}
public void setAnswer(String answer) {
Answer = answer;
}
}
JSON Response
JSON Response class is written for getting the response of the model class with the method call.
public class JSONResponse {
private QAModel[] physiography;
public QAModel[] getPhysiography()
{
return physiography;
}
}
Interface
Interface has one method for getting the data from the server, that is getJSON and the interface does have the suffix url which hold the JSON data.
public interface RequestInterface {
#GET("bins/lo1md")
Call<JSONResponse> getJSON();
}
You are missing a '/' in your base URL 'https://api.myjson.com'
Please update your line
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.myjson.com").addConverterFactory(GsonConverterFactory.create()).build();
to this
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.myjson.com/").addConverterFactory(GsonConverterFactory.create()).build();
Also you need to change your model class to as below,
public class JSONResponse {
#SerializedName("physiography")
#Expose
private List<Physiography> physiography = null;
public List<Physiography> getPhysiography() {
return physiography;
}
public void setPhysiography(List<Physiography> physiography) {
this.physiography = physiography;
}
}
and
public class Physiography {
#SerializedName("answer")
#Expose
private String answer;
#SerializedName("question")
#Expose
private String question;
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
make adapter.notifyDataSetChanged();
Edited :
public class JSONResponse {
#SerializedName("physiography")
public List<Physiography> physiography = new ArrayList<Physiography>;
}
public class Physiography {
#SerializedName("answer")
public String answer;
#SerializedName("question")
public String question;
}
change your response class like then check it
Boom !
1) put this gradle in your project .
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.google.code.gson:gson:2.8.0'
2) make 2 models , 1st for
QAModel
public class QAModel{
#SerializedName("answer")
private String Answer;
#SerializedName("question")
private String Question;
public QAModel(String question, String answer) {
Question = question;
Answer = answer;
}
public String getQuestion() {
return Question;
}
public void setQuestion(String question) {
Question = question;
}
public String getAnswer() {
return Answer;
}
public void setAnswer(String answer) {
Answer = answer;
}
}
and 2nd for Response of server
ResponseQAModel
public class ResponseQAModel {
#SerializedName("physiography")
private List<QAModel> qaModels;
public List<QAModel> getQaModels() {
return qaModels;
}
public void setQaModels(List<QAModel> qaModels) {
this.qaModels = qaModels;
}
}
3)ApiClient where you setup your retrofit
public class ApiClient {
public static final String BASE_URL = "https://api.myjson.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
4) Your Routes ApiInterface
public interface ApiInterface {
#GET("/bins/lo1md")
Call<ResponseQAModel> getJSON();
}
5)Now its time to catch output ;)
private void loadGSON() {
final Call<ResponseQAModel> responseQAModelCall;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
responseQAModelCall = apiService.getJSON();
responseQAModelCall.enqueue(new Callback<ResponseQAModel>() {
#Override
public void onResponse(Call<ResponseQAModel> call, Response<ResponseQAModel> response) {
Log.d("kkkkk",response.body().getQaModels().toString());
//responseQAMODELS contains all response pass to your adapter
List<QAModel> responseQAModels = response.body().getQaModels();
}
#Override
public void onFailure(Call<ResponseQAModel> call, Throwable t) {
}
});
}
First of all don't name your response object to something that common(JSONResponse). Name it more appropriately lets say PhysiographyResponse. Use Moshi library from squareup, it will generate JAVA objects of your JSON response.
Moshi dependency
implementation 'com.squareup.retrofit2:converter-moshi:2.3.0'
implementation 'com.squareup.moshi:moshi:1.5.0'
Data model classes -
import com.squareup.moshi.Json;
public class PhysiographyResponse {
#Json(name = "physiography")
List<QAModel> QAModel;
public List<QAModel> getQAModel() {
return QAModel;
}
public void setQAModel(List<QAModel> QAModel) {
this.QAModel = QAModel;
}
}
import com.squareup.moshi.Json;
public class QAModel {
#Json(name = "answer")
String answer;
#Json(name = "question")
String question;
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
Api interface
public interface RequestInterface {
#GET("bins/lo1md")
Call<PhysiographyResponse> getPhysiographyResponse();
}
Retrofit call
Call<PhysiographyResponse> call = requestInterface.getPhysiographyResponse();
call.enqueue(new Callback<PhysiographyResponse>() {
#Override
public void onResponse(Call<PhysiographyResponse> call, Response<PhysiographyResponse> response) {
dialog.dismiss();
dataArray = new ArrayList<QAModel>(Arrays.asList(resposne.getQAModel));
adapter= new DataAdapter(dataArray);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});

Fetching json object from JSON string

I am new to Android and I am developing app which has server side functionality. I am getting response in JSON format.
My response is shown as this image.
I know how to parse json using Volley but I don't know hot to parse using GSON. Previous code of my app was written by some one else. Now I have to complete this code. but I do not know how he getting data from JSON string.
I need JSON arrays in different activity. Array response:
image
Here is some snaps of my code.
Code for adapter for activity one
topicListAdapter = new TopicListAdapter(TopicActivity.this,
myCourseListMain. getCourseArrayList().get(Integer.parseInt(course_position)).
getTopicListMain().getTopicDetailsArrayList(), flag);
listAlltopics.setAdapter(topicListAdapter);
in which I got list of topics
here is code for second activity list adapter
lessionListAdapter = new LessionListAdapter(LessionActivity.this,
myCourseListMain. getCourseArrayList(). get(Integer.parseInt(course_position)).
getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList(), flag);
by this code i got array of lession in second activity
Now I want sublession array in third activity but I don't know how to get it.
Here is what I tried
lessionListAdapter = new DummyAdapter(DummyTopicList.this,
myCourseListMain . getCourseArrayList(). get(Integer.parseInt(course_position)).
getTopicListMain() . getTopicDetailsArrayList() .get(Integer.parseInt(topic_position)).
getLessionLIstMain() .getLessionLIstDetailArrayList().get(Integer.parseInt(lession_position)). , flag);
listAlllessions.setAdapter(lessionListAdapter);
Here are some other classes which helpful to you for understand
public class MyCourseListMain {
#SerializedName("data")
private ArrayList<Course> courseArrayList;
public ArrayList<Course> getCourseArrayList() {
return courseArrayList;
}
public void setCourseArrayList(ArrayList<Course> courseArrayList) {
this.courseArrayList = courseArrayList;
}
}
class for course
public class Course {
#SerializedName("img")
private String img;
#SerializedName("title")
private String title;
#SerializedName("institute_id")
private String institute_id;
#SerializedName("institute_name")
private String institute_name;
#SerializedName("expired")
private String expired;
#SerializedName("status")
private String status;
#SerializedName("subscribe_box")
private String subscribe_box;
#SerializedName("expire_on")
private String expire_on;
#SerializedName("item_id")
private String item_id;
#SerializedName("rated")
private String rated;
private TopicListMain topicListMain;
public String getRated() {
return rated;
}
public void setRated(String rated) {
this.rated = rated;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getInstitute_id() {
return institute_id;
}
public void setInstitute_id(String institute_id) {
this.institute_id = institute_id;
}
public String getInstitute_name() {
return institute_name;
}
public void setInstitute_name(String institute_name) {
this.institute_name = institute_name;
}
public String getExpired() {
return expired;
}
public void setExpired(String expired) {
this.expired = expired;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSubscribe_box() {
return subscribe_box;
}
public void setSubscribe_box(String subscribe_box) {
this.subscribe_box = subscribe_box;
}
public String getExpire_on() {
return expire_on;
}
public void setExpire_on(String expire_on) {
this.expire_on = expire_on;
}
public String getItem_id() {
return item_id;
}
public void setItem_id(String item_id) {
this.item_id = item_id;
}
public TopicListMain getTopicListMain() {
return topicListMain;
}
public void setTopicListMain(TopicListMain topicListMain) {
this.topicListMain = topicListMain; } }
class for topiclist_main
public class TopicListMain {
#SerializedName("data")
private ArrayList<TopicDetails> topicDetailsArrayList;
public ArrayList<TopicDetails> getTopicDetailsArrayList() {
return topicDetailsArrayList;
}
public void setTopicDetailsArrayList(ArrayList<TopicDetails> topicDetailsArrayList) {
this.topicDetailsArrayList = topicDetailsArrayList; }}
class for topic details
public class TopicDetails
{
#SerializedName("topic_id")
private String topic_id;
#SerializedName("title")
private String title;
#SerializedName("locked")
private String locked;
#SerializedName("lessons")
private ArrayList<Lession> lessionArrayList;
private LessionLIstMain lessionLIstMain;
public LessionLIstMain getLessionLIstMain() {
return lessionLIstMain;
}
public void setLessionLIstMain(LessionLIstMain lessionLIstMain) {
this.lessionLIstMain = lessionLIstMain;
}
public String getTopic_id() {
return topic_id;
}
public void setTopic_id(String topic_id) {
this.topic_id = topic_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocked() {
return locked;
}
public void setLocked(String locked) {
this.locked = locked;
}
public ArrayList<Lession> getLessionArrayList() {
return lessionArrayList;
}
public void setLessionArrayList(ArrayList<Lession> lessionArrayList) {
this.lessionArrayList = lessionArrayList; }}
https://github.com/google/gson
Make your object have same construct with your data which you got.And
YourObject val = new Gson().fromJson(new String(YourString.getBytes("ISO-8859-1"),
"UTF-8"), YourObject.class);
finally i got my solution by below code.
lessionListAdapter = new DummyAdapter(DummyTopicList.this,
myCourseListMain . getCourseArrayList(). get(Integer.parseInt(course_position)).
getTopicListMain() . getTopicDetailsArrayList() .get(Integer.parseInt(topic_position)).
getLessionArrayList().get(Integer.parseInt((lession_position))).getLessionLIstDetailArrayList() , flag);
listAlllessions.setAdapter(lessionListAdapter);
i also made some few classes to handle json array.
public class SubLessionDetail {
#SerializedName("lesson_id")
private String lession_id;
#SerializedName("title")
private String title;
#SerializedName("locked")
private String locked;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLocked() {
return locked;
}
public void setLocked(String locked) {
this.locked = locked;
}
public String getLession_id() {
return lession_id;
}
public void setLession_id(String lession_id) {
this.lession_id = lession_id;
}
}

Not receiving data from server using Retrofit 2

I am trying to retrieve Reddit information from a particular subreddit using Retrofit 2. I have followed many tutorials and videos and my code seems to be correct from my perspective but I only manage to have null objects in my model class. I have the permission for internet in the Manifest.
This is a link the JSON I am working with HERE
MainActivity
public class MainActivity extends AppCompatActivity
{
TextView mTextView;
Data mData;
private static final String TAG = "Battlestations";
#Override
protected void onCreate(Bundle savedInstanceState)
{
mTextView = (TextView) findViewById(R.id.test_view);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Call<Data> serviceCall = Service.getDesktopService().desks();
serviceCall.enqueue(new Callback<Data>()
{
#Override
public void onResponse(Call<Data> call, Response<Data> response)
{
Log.d("Reponce","return");
Log.i(TAG, "Response is " + mData.getChildren());
}
#Override
public void onFailure(Call<Data> call, Throwable t)
{
}
});
}
}
Api/Service Class
public class Service
{
private static final String BASE_URL = "https://www.reddit.com/r/";
private static DeskInterface mRetrofit;
public static DeskInterface getDesktopService()
{
if(mRetrofit == null)
{
Retrofit build = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
mRetrofit = build.create(DeskInterface.class);
}
return mRetrofit;
}
public interface DeskInterface
{
#GET("battlestations/hot/.json")
Call<Data> desks();
}
}
Data
public class Data
{
private List<Child> children = null;
public List<Child> getChildren()
{
return children;
}
public void setChildren(List<Child> children)
{
this.children = children;
}
}
Child
public class Child
{
private Data_ data;
public Data_ getData()
{
return data;
}
public void setData(Data_ data)
{
this.data = data;
}
}
Data_
public class Data_
{
private String subreddit;
private Integer score;
private String author;
private String subredditNamePrefixed;
private String url;
private String title;
public String getSubreddit()
{
return subreddit;
}
public void setSubreddit(String subreddit)
{
this.subreddit = subreddit;
}
public Integer getScore()
{
return score;
}
public void setScore(Integer score)
{
this.score = score;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public String getSubredditNamePrefixed()
{
return subredditNamePrefixed;
}
public void setSubredditNamePrefixed(String subredditNamePrefixed)
{
this.subredditNamePrefixed = subredditNamePrefixed;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
}
You need to add mData = response.body() in onResponse() (also check response.isSuccessful() first)
The problem is that your Data does not correspond with Reddit JSON. Your Data class
public class Data {
private List<Child> children = null;
}
does not match with the given json, which is:
{
"kind":"listing",
"data":{
"modhash":"...",
"children":[...],
"after":"...",
"before":"..."
}
}
Retrofit automagically convert from json to java but only if the mapping is correct.
A correct Java class would be:
public class Subreddit {
String kind;
Data data;
}
public class Data{
String modhash;
List<Child> children;
String after;
String before;
}
and then modify desks method interface to
Call<Subreddit> desks();
You would have to go recursively for the entire depth of the JSON to get the right mapping.
But before you get to work, just replace your Retrofit interface:
public interface DeskInterface{
#GET("battlestations/hot/.json")
Call<Data> desks();
}
with:
public interface DeskInterface{
#GET("battlestations/hot/.json")
Call<JsonObject> desks();
}
and it should return something. If is still null, then further investigation is needed. If it returns a valid response(some json text) then copy/paste that subreddit to this website where it converts all the json to a valid Java class

Categories

Resources