When I run the app its give me error and when i refresh app it crash
My code is
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
city = (TextView)findViewById(R.id.city);
country = (TextView) findViewById(R.id.country);
update = (TextView) findViewById(R.id.last_update);
temp = (TextView) findViewById(R.id.temp);
state = (TextView) findViewById(R.id.state);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchWeather();
}
});
}
public void fetchWeather(){
swipeRefreshLayout.setRefreshing(true);
WeatherAPI.Factory.getInstance().getWeather().enqueue(new Callback<Weather>() {
#Override
public void onResponse(Call<Weather> call, Response<Weather> response) {
city.setText(response
.body()
.getQuery()
.getResults()
.getChannel()
.getLocation()
.getCity());
country.setText(response
.body()
.getQuery()
.getResults()
.getChannel()
.getLocation()
.getCountry());
update.setText(response
.body()
.getQuery()
.getResults()
.getChannel()
.getLastBuildDate());
temp.setText( response.body().getQuery().getResults().getChannel().getItem().getCondition().getTemp() +"\u2109");
state.setText(response.body().getQuery().getResults().getChannel().getLocation().getRegion());
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFailure(Call<Weather> call, Throwable t) {
Log.e("Failed",t.getMessage());
swipeRefreshLayout.setRefreshing(false);
}
});
}
#Override
public void onRefresh() {
fetchWeather();
}
}
Model class of Result
public class Results {
#SerializedName("channel")
#Expose
private Channel channel;
public void setChannel(Channel channel) {
this.channel = channel;
}
public Channel getChannel() {
return channel;
}
}
model class of Channel
public class Channel {
#SerializedName("units")
#Expose
private Units units;
#SerializedName("title")
#Expose
private String title;
#SerializedName("link")
#Expose
private String link;
#SerializedName("description")
#Expose
private String description;
#SerializedName("language")
#Expose
private String language;
#SerializedName("lastBuildDate")
#Expose
private String lastBuildDate;
#SerializedName("ttl")
#Expose
private String ttl;
#SerializedName("location")
#Expose
private Location location;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("atmosphere")
#Expose
private Atmosphere atmosphere;
#SerializedName("astronomy")
#Expose
private Astronomy astronomy;
#SerializedName("image")
#Expose
private Image image;
#SerializedName("item")
#Expose
private Item item;
public Units getUnits() {
return units;
}
public void setUnits(Units units) {
this.units = units;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getLastBuildDate() {
return lastBuildDate;
}
public void setLastBuildDate(String lastBuildDate) {
this.lastBuildDate = lastBuildDate;
}
public String getTtl() {
return ttl;
}
public void setTtl(String ttl) {
this.ttl = ttl;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Atmosphere getAtmosphere() {
return atmosphere;
}
public void setAtmosphere(Atmosphere atmosphere) {
this.atmosphere = atmosphere;
}
public Astronomy getAstronomy() {
return astronomy;
}
public void setAstronomy(Astronomy astronomy) {
this.astronomy = astronomy;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Error application running in wifi. When I run Mobile Internet it does not gives error......
FATAL EXCEPTION: main
Process: com.example.prem.climate, PID: 11893
java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.prem.climate.model.Channel com.example.prem.climate.model.Results.getChannel()' on a null object reference
at com.example.prem.climate.MainActivity$2.onResponse(MainActivity.java:68)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618
That seems like response.body().getQuery().getResults() returns null, and then you try invoke getChannel() on null
Related
I am trying to communicate with an API using Retrofit in Android Studios but do not know how to get the JSON array within a JSON object.
JSON:
{
"result":{
"status":{
"msg":"success",
"code":200,
"action":2,
"execution_time":"0.505"
},
"page":"1",
"page_size":"40",
"q":"iphone",
"sort":"default",
"tmall":false,
"free_shiping":false,
"total_results":1924963,
"ip":"13.228.169.5",
"item":[
{
"num_iid":619354061232,
"pic":"https://img.alicdn.com/bao/uploaded/i4/2150908574/O1CN01O3Akm82DCwTChbTXg_!!2150908574.jpg",
"title":"Apple/苹果 iPhone XR iphone xs max手机双卡国行原装4G xr苹果x",
"price":"6000",
"promotion_price":"2009",
"sales":1973,
"loc":"广东 深圳",
"seller_id":2150908574,
"seller_nick":"实惠馆超市",
"shop_title":"新魔方数码",
"user_type":0,
"detail_url":"https://item.taobao.com/item.htm?id=619354061232",
"delivery_fee":"0.00"
}
"item":[...]
Method:
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
//not sure what to do here
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
TaobaoModel:
public class TaobaoModel {
#SerializedName("result")
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
Result:
public class Result {
#SerializedName("status")
private Status status;
#SerializedName("q")
private String q;
#SerializedName("page")
private String page;
#SerializedName("page_size")
private String page_size;
#SerializedName("total_results")
private int total_results;
#SerializedName("tmall")
private String tmall;
#SerializedName("sort")
private String sort;
#SerializedName("free_shiping")
private String free_shiping;
#SerializedName("ip")
private String ip;
#SerializedName("item")
private ArrayList<TaobaoItems> item;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPage_size() {
return page_size;
}
public void setPage_size(String page_size) {
this.page_size = page_size;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public String getTmall() {
return tmall;
}
public void setTmall(String tmall) {
this.tmall = tmall;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getFree_shiping() {
return free_shiping;
}
public void setFree_shiping(String free_shiping) {
this.free_shiping = free_shiping;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public ArrayList<TaobaoItems> getItem() {
return item;
}
public void setItem(ArrayList<TaobaoItems> item) {
this.item = item;
}
}
TaobaoItems
public class TaobaoItems {
#SerializedName("num_iid")
private long num_iid;
#SerializedName("pic")
private String pic;
#SerializedName("title")
private String title;
#SerializedName("price")
private String price;
#SerializedName("promotion_price")
private String promotion_price;
#SerializedName("sales")
private int sales;
#SerializedName("loc")
private String loc;
#SerializedName("seller_id")
private long seller_id;
#SerializedName("seller_nick")
private String seller_nick;
#SerializedName("shop_title")
private String shop_title;
#SerializedName("user_type")
private int user_type;
#SerializedName("detail_url")
private String detail_url;
#SerializedName("delivery_fee")
private String delivery_fee;
public TaobaoItems(String title, String price, String pic, String detail_url) {
this.pic = pic;
this.title = title;
this.price = price;
this.detail_url = detail_url;
}
public long getNum_iid() {
return num_iid;
}
public void setNum_iid(long num_iid) {
this.num_iid = num_iid;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPromotion_price() {
return promotion_price;
}
public void setPromotion_price(String promotion_price) {
this.promotion_price = promotion_price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public long getSeller_id() {
return seller_id;
}
public void setSeller_id(long seller_id) {
this.seller_id = seller_id;
}
public String getSeller_nick() {
return seller_nick;
}
public void setSeller_nick(String seller_nick) {
this.seller_nick = seller_nick;
}
public String getShop_title() {
return shop_title;
}
public void setShop_title(String shop_title) {
this.shop_title = shop_title;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public String getDetail_url() {
return detail_url;
}
public void setDetail_url(String detail_url) {
this.detail_url = detail_url;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
}
Status:
public class Status {
#SerializedName("msg")
private String msg;
#SerializedName("code")
private int code;
#SerializedName("action")
private int action;
#SerializedName("execution_time")
private String execution_time;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getExecution_time() {
return execution_time;
}
public void setExecution_time(String execution_time) {
this.execution_time = execution_time;
}
}
My intention is to get the JSON Array item and display title,price,pic,detail_url from it. I found out how to display it one at a time so far, but couldn't find how to iterate the JSON object so that I can display the data in a listview. Please help, I am new to this and I've been stuck for quite awhile now. If you want to see my interface, retrofit instance etc just let me know.
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
List<Result> retro=response.body().getitems();
generateDataList(retro);
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<Result> dataList) {
recyclerView = findViewById(R.id.customRecycler);
adapter = new CustomAdapter(this,dataList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
I'm trying to use GSON with my OpenWeatherMap API. I was able to parse my JSON into the following code:
public class List {
#SerializedName("dt")
#Expose
private Integer dt;
#SerializedName("main")
#Expose
private Main main;
#SerializedName("weather")
#Expose
private java.util.List<Weather> weather = null;
#SerializedName("clouds")
#Expose
private Clouds clouds;
#SerializedName("wind")
#Expose
private Wind wind;
#SerializedName("rain")
#Expose
private Rain rain;
#SerializedName("sys")
#Expose
private Sys sys;
#SerializedName("dt_txt")
#Expose
private String dtTxt;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Main getMain() {
return main;
}
public void setMain(Main main) {
this.main = main;
}
public java.util.List<Weather> getWeather() {
return weather;
}
public void setWeather(java.util.List<Weather> weather) {
this.weather = weather;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
public Sys getSys() {
return sys;
}
public void setSys(Sys sys) {
this.sys = sys;
}
public String getDtTxt() {
return dtTxt;
}
public void setDtTxt(String dtTxt) {
this.dtTxt = dtTxt;
}
}
public class Main {
#SerializedName("temp")
#Expose
private Double temp;
#SerializedName("temp_min")
#Expose
private Double tempMin;
#SerializedName("temp_max")
#Expose
private Double tempMax;
#SerializedName("pressure")
#Expose
private Double pressure;
#SerializedName("sea_level")
#Expose
private Double seaLevel;
#SerializedName("grnd_level")
#Expose
private Double grndLevel;
#SerializedName("humidity")
#Expose
private Integer humidity;
#SerializedName("temp_kf")
#Expose
private Integer tempKf;
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getTempMin() {
return tempMin;
}
public void setTempMin(Double tempMin) {
this.tempMin = tempMin;
}
public Double getTempMax() {
return tempMax;
}
public void setTempMax(Double tempMax) {
this.tempMax = tempMax;
}
public Double getPressure() {
return pressure;
}
public void setPressure(Double pressure) {
this.pressure = pressure;
}
public Double getSeaLevel() {
return seaLevel;
}
public void setSeaLevel(Double seaLevel) {
this.seaLevel = seaLevel;
}
public Double getGrndLevel() {
return grndLevel;
}
public void setGrndLevel(Double grndLevel) {
this.grndLevel = grndLevel;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Integer getTempKf() {
return tempKf;
}
public void setTempKf(Integer tempKf) {
this.tempKf = tempKf;
}
}
public class Weather {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("main")
#Expose
private String main;
#SerializedName("description")
#Expose
private String description;
#SerializedName("icon")
#Expose
private String icon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
I've been searching online and on here and I have been unable to find how exactly to use GSON with my code which is:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather_app, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), DividerItemDecoration.VERTICAL));
requestJsonObject();
return view;
}
private void requestJsonObject (){
}
How exactly do I add the GSON parsing to my code? I only need the temperature, max, min, weather and humidity?
EDIT:
Here is some more info. I plan on using a normal http connection with an apikey to get my information. I am also planning on using RecyclerView and here is that code:
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.CurrentRecycler> {
List<Weather> mCurrentWeatherDataList;
public static class CurrentRecycler extends RecyclerView.ViewHolder{
public TextView location;
public TextView currentTemp;
public TextView currentHumidity;
public TextView currentDescription;
public ImageView currentIcon;
public CurrentRecycler (View view) {
super (view);
location = (TextView) view.findViewById(R.id.current_city_location);
currentTemp = (TextView) view.findViewById(R.id.current_temperature);
currentHumidity = (TextView) view.findViewById(R.id.current_humidity);
currentDescription = (TextView) view.findViewById(R.id.current_weather_description);
currentIcon = (ImageView) view.findViewById(R.id.current_weather_icon);
}
}
public RecyclerViewAdapter (List<Weather> mCurrentWeatherDataList) {
this.mCurrentWeatherDataList = mCurrentWeatherDataList;
}
#Override
public CurrentRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final CurrentRecycler currentRecycler = new CurrentRecycler(view);
return currentRecycler;
}
#Override
public void onBindViewHolder( CurrentRecycler holder, int position) {
final Weather currentRecycler = mCurrentWeatherDataList.get(position);
holder.location.setText(currentRecycler.getDefaultLocation());
holder.currentTemp.setText((currentRecycler.getDefaultCurrentTemp()));
holder.currentHumidity.setText(currentRecycler.getDefaultHumidity());
holder.currentDescription.setText(currentRecycler.getDefaultDescription());
}
#Override
public int getItemCount() {
return mCurrentWeatherDataList.size();
}
}
In your requestJsonObject method, use volley or okhttp to fetch the weather data from API.
Once you get the data as a String, you can use the following code:
List list = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(str, List.class);
Main main = list.getDt();
main.getTemp();
main.getTempMin();
main.getTempMax();
str means your api response data. List means your first entity class.
Moreover, I strongly recommend you to rename your class name, never try to use the reserved name of Java, make them meaningful.
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;
}
}
i got data from api link (server) to display data in recyclview ,if i want to click on items then it will open next activity thats fine, but some items have no data , if i want to click geting class cast exception
in this above image, click on Adventure , then it will open next activity with related data , if i want click on Kids Activities then getting Class cast exception error because from server no data is available of Kids Activities ,
if i want click on Kids ACtivities then it wil open toast massage like no more data is available , how should i get it?
This is adapter class
public class SubCategoryChild_Adapter extends RecyclerView.Adapter {
private List<SubCategoryChild> subCategoryChildList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView
discountName,
subcategorychild_merchantName,
subcategoryChild_discountedPrice,
subcategoryChild_actualPrice,
subcategoryChild_distance,
staticUgx;
public ImageView SubcategoryChild_imageView;
public SubCategoryChild subCategoryChild;
public MyViewHolder(View view) {
super(view);
subcategoryChild_actualPrice = (TextView) view.findViewById(R.id.ScChild_actualPrice);
subcategoryChild_actualPrice.setPaintFlags(subcategoryChild_actualPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
subcategoryChild_discountedPrice = (TextView) view.findViewById(R.id.ScChild_discountedPrice);
subcategorychild_merchantName = (TextView) view.findViewById(R.id.ScChild_merchantName);
staticUgx = (TextView) view.findViewById(R.id.ScChild_actualprice_ugx);
staticUgx.setPaintFlags(staticUgx.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
subcategoryChild_distance = (TextView) view.findViewById(R.id.ScChild_Near_Location_text);
discountName = (TextView) view.findViewById(R.id.ScChild_Discount_Text);
SubcategoryChild_imageView = (ImageView) view.findViewById(R.id.ScChild_imageView);
}
}
public SubCategoryChild_Adapter(Context context , List<SubCategoryChild> subCategoryChildList) {
this.subCategoryChildList = subCategoryChildList;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder itemView;
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.subcategorydeal_list, parent, false);
itemView = new MyViewHolder(view);
return itemView;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){
final SubCategoryChild subCategoryChild = subCategoryChildList.get(position);
((MyViewHolder) holder).subcategorychild_merchantName.setText(subCategoryChild.getMerchantName());
((MyViewHolder) holder).discountName.setText(subCategoryChild.getName());
((MyViewHolder) holder).subcategoryChild_actualPrice.setText(subCategoryChild.getActualPrice());
((MyViewHolder) holder).subcategoryChild_discountedPrice.setText(subCategoryChild.getDiscountedPrice());
((MyViewHolder) holder).subcategoryChild_distance.setText(subCategoryChild.getDistance());
context = ((MyViewHolder) holder).SubcategoryChild_imageView.getContext();
Picasso.with(context).load(subCategoryChild.getLogo()).fit().into(((MyViewHolder)holder).SubcategoryChild_imageView);
((MyViewHolder) holder).subCategoryChild = subCategoryChild;
}
#Override
public int getItemCount() {
if(subCategoryChildList == null){
return 0;
}else {
return subCategoryChildList.size();
}
}
}
this is model class
public class SubCategoryChild {
#SerializedName("merchant_id")
#Expose
private String merchantId;
#SerializedName("merchant_name")
#Expose
private String merchantName;
#SerializedName("name")
#Expose
private String name;
#SerializedName("deal_sub_title")
#Expose
private String dealSubTitle;
#SerializedName("discounted_price")
#Expose
private String discountedPrice;
#SerializedName("actual_price")
#Expose
private String actualPrice;
#SerializedName("discounted_percentage")
#Expose
private String discountedPercentage;
#SerializedName("category_id")
#Expose
private String categoryId;
#SerializedName("sub_category_id")
#Expose
private String subCategoryId;
#SerializedName("city_id")
#Expose
private String cityId;
#SerializedName("logo")
#Expose
private String logo;
#SerializedName("website")
#Expose
private String website;
#SerializedName("email")
#Expose
private String email;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("description")
#Expose
private String description;
#SerializedName("Merchant_address")
#Expose
private String merchantAddress;
#SerializedName("latitude")
#Expose
private String latitude;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("distance")
#Expose
private String distance;
#SerializedName("deal_count")
#Expose
private Integer dealCount;
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public String getMerchantName() {
return merchantName;
}
public void setMerchantName(String merchantName) {
this.merchantName = merchantName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDealSubTitle() {
return dealSubTitle;
}
public void setDealSubTitle(String dealSubTitle) {
this.dealSubTitle = dealSubTitle;
}
public String getDiscountedPrice() {
return discountedPrice;
}
public void setDiscountedPrice(String discountedPrice) {
this.discountedPrice = discountedPrice;
}
public String getActualPrice() {
return actualPrice;
}
public void setActualPrice(String actualPrice) {
this.actualPrice = actualPrice;
}
public String getDiscountedPercentage() {
return discountedPercentage;
}
public void setDiscountedPercentage(String discountedPercentage) {
this.discountedPercentage = discountedPercentage;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getSubCategoryId() {
return subCategoryId;
}
public void setSubCategoryId(String subCategoryId) {
this.subCategoryId = subCategoryId;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMerchantAddress() {
return merchantAddress;
}
public void setMerchantAddress(String merchantAddress) {
this.merchantAddress = merchantAddress;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public Integer getDealCount() {
return dealCount;
}
public void setDealCount(Integer dealCount) {
this.dealCount = dealCount;
}
}
this is activity class
public class SubCategoryChild_Activity extends AppCompatActivity {
RecyclerView subCategoryDeal_RecyclerView;
public Context context;
ProgressBar progress_bar;
SubCategoryChild_Adapter subCategoryChild_adapter;
List<SubCategoryChild> subCategoryChildList;
SubCategoryChild subCategoryChild;
public String catId,subCatId,ActionBar_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category_child_);
Bundle extras = getIntent().getExtras();
catId = extras.getString("cat_Id");
subCatId = extras.getString("Sub_CatId");
ActionBar_Name = extras.getString("actionBar_Name");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(ActionBar_Name);
subCategoryDeal_RecyclerView = (RecyclerView) findViewById(R.id.subCategoryDeal_RecyclerView);
final ProgressBar progress_bar = (ProgressBar) findViewById(R.id.ScChild_progress_bar);
subCategoryDeal_RecyclerView.setLayoutManager(new LinearLayoutManager(this));
subCategoryDeal_RecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
subCategoryDeal_RecyclerView.setLayoutManager(layoutManager);
subCategoryDeal_RecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
subCategoryDeal_RecyclerView.setItemAnimator(new DefaultItemAnimator());
subCategoryChild_adapter = new SubCategoryChild_Adapter(context, subCategoryChildList);
subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter);
progress_bar.setVisibility(View.VISIBLE);
if(new SubCategoryChild_Response().getStatus() == null){
RestClient.get(this).diskCacheEnable(true).new NetworkTask<Void, SubCategoryChild_Response>(SubCategoryChild_Response.class, Http.GET) {
#Override
protected void onPostExecute(SubCategoryChild_Response subCategoryChild_response) {
super.onPostExecute(subCategoryChild_response);
progress_bar.setVisibility(View.GONE);
if (subCategoryChild_response != null && subCategoryChild_response.getSubCategoryChild() != null & subCategoryChild_response.getSubCategoryChild().size() > 0) {
subCategoryChildList = subCategoryChild_response.getSubCategoryChild();
subCategoryChild_adapter = new SubCategoryChild_Adapter(SubCategoryChild_Activity.this, subCategoryChildList);
subCategoryDeal_RecyclerView.setAdapter(subCategoryChild_adapter);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://api.bargaincry.com/apurl/deal/get_merchantBy_subcat/41187/" + catId + "/" + subCatId + "/latitude~longitude");
}else {
if(new SubCategoryChild_Response().getStatus().isEmpty())
Toast.makeText(SubCategoryChild_Activity.this,"error",Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.navigation_,menu);
//getMenuInflater().inflate(R.menu.navigation_, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
ComponentName cn = new ComponentName(this, SearchResultsActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));
//searchView.setSubmitButtonEnabled(true);
//searchView.setOnQueryTextListener(MainActivity.this);
searchView.setIconifiedByDefault(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is Response class
public class SubCategoryChild_Response {
#SerializedName("status")
#Expose
private String status;
#SerializedName("merchant")
#Expose
private List<SubCategoryChild> subCategoryChildList = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<SubCategoryChild> getSubCategoryChild() {
return subCategoryChildList;
}
public void setSubCategoryChildList(List<SubCategoryChild> subCategoryChildList) {
this.subCategoryChildList = subCategoryChildList;
}
}
this is catLog here
FATAL EXCEPTION: main Process: app.com.BargainCryApp, PID: 28129
java.lang.ClassCastException: java.lang.String cannot be cast to
models.SubCategoryChild_Response at
app.com.BargainCryApp.SubCategoryChild_Activity$1.onPostExecute(SubCategoryChild_Activity.java:69)
at android.os.AsyncTask.finish(AsyncTask.java:665) at
android.os.AsyncTask.-wrap1(AsyncTask.java) at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:682)
at android.os.Handler.dispatchMessage(Handler.java:111) at
android.os.Looper.loop(Looper.java:207) at
android.app.ActivityThread.main(ActivityThread.java:5769) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:861)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Before casting object, check instanceOf
if (holder instanceof MyViewHolder) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.subcategorychild_merchantName.setText(subCategoryChild.getMerchantName());
//..........
}
For your question how to avoid ClassCastException, the answer is use 'instanceof'
operator and instanceof returns true then further perform your actions.
if (subCategoryChild_response != null &&
subCategoryChild_response.getSubCategoryChild() != null &&
subCategoryChild_response.getSubCategoryChild() instanceof 'Your Child Class should be here'
subCategoryChild_response.getSubCategoryChild().size() > 0)
Hope this helps you
I want to get data from my localhost with retrofit library. I want to make it so that when I click the button, all TextView will set new value. For example, TextView username will change "developer" in my json file. However, when I clicked the button I guess json returned null because I can not see anything. Can you help me solve this problem?
JSON File :
{"USERS":[{"_id":"587c0346f8469d38a0ea46bf",
"username":"developer",
"name":"Akif",
"surname":"Demirezen",
"tel":"023656565",
"age":"25",
"location_id":{"_id":"587c0346f8469d38a0ea46be",
"il":"istanbul",
"ilce":"cevizlibağ"},
"__v":0}]}
Example.class :
public class Example {
#SerializedName("USERS")
#Expose
private List<USER> uSERS = null;
public List<USER> getUSERS() {
return uSERS;
}
public void setUSERS(List<USER> uSERS) {
this.uSERS = uSERS;
}
}
LocationID Class :
public class LocationId {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("il")
#Expose
private String il;
#SerializedName("ilce")
#Expose
private String ilce;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIl() {
return il;
}
public void setIl(String il) {
this.il = il;
}
public String getIlce() {
return ilce;
}
public void setIlce(String ilce) {
this.ilce = ilce;
}
}
Main Activity Class :
public class MainActivity extends AppCompatActivity {
TextView tid,tusername,tname,tsurname,tage,ttel,tlocationid;
Button butonverilerigoster;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tid = (TextView) findViewById(R.id.t_id);
tusername = (TextView) findViewById(R.id.t_username);
tname = (TextView) findViewById(R.id.t_name);
tsurname = (TextView) findViewById(R.id.t_surname);
tage = (TextView) findViewById(R.id.t_age);
ttel = (TextView) findViewById(R.id.t_tel);
tlocationid = (TextView) findViewById(R.id.t_locationid);
butonverilerigoster = (Button) findViewById(R.id.butonusergetir);
butonverilerigoster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(new Runnable() {
public void run() {
ApiService.Factory.getInstance().getuse().enqueue(new Callback<USER>() {
#Override
public void onResponse(Call<USER> call, Response<USER> response) {
tid.setText(response.body().getId());
tusername.setText(response.body().getUsername());
tname.setText(response.body().getName());
tsurname.setText(response.body().getSurname());
tage.setText(response.body().getAge());
ttel.setText(response.body().getTel());
tlocationid.setText((CharSequence) response.body().getLocationId());
}
#Override
public void onFailure(Call<USER> call, Throwable t) {
Log.e("Failed", t.getMessage());
}
});
}
}).start();
}
});
}
}
User class :
public class USER {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("tel")
#Expose
private String tel;
#SerializedName("age")
#Expose
private String age;
#SerializedName("location_id")
#Expose
private LocationId locationId;
#SerializedName("__v")
#Expose
private Integer v;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public LocationId getLocationId() {
return locationId;
}
public void setLocationId(LocationId locationId) {
this.locationId = locationId;
}
public Integer getV() {
return v;
}
public void setV(Integer v) {
this.v = v;
}
}