how to avoid ClassCast Exception - android

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

Related

Trying to use GSON with OpenWeather API

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.

Json Return Null Using Retrofit Library Android

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;
}
}

Android Attempt to invoke virtual method '...' on a null object reference

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

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;
}

Adding items to Realm database changes some variables

This is the code I have:
for (SearchData searchData1 : searchDataTemp){
Log.i("", "test is favourite searchdata:" + searchData1.getIs_favorite() + "..name: " + searchData1.getTitle());
}
Realm realm = Realm.getInstance(getActivity());
realm.beginTransaction();
List<SearchData> managedSeachData = realm.copyToRealmOrUpdate(searchDataTemp);
realm.commitTransaction();
for (SearchData searchData1 : managedSeachData) {
Log.i("", "test is favourite searchdata:" + searchData1.getIs_favorite() + "..name: " + searchData1.getTitle());
user.getRecents().add(searchData1);
}
This is what I get for the normal list in my logs:
test is favourite searchdata:true..name: Vondelpark
This is what I get for the managed Realmlist in my logs:
test is favourite searchdata:false..name: Vondelpark
Any ideea how this can be fixed?
PS: This is my SearchData model:
public class SearchData extends RealmObject{
#PrimaryKey
private String id;
private String title;
private String subtitle;
private String reference;
private String place_id;
private boolean is_favorite;
private int timestamp;
private String last_travel_mode;
private Geometry geometry;
private double distance;
private boolean close;
private int visited_count;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getPlace_id() {
return place_id;
}
public void setPlace_id(String place_id) {
this.place_id = place_id;
}
public boolean getIs_favorite() {
return is_favorite;
}
public void setIs_favorite(boolean is_favorite) {
this.is_favorite = is_favorite;
}
public int getTimestamp() {
return timestamp;
}
public void setTimestamp(int timestamp) {
this.timestamp = timestamp;
}
public String getLast_travel_mode() {
return last_travel_mode;
}
public void setLast_travel_mode(String last_travel_mode) {
this.last_travel_mode = last_travel_mode;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public boolean isClose() {
return close;
}
public void setClose(boolean close) {
this.close = close;
}
public boolean is_favorite() {
return is_favorite;
}
public int getVisited_count() {
return visited_count;
}
public void setVisited_count(int visited_count) {
this.visited_count = visited_count;
}
public SearchData() {
}
public SearchData(String id, String title, String subtitle, String reference, String place_id, boolean is_favorite, int timestamp, String last_travel_mode , int visited_count){
this.id = id;
this.title = title;
this.subtitle = subtitle;
this.reference = reference;
this.place_id = place_id;
this.is_favorite = is_favorite;
this.timestamp = timestamp;
this.last_travel_mode = last_travel_mode;
this.visited_count = visited_count;
}
public SearchData(String id, String title, String subtitle, String reference, String place_id, boolean is_favorite, int timestamp, String last_travel_mode, Geometry geometry , int visited_count){
this.id = id;
this.title = title;
this.subtitle = subtitle;
this.reference = reference;
this.place_id = place_id;
this.is_favorite = is_favorite;
this.timestamp = timestamp;
this.last_travel_mode = last_travel_mode;
this.geometry = geometry;
this.visited_count = visited_count;
}
}
SearchData class has both getIs_favorite() and is_favorite().
In that case, Realm annotation processor overrides only is_favorite().
That's why getIs_favorite() returns always false.

Categories

Resources