Please i need help , i am new to android so i need help . i need to receive data from JSON and i watched a loot of tutorials and i cant find my answer . I need to receive data from JSON link . once i do it i get a loot of errors and also the compilator gives me a lot of errors . Here is my code :
my custom adapter called CustomItemAdapter.java
package com.example.madrit.okhttp_gson_view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CustomItemAdapter extends ArrayAdapter <model_item> {
public CustomItemAdapter(Context context , List<model_item> mymodel)
{
super(context , 0 , mymodel);
}
#Nullable
#Override
public model_item getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
model_item model = getItem(position);
if (convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_shop_list, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.item_onthelist_title);
TextView price = (TextView) convertView.findViewById(R.id.item_onthelist_price);
TextView description = (TextView) convertView.findViewById(R.id.item_onthelist_description);
title.setText(model.getName());
price.setText(Double.toString(model.getPrice()));
description.setText(model.getMeta_description());
return convertView;
}
}
my model item model_item.java
package com.example.madrit.okhttp_gson_view;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class model_item {
private String id_product;
private String id_supplier;
private String id_manufacturer;
private String id_category_default;
private String id_shop_default;
private String id_tax_rules_group;
private String on_sale;
private String online_only;
private String ean13;
private String upc;
private String ecotax;
private int quantity;
private String minimal_quantity;
private double price;
private String wholesale_price;
private String unity;
private String unit_price_ratio;
private String additional_shipping_cost;
private String reference;
private String supplier_reference;
private String location;
private String width;
private String height;
private String depth;
private String weight;
private String out_of_stock;
private String quantity_discount;
private String customizable;
private String uploadable_files;
private String text_fields;
private String active;
private String redirect_type;
private String id_product_redirected;
private String available_for_order;
private String available_date;
private String condition;
private String show_price;
private String indexed;
private String visibility;
private String cache_is_pack;
private String cache_has_attachments;
private String is_virtual;
private String cache_default_attribute;
private String date_add;
private String date_upd;
private String advanced_stock_management;
private String pack_stock_type;
private String id_shop;
private int id_product_attribute;
private String product_attribute_minimal_quantity;
private String description;
private String description_short;
private String available_now;
private String available_later;
private String link_rewrite;
private String meta_description;
private String meta_keywords;
private String meta_title;
private String name;
private String id_image;
private String legend;
private String manufacturer_name;
private String category_default;
#SerializedName("new")
private String newX;
private String orderprice;
private int allow_oosp;
private String category;
private String link;
private int attribute_price;
private double price_tax_exc;
private double price_without_reduction;
private int reduction;
private boolean specific_prices;
private int quantity_all_versions;
private int virtual;
private int pack;
private int nopackprice;
private boolean customization_required;
private int rate;
private String tax_name;
private String image_url;
private List<?> features;
private List<?> attachments;
private List<?> packItems;
public String getId_product() {
return id_product;
}
public void setId_product(String id_product) {
this.id_product = id_product;
}
public String getId_supplier() {
return id_supplier;
}
public void setId_supplier(String id_supplier) {
this.id_supplier = id_supplier;
}
public String getId_manufacturer() {
return id_manufacturer;
}
public void setId_manufacturer(String id_manufacturer) {
this.id_manufacturer = id_manufacturer;
}
public String getId_category_default() {
return id_category_default;
}
public void setId_category_default(String id_category_default) {
this.id_category_default = id_category_default;
}
public String getId_shop_default() {
return id_shop_default;
}
public void setId_shop_default(String id_shop_default) {
this.id_shop_default = id_shop_default;
}
public String getId_tax_rules_group() {
return id_tax_rules_group;
}
public void setId_tax_rules_group(String id_tax_rules_group) {
this.id_tax_rules_group = id_tax_rules_group;
}
public String getOn_sale() {
return on_sale;
}
public void setOn_sale(String on_sale) {
this.on_sale = on_sale;
}
public String getOnline_only() {
return online_only;
}
public void setOnline_only(String online_only) {
this.online_only = online_only;
}
public String getEan13() {
return ean13;
}
public void setEan13(String ean13) {
this.ean13 = ean13;
}
public String getUpc() {
return upc;
}
public void setUpc(String upc) {
this.upc = upc;
}
public String getEcotax() {
return ecotax;
}
public void setEcotax(String ecotax) {
this.ecotax = ecotax;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getMinimal_quantity() {
return minimal_quantity;
}
public void setMinimal_quantity(String minimal_quantity) {
this.minimal_quantity = minimal_quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getWholesale_price() {
return wholesale_price;
}
public void setWholesale_price(String wholesale_price) {
this.wholesale_price = wholesale_price;
}
public String getUnity() {
return unity;
}
public void setUnity(String unity) {
this.unity = unity;
}
public String getUnit_price_ratio() {
return unit_price_ratio;
}
public void setUnit_price_ratio(String unit_price_ratio) {
this.unit_price_ratio = unit_price_ratio;
}
public String getAdditional_shipping_cost() {
return additional_shipping_cost;
}
public void setAdditional_shipping_cost(String additional_shipping_cost) {
this.additional_shipping_cost = additional_shipping_cost;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getSupplier_reference() {
return supplier_reference;
}
public void setSupplier_reference(String supplier_reference) {
this.supplier_reference = supplier_reference;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getDepth() {
return depth;
}
public void setDepth(String depth) {
this.depth = depth;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOut_of_stock() {
return out_of_stock;
}
public void setOut_of_stock(String out_of_stock) {
this.out_of_stock = out_of_stock;
}
public String getQuantity_discount() {
return quantity_discount;
}
public void setQuantity_discount(String quantity_discount) {
this.quantity_discount = quantity_discount;
}
public String getCustomizable() {
return customizable;
}
public void setCustomizable(String customizable) {
this.customizable = customizable;
}
public String getUploadable_files() {
return uploadable_files;
}
public void setUploadable_files(String uploadable_files) {
this.uploadable_files = uploadable_files;
}
public String getText_fields() {
return text_fields;
}
public void setText_fields(String text_fields) {
this.text_fields = text_fields;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getRedirect_type() {
return redirect_type;
}
public void setRedirect_type(String redirect_type) {
this.redirect_type = redirect_type;
}
public String getId_product_redirected() {
return id_product_redirected;
}
public void setId_product_redirected(String id_product_redirected) {
this.id_product_redirected = id_product_redirected;
}
public String getAvailable_for_order() {
return available_for_order;
}
public void setAvailable_for_order(String available_for_order) {
this.available_for_order = available_for_order;
}
public String getAvailable_date() {
return available_date;
}
public void setAvailable_date(String available_date) {
this.available_date = available_date;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getShow_price() {
return show_price;
}
public void setShow_price(String show_price) {
this.show_price = show_price;
}
public String getIndexed() {
return indexed;
}
public void setIndexed(String indexed) {
this.indexed = indexed;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getCache_is_pack() {
return cache_is_pack;
}
public void setCache_is_pack(String cache_is_pack) {
this.cache_is_pack = cache_is_pack;
}
public String getCache_has_attachments() {
return cache_has_attachments;
}
public void setCache_has_attachments(String cache_has_attachments) {
this.cache_has_attachments = cache_has_attachments;
}
public String getIs_virtual() {
return is_virtual;
}
public void setIs_virtual(String is_virtual) {
this.is_virtual = is_virtual;
}
public String getCache_default_attribute() {
return cache_default_attribute;
}
public void setCache_default_attribute(String cache_default_attribute) {
this.cache_default_attribute = cache_default_attribute;
}
public String getDate_add() {
return date_add;
}
public void setDate_add(String date_add) {
this.date_add = date_add;
}
public String getDate_upd() {
return date_upd;
}
public void setDate_upd(String date_upd) {
this.date_upd = date_upd;
}
public String getAdvanced_stock_management() {
return advanced_stock_management;
}
public void setAdvanced_stock_management(String advanced_stock_management) {
this.advanced_stock_management = advanced_stock_management;
}
public String getPack_stock_type() {
return pack_stock_type;
}
public void setPack_stock_type(String pack_stock_type) {
this.pack_stock_type = pack_stock_type;
}
public String getId_shop() {
return id_shop;
}
public void setId_shop(String id_shop) {
this.id_shop = id_shop;
}
public int getId_product_attribute() {
return id_product_attribute;
}
public void setId_product_attribute(int id_product_attribute) {
this.id_product_attribute = id_product_attribute;
}
public String getProduct_attribute_minimal_quantity() {
return product_attribute_minimal_quantity;
}
public void setProduct_attribute_minimal_quantity(String product_attribute_minimal_quantity) {
this.product_attribute_minimal_quantity = product_attribute_minimal_quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription_short() {
return description_short;
}
public void setDescription_short(String description_short) {
this.description_short = description_short;
}
public String getAvailable_now() {
return available_now;
}
public void setAvailable_now(String available_now) {
this.available_now = available_now;
}
public String getAvailable_later() {
return available_later;
}
public void setAvailable_later(String available_later) {
this.available_later = available_later;
}
public String getLink_rewrite() {
return link_rewrite;
}
public void setLink_rewrite(String link_rewrite) {
this.link_rewrite = link_rewrite;
}
public String getMeta_description() {
return meta_description;
}
public void setMeta_description(String meta_description) {
this.meta_description = meta_description;
}
public String getMeta_keywords() {
return meta_keywords;
}
public void setMeta_keywords(String meta_keywords) {
this.meta_keywords = meta_keywords;
}
public String getMeta_title() {
return meta_title;
}
public void setMeta_title(String meta_title) {
this.meta_title = meta_title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId_image() {
return id_image;
}
public void setId_image(String id_image) {
this.id_image = id_image;
}
public String getLegend() {
return legend;
}
public void setLegend(String legend) {
this.legend = legend;
}
public String getManufacturer_name() {
return manufacturer_name;
}
public void setManufacturer_name(String manufacturer_name) {
this.manufacturer_name = manufacturer_name;
}
public String getCategory_default() {
return category_default;
}
public void setCategory_default(String category_default) {
this.category_default = category_default;
}
public String getNewX() {
return newX;
}
public void setNewX(String newX) {
this.newX = newX;
}
public String getOrderprice() {
return orderprice;
}
public void setOrderprice(String orderprice) {
this.orderprice = orderprice;
}
public int getAllow_oosp() {
return allow_oosp;
}
public void setAllow_oosp(int allow_oosp) {
this.allow_oosp = allow_oosp;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public int getAttribute_price() {
return attribute_price;
}
public void setAttribute_price(int attribute_price) {
this.attribute_price = attribute_price;
}
public double getPrice_tax_exc() {
return price_tax_exc;
}
public void setPrice_tax_exc(double price_tax_exc) {
this.price_tax_exc = price_tax_exc;
}
public double getPrice_without_reduction() {
return price_without_reduction;
}
public void setPrice_without_reduction(double price_without_reduction) {
this.price_without_reduction = price_without_reduction;
}
public int getReduction() {
return reduction;
}
public void setReduction(int reduction) {
this.reduction = reduction;
}
public boolean isSpecific_prices() {
return specific_prices;
}
public void setSpecific_prices(boolean specific_prices) {
this.specific_prices = specific_prices;
}
public int getQuantity_all_versions() {
return quantity_all_versions;
}
public void setQuantity_all_versions(int quantity_all_versions) {
this.quantity_all_versions = quantity_all_versions;
}
public int getVirtual() {
return virtual;
}
public void setVirtual(int virtual) {
this.virtual = virtual;
}
public int getPack() {
return pack;
}
public void setPack(int pack) {
this.pack = pack;
}
public int getNopackprice() {
return nopackprice;
}
public void setNopackprice(int nopackprice) {
this.nopackprice = nopackprice;
}
public boolean isCustomization_required() {
return customization_required;
}
public void setCustomization_required(boolean customization_required) {
this.customization_required = customization_required;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public String getTax_name() {
return tax_name;
}
public void setTax_name(String tax_name) {
this.tax_name = tax_name;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public List<?> getFeatures() {
return features;
}
public void setFeatures(List<?> features) {
this.features = features;
}
public List<?> getAttachments() {
return attachments;
}
public void setAttachments(List<?> attachments) {
this.attachments = attachments;
}
public List<?> getPackItems() {
return packItems;
}
public void setPackItems(List<?> packItems) {
this.packItems = packItems;
}
}
list_main_item.java ( the main activity ) :
package com.example.madrit.okhttp_gson_view;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class list_main_item extends AppCompatActivity {
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.item_shop_list_view);
String url = "http://77.242.25.43:8080/girogama/modules/api/mApi/v1/categories.php?action=get_products&id_category=6&page=1&products_per_page=15";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Gson gson = new Gson();
model_item[] model = gson.fromJson(json , model_item[].class);
List<model_item> list = Arrays.asList(model);
final ListAdapter myadapter = new CustomItemAdapter(list_main_item.this,list);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
listview.setAdapter(myadapter);
Log.i("Item_shop_activity"," te dhenat e response");
}
});
}
});
setContentView(R.layout.activity_list__main_item);
}
}
my main xml file activity_list_main_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_item_shop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.madrit.okhttp_gson_view.list_main_item">
<ListView
android:id="#+id/item_shop_list_view"
android:layout_width="wrap_content"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
the error
the error it gaved me
Please i need help , even if i have done any other stupid error with data parsing !!
Call setContentView(R.layout.activity_list__main_item); right after super.onCreate(savedInstanceState); or before assigning/accessing any views.
Related
Api (Interface)
package com.example.openweathermap;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface Api {
String BASE_URL="https://samples.openweathermap.org/data/2.5/";
#GET("weather/")
Call<WeatherResponse> getWeatherDetails(#Query("api_key")String api_key);
}
My Model Class
Here is my model class which consists of getters and setters
package com.example.openweathermap;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Weather {
#SerializedName("coord")
private String coord;
#SerializedName("lon")
private String lon;
#SerializedName("lat")
private String lat;
#SerializedName("weather")
private List<Integer> weather = new ArrayList<Integer>();
#SerializedName("description")
private String description;
#SerializedName("base")
private String base;
#SerializedName("main")
private String main;
#SerializedName("temp")
private String temp;
#SerializedName("pressure")
private String pressure;
#SerializedName("humidity")
private Integer humidity;
#SerializedName("temp_min")
private String temp_min;
#SerializedName("temp_max")
private String temp_max;
#SerializedName("visibility")
private String visibility;
#SerializedName("wind")
private String wind;
#SerializedName("speed")
private String speed;
#SerializedName("deg")
private String deg;
#SerializedName("clouds")
private String clouds;
#SerializedName("all")
private String all;
#SerializedName("dt")
private String dt;
#SerializedName("sys")
private String sys;
#SerializedName("type")
private String type;
#SerializedName("id")
private String id;
#SerializedName("message")
private String message;
#SerializedName("country")
private String country;
#SerializedName("sunrise")
private String sunrise;
#SerializedName("sunset")
private String sunset;
public Weather(String description) {
this.description = description;
}
public Weather(String coord, String lon, String lat, List<Integer> weather, String base, String main, String temp, String pressure, Integer humidity, String temp_min, String temp_max, String visibility, String wind, String speed, String deg, String clouds, String all, String dt, String sys, String type, String id, String message, String country, String sunrise, String sunset) {
this.coord = coord;
this.lon = lon;
this.lat = lat;
this.weather = weather;
this.base = base;
this.main = main;
this.temp = temp;
this.pressure = pressure;
this.humidity = humidity;
this.temp_min = temp_min;
this.temp_max = temp_max;
this.visibility = visibility;
this.wind = wind;
this.speed = speed;
this.deg = deg;
this.clouds = clouds;
this.all = all;
this.dt = dt;
this.sys = sys;
this.type = type;
this.id = id;
this.message = message;
this.country = country;
this.sunrise = sunrise;
this.sunset = sunset;
}
public String getCoord() {
return coord;
}
public void setCoord(String coord) {
this.coord = coord;
}
public String getLon() {
return lon;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public List<Integer> getWeather() {
return weather;
}
public void setWeather(List<Integer> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getPressure() {
return pressure;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public String getTemp_min() {
return temp_min;
}
public void setTemp_min(String temp_min) {
this.temp_min = temp_min;
}
public String getTemp_max() {
return temp_max;
}
public void setTemp_max(String temp_max) {
this.temp_max = temp_max;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getDeg() {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public String getClouds() {
return clouds;
}
public void setClouds(String clouds) {
this.clouds = clouds;
}
public String getAll() {
return all;
}
public void setAll(String all) {
this.all = all;
}
public String getDt() {
return dt;
}
public void setDt(String dt) {
this.dt = dt;
}
public String getSys() {
return sys;
}
public void setSys(String sys) {
this.sys = sys;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getSunrise() {
return sunrise;
}
public void setSunrise(String sunrise) {
this.sunrise = sunrise;
}
public String getSunset() {
return sunset;
}
public void setSunset(String sunset) {
this.sunset = sunset;
}
}
MyJSONResponse
I am trying to get this data in adapter which is a RecyclerView Adapter
package com.example.openweathermap;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class WeatherResponse {
#SerializedName("weather")
private List<Weather> weather;
#SerializedName("id")
private String id;
#SerializedName("main")
private String main;
#SerializedName("description")
private String description;
#SerializedName("temp")
private String temp;
public WeatherResponse(List<Weather> weather) {
this.weather = weather;
}
public WeatherResponse(String weather, String id, String main, String description, String temp) {
this.id = id;
this.main = main;
this.description = description;
this.temp = temp;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getId() {
return id;
}
public void setId(String 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 getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
}
----------
**MyAdapter
This is the recyclerview adapter**
----------
package com.example.openweathermap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Weather> weathers;
public Context context;
public MyAdapter(ArrayList<Weather> weathers, Context context) {
this.weathers = weathers;
this.context = context;
}
public MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.ViewHolder holder, int position) {
Weather weather=weathers.get(position);
holder.temp.setText(weather.getTemp());
/*holder.name.setText(weather.getCountry());*/
holder.description.setText(weather.getDescription());
weathers=new ArrayList<>();
}
#Override
public int getItemCount() {
return weathers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView temp;
public TextView name;
public TextView description;
public ViewHolder(#NonNull View itemView) {
super(itemView);
temp=(TextView)itemView.findViewById(R.id.temp);
name=(TextView)itemView.findViewById(R.id.name);
description=(TextView)itemView.findViewById(R.id.description);
}
}
}
Main Activity
package com.example.openweathermap;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<Weather> weathersList;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "ae47e0f7eb5fbbce0c9cfbdf1373a1b3";
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
weathersList=new ArrayList<>();
if (API_KEY.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please obtain your API KEY first ", Toast.LENGTH_LONG).show();
return;
}
getWeather();
}
private void getWeather() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api=retrofit.create(Api.class);
Call<WeatherResponse> call=api.getWeatherDetails(API_KEY);
call.enqueue(new Callback<WeatherResponse>() {
#Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
ArrayList<Weather> weathersList = (ArrayList<Weather>) response.body().getWeather();
adapter=new MyAdapter(weathersList,getApplicationContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
I am getting an error as " Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference RecyclerView Adapter Error" in MyAdapter
I have tough problem with my project. Its hard to explain. I have two different model but, I should compare these two model. Should I make a new model for this two models?
Here is Cart.java. There is Voyage.java as a Model. This class differentiate if type_voyage not equals each other. I have another model named Bus.java. I should compare if it equals together with model.
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
ArrayList<Voyage> list = Lists.newArrayList(Collections2.filter(voyages, new Predicate<Voyage>() {
#Override
public boolean apply(Voyage voyage) {
return !voyage.getType_voyage().equals(type_voyage);
}
}));
return list.size() > 0 ? true : false;
}
Bus.java
public class Bus {
private static Bus instance;
private String BROADCAST_TAG = "com.bss.hepsi.bus";
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<BusPassenger> busPasengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_bus;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
boolean isExpanded;
boolean isShowProgress;
public Bus() {
}
public static synchronized Bus getInstance() {
if (instance == null) {
instance = new Bus();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public boolean isShowProgress() {
return this.isShowProgress;
}
public void setShowProgress(boolean showProgress) {
this.isShowProgress = showProgress;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_bus() {
return type_bus;
}
public void setType_voyage(String type_bus) {
this.type_bus = type_bus;
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
if (resultReturn.length()<1){
busReturnIsEmpty();}
else{
busReturnIsNotEmpty();
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(600 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
private void sendVoyagesArrayBroadcast(String target, JSONArray resultArray) {
Intent intent = new Intent();
intent.setAction(BROADCAST_TAG + target);
intent.putExtra("data", resultArray.toString());
context.sendBroadcast(intent);
}
public static Bus setJsonToClass(JSONObject jsonObject, int direction, String owner) {
Bus bus = new Gson().fromJson(String.valueOf(jsonObject), Bus.class);
bus.setDirection(direction);
bus.setType_voyage(owner);
bus.setDepartureTime(bus.departure_time);
bus.setArrivalTime(bus.arrival_time);
for (Leg leg :
bus.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
bus.type = owner;
return bus;
}
Voyage.java
public class Voyage {
private static Voyage instance;
//private static String url="http://78.186.57.167:3000/";
//private static String url="http://10.0.0.27:1337/";
/////public static final String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///bunu kaldırdım static oldugu için
private String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///onun yerine bunu koydum
//private static String url="http://185.122.203.104:3002/";
// private static String url="http://10.0.0.25:1337/";
public int checkCart; // Result activity'de veri gelip gelmediğini kontrol edip kullanıcıyı uyarmak için
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<FlightPassenger> flightPassengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_voyage;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
public Voyage() {
}
public static synchronized Voyage getInstance() {
if (instance == null) {
instance = new Voyage();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
/*public static String getUrl() {
return url;
}*/
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_voyage() {
return type_voyage;
}
public void setType_voyage(String type_voyage) {
this.type_voyage = type_voyage;
}
public void searchFlightVoyages(Context context) {
this.context = context;
cancelRequest("flight/search", context);
Map<String, String> header = prepareVoyageSearchHeaderForFlight();
sendRequest("flight/search", header);
}
public void searchTrainVoyages(Context context) {
this.context = context;
cancelRequest("train/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("train/search", header);
}
public void searchBoatVoyages(Context context) {
this.context = context;
cancelRequest("seaway/boat/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/boat/search", header);
}
public void searchFerryVoyages(Context context) {
this.context = context;
cancelRequest("seaway/ferry/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/ferry/search", header);
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
// servisten gelen cevap not_available ise
//// owner
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
// servisten gösterilebilecek bir sonuç geldiyse
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
// checkCart=0;
// sendCheckCart();
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setTag(owner);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public static Voyage setJsonToClass(JSONObject jsonObject, int direction, String owner) {
//Log.e("jsonobj", String.valueOf(jsonObject));
Voyage voyage = new Gson().fromJson(String.valueOf(jsonObject), Voyage.class);
voyage.setDirection(direction);
voyage.setType_voyage(owner);
voyage.setDepartureTime(voyage.departure_time);
voyage.setArrivalTime(voyage.arrival_time);
for (Leg leg :
voyage.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
voyage.type = owner;
return voyage;
}
When you remove all the code from your question that is superfluous, it makes the problem more obvious.
First I simplified your comparison method:
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
for(Voyage voyage : voyages) {
if(!type_voyage.equals(voyage.getType_voyage()) {
return true;
}
}
}
Then created an interface
interface Voyage {
String getType_voyage();
}
Bus.java
public class Bus implements Voyage {
...
private String type_voyage;
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
And changed Voyage.java to Ferry.java
public class Ferry implements Voyage {
...
private String type_voyage;
...
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
You may want to look at creating some more classes so that your 'model' classes are not doing to much / have so many responsibilities.
I have an autocompletetextview. I am getting results from an API and sending to the adapter on textchanged.
Here is the adapter.
public class ProductSearchAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<ProductListModel> originalList;
private ArrayList<ProductListModel> suggestions = new ArrayList<>();
private Filter filter = new CustomFilter();
public ProductSearchAdapter(Context context, ArrayList<ProductListModel> originalList) {
this.context = context;
this.originalList = originalList;
}
#Override
public int getCount() {
return suggestions.size(); // Return the size of the suggestions list.
}
#Override
public Object getItem(int position) {
return originalList.get(position).getName();
}
#Override
public long getItemId(int position) {
return 0;
}
/**
* This is where you inflate the layout and also where you set what you want to display.
* Here we also implement a View Holder in order to recycle the views.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.product_search_row, parent, false);
holder = new ViewHolder();
holder.textViewProductName = (TextView) convertView.findViewById(R.id.textViewProductName);
holder.imageViewProductImage = (ImageView) convertView.findViewById(R.id.imageViewProductImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewProductName.setText(originalList.get(position).getName());
Picasso.with(context)
.load(originalList.get(position).getImagesSmall().get(0).getSrc())
.into(holder.imageViewProductImage);
return convertView;
}
#Override
public Filter getFilter() {
return filter;
}
private static class ViewHolder {
ImageView imageViewProductImage;
TextView textViewProductName;
}
/**
* Our Custom Filter Class.
*/
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
for (int i = 0; i < originalList.size(); i++) {
if (originalList.get(i).getName().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.
suggestions.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
}
FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;
results.values = suggestions;
results.count = suggestions.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
Now the problem is the dropdown is not showing up. Whereas if I try the same autocompletetextview with array adapter, its showing up.
Here is the activity part I am calling the api from:
autoCompleteTextViewSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().length() > 0) {
hitSearchAPI(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
On API response:
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
productList = gson.fromJson(responseString, ProductListModel[].class);
arrayListProducts = new ArrayList<ProductListModel>(Arrays.asList(productList));
productsSearchAdapter = new ProductSearchAdapter(MainActivity.this, arrayListProducts);
autoCompleteTextViewSearch.setThreshold(1);
autoCompleteTextViewSearch.setAdapter(productsSearchAdapter);
Same textview working with array adapter but not with custom adapter.
ProductListModel:
public class ProductListModel {
String _id;
String name;
String color;
String description;
int credits;
ProductItemModel category;
ArrayList<ProductItemModel> subcategories;
ProductItemModel fit;
ProductBrandModel brand;
ArrayList<ProductItemModel> rules;
ProductBrandModel condition;
ArrayList<ProductImagesModel> images;
ArrayList<ProductItemModel> size;
ArrayList<ProductImagesModel> imagesSmall;
String userId;
long time_created;
long time_approved;
long time_featured;
long time_rejected;
boolean approved;
boolean rejected;
boolean featured;
int status;
ProductUserProfileModel user_profile;
String rejected_reason_id;
String categoryId;
int likes;
boolean likedBy;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
public ProductItemModel getCategory() {
return category;
}
public void setCategory(ProductItemModel category) {
this.category = category;
}
public ArrayList<ProductItemModel> getSubcategories() {
return subcategories;
}
public void setSubcategories(ArrayList<ProductItemModel> subcategories) {
this.subcategories = subcategories;
}
public ProductItemModel getFit() {
return fit;
}
public void setFit(ProductItemModel fit) {
this.fit = fit;
}
public ProductBrandModel getBrand() {
return brand;
}
public void setBrand(ProductBrandModel brand) {
this.brand = brand;
}
public ArrayList<ProductItemModel> getRules() {
return rules;
}
public void setRules(ArrayList<ProductItemModel> rules) {
this.rules = rules;
}
public ProductBrandModel getCondition() {
return condition;
}
public void setCondition(ProductBrandModel condition) {
this.condition = condition;
}
public ArrayList<ProductImagesModel> getImages() {
return images;
}
public void setImages(ArrayList<ProductImagesModel> images) {
this.images = images;
}
public ArrayList<ProductItemModel> getSize() {
return size;
}
public void setSize(ArrayList<ProductItemModel> size) {
this.size = size;
}
public ArrayList<ProductImagesModel> getImagesSmall() {
return imagesSmall;
}
public void setImagesSmall(ArrayList<ProductImagesModel> imagesSmall) {
this.imagesSmall = imagesSmall;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public long getTime_created() {
return time_created;
}
public void setTime_created(long time_created) {
this.time_created = time_created;
}
public long getTime_approved() {
return time_approved;
}
public void setTime_approved(long time_approved) {
this.time_approved = time_approved;
}
public long getTime_featured() {
return time_featured;
}
public void setTime_featured(long time_featured) {
this.time_featured = time_featured;
}
public long getTime_rejected() {
return time_rejected;
}
public void setTime_rejected(long time_rejected) {
this.time_rejected = time_rejected;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public boolean isRejected() {
return rejected;
}
public void setRejected(boolean rejected) {
this.rejected = rejected;
}
public boolean isFeatured() {
return featured;
}
public void setFeatured(boolean featured) {
this.featured = featured;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public ProductUserProfileModel getUser_profile() {
return user_profile;
}
public void setUser_profile(ProductUserProfileModel user_profile) {
this.user_profile = user_profile;
}
public String getRejected_reason_id() {
return rejected_reason_id;
}
public void setRejected_reason_id(String rejected_reason_id) {
this.rejected_reason_id = rejected_reason_id;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public boolean isLikedBy() {
return likedBy;
}
public void setLikedBy(boolean likedBy) {
this.likedBy = likedBy;
}
}
You need to add toString() method to your model so the AutoCompleteTextView can compare between the typed String and the returned value.
if you are looking by name the toString() needs to return it :
#Override
public String toString() {
return name ;
}
}
I am writing an android app that uses a bundle to pass data between activities. I made an Answers.java class to get the data from the bundle. When I try to get the data I receive an error Illegal Self-Reference. I get the error on
Answers a = a.getQuestion1_1();
Here is my activity code
package www.iup.edu.iupcrimsurvey;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Thank_You_MainActivity extends AppCompatActivity {
Answers a = a.getQuestion1_1();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thank__you__main);
// Sets an onClickListener to the button and calls the launchNextScreenActivity() method
final Button btn = (Button) findViewById(R.id.Next_Screen15);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
launchNextScreenActivity();
}
});
// Sets an onClickListener to the button and calls the launchNextScreenActivity() method
final Button btn2 = (Button) findViewById(R.id.Close);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
launchFinishActivity();
}
});
}
// Switches to the StartScreen_Activity screen
private void launchNextScreenActivity() {
Intent intent = new Intent(this, StartScreen_MainActivity.class);
startActivity(intent);
}
// Closes the app
private void launchFinishActivity() {
}
}
My Answers.java file
package www.iup.edu.iupcrimsurvey;
public class Answers {
private int question1_1 = StartScreen_MainActivity.MyAppsBundle.getInt("Demographics_question1");
private String question1_2 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question2");
private String question1_3 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question3");
private String question1_4 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question4");
private String question1_5 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question5");
private String question1_6 = StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question6");
private String question1_7= StartScreen_MainActivity.MyAppsBundle.getString("Demographics_question7");
private String question2_1 = StartScreen_MainActivity.MyAppsBundle.getString("housing_question1");
private int question2_2 = StartScreen_MainActivity.MyAppsBundle.getInt("housing_question2");
private String question2_3 = StartScreen_MainActivity.MyAppsBundle.getString("housing_question3");
private String question2_4 = StartScreen_MainActivity.MyAppsBundle.getString("housing_question4");
private String question3_1 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question1");
private String question3_2 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question2");
private String question3_3 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question3");
private String question3_4 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question4");
private String question3_5 = StartScreen_MainActivity.MyAppsBundle.getString("Sexuality_question5");
private String question4_1 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question1");
private String question4_2 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question2");
private String question4_3 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question3");
private String question4_4 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question4");
private String question4_5 = StartScreen_MainActivity.MyAppsBundle.getString("Alcohol_question5");
private String question5_1 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question1");
private String question5_2 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question2");
private String question5_3 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question3");
private String question5_4 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question4");
private String question5_5 = StartScreen_MainActivity.MyAppsBundle.getString("Travel_question5");
private String question6_1 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question1");
private String question6_2 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question2");
private String question6_3 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question3");
private String question6_4 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question4");
private String question6_5 = StartScreen_MainActivity.MyAppsBundle.getString("Work_question5");
private String question7_1 = StartScreen_MainActivity.MyAppsBundle.getString("Crime_question1");
private String question8_1 = StartScreen_MainActivity.MyAppsBundle.getString("Crime_Committed_question1");
private String question8_2 = StartScreen_MainActivity.MyAppsBundle.getString("Crime_Committed_question2");
private String question10_1 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question1");
private String question10_2 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question2");
private String question10_3 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question3");
private String question10_4 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question4");
private String question10_5 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question5");
private String question10_6 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question6");
private String question10_7 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question7");
private String question10_8 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question8");
private String question10_9 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question9");
private String question10_10 = StartScreen_MainActivity.MyAppsBundle.getString("Incident_question10");
public int getQuestion1_1() {
return question1_1;
}
public void setQuestion1_1(int question1_1) {
this.question1_1 = question1_1;
}
public String getQuestion1_2() {
return question1_2;
}
public void setQuestion1_2(String question1_2) {
this.question1_2 = question1_2;
}
public String getQuestion1_3() {
return question1_3;
}
public void setQuestion1_3(String question1_3) {
this.question1_3 = question1_3;
}
public String getQuestion1_4() {
return question1_4;
}
public void setQuestion1_4(String question1_4) {
this.question1_4 = question1_4;
}
public String getQuestion1_5() {
return question1_5;
}
public void setQuestion1_5(String question1_5) {
this.question1_5 = question1_5;
}
public String getQuestion1_6() {
return question1_6;
}
public void setQuestion1_6(String question1_6) {
this.question1_6 = question1_6;
}
public String getQuestion1_7() {
return question1_7;
}
public void setQuestion1_7(String question1_7) {
this.question1_7 = question1_7;
}
public String getQuestion2_1() {
return question2_1;
}
public void setQuestion2_1(String question2_1) {
this.question2_1 = question2_1;
}
public int getQuestion2_2() {
return question2_2;
}
public void setQuestion2_2(int question2_2) {
this.question2_2 = question2_2;
}
public String getQuestion2_3() {
return question2_3;
}
public void setQuestion2_3(String question2_3) {
this.question2_3 = question2_3;
}
public String getQuestion2_4() {
return question2_4;
}
public void setQuestion2_4(String question2_4) {
this.question2_4 = question2_4;
}
public String getQuestion3_1() {
return question3_1;
}
public void setQuestion3_1(String question3_1) {
this.question3_1 = question3_1;
}
public String getQuestion3_2() {
return question3_2;
}
public void setQuestion3_2(String question3_2) {
this.question3_2 = question3_2;
}
public String getQuestion3_3() {
return question3_3;
}
public void setQuestion3_3(String question3_3) {
this.question3_3 = question3_3;
}
public String getQuestion3_4() {
return question3_4;
}
public void setQuestion3_4(String question3_4) {
this.question3_4 = question3_4;
}
public String getQuestion3_5() {
return question3_5;
}
public void setQuestion3_5(String question3_5) {
this.question3_5 = question3_5;
}
public String getQuestion4_1() {
return question4_1;
}
public void setQuestion4_1(String question4_1) {
this.question4_1 = question4_1;
}
public String getQuestion4_2() {
return question4_2;
}
public void setQuestion4_2(String question4_2) {
this.question4_2 = question4_2;
}
public String getQuestion4_3() {
return question4_3;
}
public void setQuestion4_3(String question4_3) {
this.question4_3 = question4_3;
}
public String getQuestion4_4() {
return question4_4;
}
public void setQuestion4_4(String question4_4) {
this.question4_4 = question4_4;
}
public String getQuestion4_5() {
return question4_5;
}
public void setQuestion4_5(String question4_5) {
this.question4_5 = question4_5;
}
public String getQuestion5_1() {
return question5_1;
}
public void setQuestion5_1(String question5_1) {
this.question5_1 = question5_1;
}
public String getQuestion5_2() {
return question5_2;
}
public void setQuestion5_2(String question5_2) {
this.question5_2 = question5_2;
}
public String getQuestion5_3() {
return question5_3;
}
public void setQuestion5_3(String question5_3) {
this.question5_3 = question5_3;
}
public String getQuestion5_4() {
return question5_4;
}
public void setQuestion5_4(String question5_4) {
this.question5_4 = question5_4;
}
public String getQuestion5_5() {
return question5_5;
}
public void setQuestion5_5(String question5_5) {
this.question5_5 = question5_5;
}
public String getQuestion6_1() {
return question6_1;
}
public void setQuestion6_1(String question6_1) {
this.question6_1 = question6_1;
}
public String getQuestion6_2() {
return question6_2;
}
public void setQuestion6_2(String question6_2) {
this.question6_2 = question6_2;
}
public String getQuestion6_3() {
return question6_3;
}
public void setQuestion6_3(String question6_3) {
this.question6_3 = question6_3;
}
public String getQuestion6_4() {
return question6_4;
}
public void setQuestion6_4(String question6_4) {
this.question6_4 = question6_4;
}
public String getQuestion6_5() {
return question6_5;
}
public void setQuestion6_5(String question6_5) {
this.question6_5 = question6_5;
}
public String getQuestion7_1() {
return question7_1;
}
public void setQuestion7_1(String question7_1) {
this.question7_1 = question7_1;
}
public String getQuestion8_1() {
return question8_1;
}
public void setQuestion8_1(String question8_1) {
this.question8_1 = question8_1;
}
public String getQuestion8_2() {
return question8_2;
}
public void setQuestion8_2(String question8_2) {
this.question8_2 = question8_2;
}
public String getQuestion10_1() {
return question10_1;
}
public void setQuestion10_1(String question10_1) {
this.question10_1 = question10_1;
}
public String getQuestion10_2() {
return question10_2;
}
public void setQuestion10_2(String question10_2) {
this.question10_2 = question10_2;
}
public String getQuestion10_3() {
return question10_3;
}
public void setQuestion10_3(String question10_3) {
this.question10_3 = question10_3;
}
public String getQuestion10_4() {
return question10_4;
}
public void setQuestion10_4(String question10_4) {
this.question10_4 = question10_4;
}
public String getQuestion10_5() {
return question10_5;
}
public void setQuestion10_5(String question10_5) {
this.question10_5 = question10_5;
}
public String getQuestion10_6() {
return question10_6;
}
public void setQuestion10_6(String question10_6) {
this.question10_6 = question10_6;
}
public String getQuestion10_7() {
return question10_7;
}
public void setQuestion10_7(String question10_7) {
this.question10_7 = question10_7;
}
public String getQuestion10_8() {
return question10_8;
}
public void setQuestion10_8(String question10_8) {
this.question10_8 = question10_8;
}
public String getQuestion10_9() {
return question10_9;
}
public void setQuestion10_9(String question10_9) {
this.question10_9 = question10_9;
}
public String getQuestion10_10() {
return question10_10;
}
public void setQuestion10_10(String question10_10) {
this.question10_10 = question10_10;
}
public String getQuestion11_1() {
return question11_1;
}
public void setQuestion11_1(String question11_1) {
this.question11_1 = question11_1;
}
public String getQuestion11_2() {
return question11_2;
}
public void setQuestion11_2(String question11_2) {
this.question11_2 = question11_2;
}
public String getQuestion11_3() {
return question11_3;
}
public void setQuestion11_3(String question11_3) {
this.question11_3 = question11_3;
}
public String getQuestion11_4() {
return question11_4;
}
public void setQuestion11_4(String question11_4) {
this.question11_4 = question11_4;
}
public String getQuestion11_5() {
return question11_5;
}
public void setQuestion11_5(String question11_5) {
this.question11_5 = question11_5;
}
public String getQuestion11_6() {
return question11_6;
}
public void setQuestion11_6(String question11_6) {
this.question11_6 = question11_6;
}
public String getQuestion11_7() {
return question11_7;
}
public void setQuestion11_7(String question11_7) {
this.question11_7 = question11_7;
}
public String getQuestion11_8() {
return question11_8;
}
public void setQuestion11_8(String question11_8) {
this.question11_8 = question11_8;
}
public String getQuestion11_9() {
return question11_9;
}
public void setQuestion11_9(String question11_9) {
this.question11_9 = question11_9;
}
public String getQuestion11_10() {
return question11_10;
}
public void setQuestion11_10(String question11_10) {
this.question11_10 = question11_10;
}
private String question11_1 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question1");
private String question11_2 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question2");
private String question11_3 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question3");
private String question11_4 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question4");
private String question11_5 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question5");
private String question11_6 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question6");
private String question11_7 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question7");
private String question11_8 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question8");
private String question11_9 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question9");
private String question11_10 = StartScreen_MainActivity.MyAppsBundle.getString("Relationship_question10");
}
The way you are trying to call is wrong.
Please follow this:
Create the Object of the Answer class
> public class Thank_You_MainActivity extends AppCompatActivity {
Answer a;//Create an object
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thank__you__main);
a = new Ans();//define it
String aa = a.getGetQuestion1_1(); then use it anywhere
Hope this will help you
I am trying to pass Parcelable object from the A activity to B activity via intent:
Intent intent = new Intent (A.this, B.class);
intent.putExtra ("post", mypost); // where post implements Parcelable`
In B Activity I got the post object in this way:
Post myPost = getIntent().getParcelableExtra("post");
In B activity myPost object fields are mixed, e.g. I have postText and postDate fields in Post model, the values of this fields in B activity are mixed.
Why this can happen? My model class look likes the following:
public class Post implements Parcelable, Serializable {
private static final long serialVersionUID = 2L;
#SerializedName("author")
private User author;
#SerializedName("comments_count")
private String commentsCount;
#SerializedName("image")
private String imageToPost;
#SerializedName("parent_key")
private String parentKey;
#SerializedName("created_date")
private String postDate;
#SerializedName("id")
private String postId;
#SerializedName("text")
private String postText;
#SerializedName("title")
private String postTitle;
#SerializedName("shared_post_id")
private String sharedPostId;
#SerializedName("url")
private String urlToPost;
#SerializedName("video")
private String videoToPost;
public Post() {
}
public Post(Parcel in) {
author = (User) in.readValue(getClass().getClassLoader());
commentsCount = in.readString();
imageToPost = in.readString();
parentKey = in.readString();
postDate = in.readString();
postId = in.readString();
postText = in.readString();
postTitle = in.readString();
sharedPostId = in.readString();
urlToPost = in.readString();
videoToPost = in.readString();
}
public static final Creator<Post> CREATOR = new Creator<Post>() {
#Override
public Post createFromParcel(Parcel in) {
return new Post(in);
}
#Override
public Post[] newArray(int size) {
return new Post[size];
}
};
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getPostDate() {
return postDate;
}
public void setPostDate(String postDate) {
this.postDate = postDate;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostText() {
return postText;
}
public void setPostText(String postText) {
this.postText = postText;
}
public String getPostId() {
return postId;
}
public void setPostId(String postId) {
this.postId = postId;
}
public String getUrlToPost() {
return urlToPost;
}
public void setUrlToPost(String urlToPost) {
this.urlToPost = urlToPost;
}
public String getImageToPost() {
return imageToPost;
}
public void setImageToPost(String imageToPost) {
this.imageToPost = imageToPost;
}
public String getVideoToPost() {
return videoToPost;
}
public void setVideoToPost(String videoToPost) {
this.videoToPost = videoToPost;
}
public String getParentKey() {
return parentKey;
}
public void setParentKey(String parentKey) {
this.parentKey = parentKey;
}
public String getCommentsCount() {
return commentsCount;
}
public void setCommentsCount(String commentsCount) {
this.commentsCount = commentsCount;
}
public String getSharedPostId() {
return sharedPostId;
}
public void setSharedPostId(String sharedPostId) {
this.sharedPostId = sharedPostId;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(author);
dest.writeString(commentsCount);
dest.writeString(imageToPost);
dest.writeString(parentKey);
dest.writeString(postDate);
dest.writeString(postId);
dest.writeString(postText);
dest.writeString(postTitle);
dest.writeString(sharedPostId);
dest.writeString(urlToPost);
dest.writeString(videoToPost);
}
}
Add describeContents and writeToParcel.
Examples:
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(email);
dest.writeString(pass);
dest.writeFloat(amountPaid);
dest.writeString(url);
dest.writeInt(age);
}