How to parse nested keys and values using JsonReader? - java

I am learning Java and I'm trying to make a Fortnite stat tracking app. I'm using the Fortnite tracker API and JsonReader to read the keys and values that get returned. This works fine but the problem is the stats like 'kills' etc are nested and I'm not sure how to read those.
Can I read nested keys and values using JsonReader?
I tried JSONObject but I'm not entirely sure I was using it correctly so I didn't get very far.
{ "accountId": "c48bb072-f321-4572-9069-1c551d074949", "platformId": 1, "platformName": "xbox", "platformNameLong": "Xbox", "epicUserHandle": "playername", "stats": {
"p2": {
"trnRating": {
"label": "TRN Rating",
"field": "TRNRating",
"category": "Rating",
"valueInt": 1,
"value": "1",
"rank": 852977,
"percentile": 100.0,
"displayValue": "1"
},
"score": {
"label": "Score",
"field": "Score",
"category": "General",
"valueInt": 236074,
"value": "236074",
"rank": 6535595,
"percentile": 3.0,
"displayValue": "236,074"
}
Above is a sample of the information that I pulled so that you can see the structure
public class MainActivity extends AppCompatActivity {
TextView tv;
TextView tv2;
TextView tv3;
Button submit;
EditText tbplatform;
EditText tbhandle;
String TAG = "TESTRUN";
String id = "";
InputStreamReader responseBodyReader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvOne);
tv2 = (TextView) findViewById(R.id.tvTwo);
tv3 = (TextView) findViewById(R.id.tvThree);
submit = (Button) findViewById(R.id.btnSubmit);
tbplatform = (EditText) findViewById(R.id.tbPlatform);
tbhandle = (EditText) findViewById(R.id.tbHandle);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String platform = String.valueOf(tbplatform.getText());
final String username = String.valueOf(tbhandle.getText());
AsyncTask.execute(new Runnable() {
#Override
public void run() {
// All your networking logic
// should be here
// Create URL
URL githubEndpoint = null;
try {
githubEndpoint = new URL("https://api.fortnitetracker.com/v1/profile/" + platform+ "/" + username);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Create connection
HttpsURLConnection myConnection = null;
try {
myConnection =
(HttpsURLConnection) githubEndpoint.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
myConnection.setRequestProperty("TRN-Api-Key", "API_KEY_HERE");
try {
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
final String key = jsonReader.nextName(); // Fetch the next key
//Log.v(TAG, key);
if (key.equals("epicUserHandle") || key.equals("platformName") || key.equals("accountId")) { // Check if desired key
// Fetch the value as a String
final String value = jsonReader.nextString();
if (key.equals("epicUserHandle")) {
Log.v(TAG, "Gamertag: " + value);
}
if (key.equals("platformName")) {
Log.v(TAG, "Console: " + value);
}
if (key.equals("stats")) {
Log.v(TAG, "Kills: " + value);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//stuff that updates ui
if(key.equals("epicUserHandle")) {
tv.setText("Username: " + value);
}
if(key.equals("platformName")) {
tv2.setText("Platform: " +value);
}
if(key.equals("accountId")) {
tv3.setText("Account ID: " +value);
}
}
});
//Log.v(TAG, "" +value);
// Do something with the value
// ...
//break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
}

I think this may help you
You Need To Create Some Classes As Given Below
class Score implements Serializable {
private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;
public Score() {
this("", "", "", 0, "", 0, 0.0, "");
}
public Score(String label, String field,
String category, Integer valueInt,
String value, Integer rank,
Double percentile, String displayValue) {
this.label = label;
this.field = field;
this.category = category;
this.valueInt = valueInt;
this.value = value;
this.rank = rank;
this.percentile = percentile;
this.displayValue = displayValue;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getValueInt() {
return valueInt;
}
public void setValueInt(Integer valueInt) {
this.valueInt = valueInt;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Double getPercentile() {
return percentile;
}
public void setPercentile(Double percentile) {
this.percentile = percentile;
}
public String getDisplayValue() {
return displayValue;
}
public void setDisplayValue(String displayValue) {
this.displayValue = displayValue;
}
}
class TRNRating implements Serializable {
private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;
public TRNRating() {
this("", "", "", 0, "", 0, 0.0, "");
}
public TRNRating(String label, String field,
String category, Integer valueInt,
String value, Integer rank,
Double percentile, String displayValue) {
this.label = label;
this.field = field;
this.category = category;
this.valueInt = valueInt;
this.value = value;
this.rank = rank;
this.percentile = percentile;
this.displayValue = displayValue;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getValueInt() {
return valueInt;
}
public void setValueInt(Integer valueInt) {
this.valueInt = valueInt;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Double getPercentile() {
return percentile;
}
public void setPercentile(Double percentile) {
this.percentile = percentile;
}
public String getDisplayValue() {
return displayValue;
}
public void setDisplayValue(String displayValue) {
this.displayValue = displayValue;
}
}
class P2 implements Serializable {
private TRNRating trnRating;
private Score score;
public P2() {
this(new TRNRating(), new Score());
}
public P2(TRNRating trnRating, Score score) {
this.trnRating = trnRating;
this.score = score;
}
public TRNRating getTrnRating() {
return trnRating;
}
public void setTrnRating(TRNRating trnRating) {
this.trnRating = trnRating;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
}
class Stats implements Serializable {
private P2 p2;
public Stats() {
this(new P2());
}
public Stats(P2 p2) {
this.p2 = p2;
}
}
//You Need To Change Name Of This Class
class Response implements Serializable {
private String accountId;
private Integer platformId;
private String platformName;
private String platformNameLong;
private String epicUserHandle;
private Stats stats;
public Response() {
this("", 0, "", "", "", new Stats());
}
public Response(String accountId, Integer platformId,
String platformName, String platformNameLong,
String epicUserHandle, Stats stats) {
this.accountId = accountId;
this.platformId = platformId;
this.platformName = platformName;
this.platformNameLong = platformNameLong;
this.epicUserHandle = epicUserHandle;
this.stats = stats;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public Integer getPlatformId() {
return platformId;
}
public void setPlatformId(Integer platformId) {
this.platformId = platformId;
}
public String getPlatformName() {
return platformName;
}
public void setPlatformName(String platformName) {
this.platformName = platformName;
}
public String getPlatformNameLong() {
return platformNameLong;
}
public void setPlatformNameLong(String platformNameLong) {
this.platformNameLong = platformNameLong;
}
public String getEpicUserHandle() {
return epicUserHandle;
}
public void setEpicUserHandle(String epicUserHandle) {
this.epicUserHandle = epicUserHandle;
}
public Stats getStats() {
return stats;
}
public void setStats(Stats stats) {
this.stats = stats;
}
}
If your response is same as explained in question. Then this will work.
//In your code after status check you need to do like this
if (myConnection.getResopnseCode() == 200) {
BufferedReader br=new BufferedReader(responseBodyReader);
String read = null, entireResponse = "";
StringBuffer sb = new StringBuffer();
while((read = br.readLine()) != null) {
sb.append(read);
}
entireResponse = sb.toString();
//You need to change name of response class
Response response = new Gson().fromJson(entireResponse , Response.class);
}

Related

How to read an array from object using Retrofit and populate a recyclerview

I'm trying to read an array which is in an object (json). I've used retrofit before but I can't get to the array. This are the models:
Negocio.class
public class Negocio {
#SerializedName("data")
#Expose
private List<Datum> data = null;
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
ImagenNegocio.class
public class ImagenNegocio {
#SerializedName("idImagenNegocio")
#Expose
private Integer idImagenNegocio;
#SerializedName("url")
#Expose
private String url;
#SerializedName("flgPortada")
#Expose
private Boolean flgPortada;
#SerializedName("flgLogo")
#Expose
private Boolean flgLogo;
#SerializedName("idNegocio")
#Expose
private Integer idNegocio;
public Integer getIdImagenNegocio() {
return idImagenNegocio;
}
public void setIdImagenNegocio(Integer idImagenNegocio) {
this.idImagenNegocio = idImagenNegocio;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getFlgPortada() {
return flgPortada;
}
public void setFlgPortada(Boolean flgPortada) {
this.flgPortada = flgPortada;
}
public Boolean getFlgLogo() {
return flgLogo;
}
public void setFlgLogo(Boolean flgLogo) {
this.flgLogo = flgLogo;
}
public Integer getIdNegocio() {
return idNegocio;
}
public void setIdNegocio(Integer idNegocio) {
this.idNegocio = idNegocio;
}
}
Datum.class
public class Datum {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("nombre")
#Expose
private String nombre;
#SerializedName("ruc")
#Expose
private String ruc;
#SerializedName("razonSocial")
#Expose
private String razonSocial;
#SerializedName("descripcion")
#Expose
private String descripcion;
#SerializedName("tiempoEntregaMinimo")
#Expose
private Integer tiempoEntregaMinimo;
#SerializedName("tiempoEntregaMaximo")
#Expose
private Integer tiempoEntregaMaximo;
#SerializedName("flgDeliveryPropio")
#Expose
private Boolean flgDeliveryPropio;
#SerializedName("flgAplicaCostoEnvio")
#Expose
private Boolean flgAplicaCostoEnvio;
#SerializedName("flgPagoOnline")
#Expose
private Boolean flgPagoOnline;
#SerializedName("flgPagoEfectivo")
#Expose
private Boolean flgPagoEfectivo;
#SerializedName("flgRecomendado")
#Expose
private Boolean flgRecomendado;
#SerializedName("flgDisponible")
#Expose
private Boolean flgDisponible;
#SerializedName("nroCuenta")
#Expose
private String nroCuenta;
#SerializedName("idRubro")
#Expose
private Integer idRubro;
#SerializedName("idBanco")
#Expose
private Integer idBanco;
#SerializedName("idConfiguracionPedido")
#Expose
private Integer idConfiguracionPedido;
#SerializedName("idUsuario")
#Expose
private Integer idUsuario;
#SerializedName("imagenNegocios")
#Expose
private List<ImagenNegocio> imagenNegocios = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRuc() {
return ruc;
}
public void setRuc(String ruc) {
this.ruc = ruc;
}
public String getRazonSocial() {
return razonSocial;
}
public void setRazonSocial(String razonSocial) {
this.razonSocial = razonSocial;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Integer getTiempoEntregaMinimo() {
return tiempoEntregaMinimo;
}
public void setTiempoEntregaMinimo(Integer tiempoEntregaMinimo) {
this.tiempoEntregaMinimo = tiempoEntregaMinimo;
}
public Integer getTiempoEntregaMaximo() {
return tiempoEntregaMaximo;
}
public void setTiempoEntregaMaximo(Integer tiempoEntregaMaximo) {
this.tiempoEntregaMaximo = tiempoEntregaMaximo;
}
public Boolean getFlgDeliveryPropio() {
return flgDeliveryPropio;
}
public void setFlgDeliveryPropio(Boolean flgDeliveryPropio) {
this.flgDeliveryPropio = flgDeliveryPropio;
}
public Boolean getFlgAplicaCostoEnvio() {
return flgAplicaCostoEnvio;
}
public void setFlgAplicaCostoEnvio(Boolean flgAplicaCostoEnvio) {
this.flgAplicaCostoEnvio = flgAplicaCostoEnvio;
}
public Boolean getFlgPagoOnline() {
return flgPagoOnline;
}
public void setFlgPagoOnline(Boolean flgPagoOnline) {
this.flgPagoOnline = flgPagoOnline;
}
public Boolean getFlgPagoEfectivo() {
return flgPagoEfectivo;
}
public void setFlgPagoEfectivo(Boolean flgPagoEfectivo) {
this.flgPagoEfectivo = flgPagoEfectivo;
}
public Boolean getFlgRecomendado() {
return flgRecomendado;
}
public void setFlgRecomendado(Boolean flgRecomendado) {
this.flgRecomendado = flgRecomendado;
}
public Boolean getFlgDisponible() {
return flgDisponible;
}
public void setFlgDisponible(Boolean flgDisponible) {
this.flgDisponible = flgDisponible;
}
public String getNroCuenta() {
return nroCuenta;
}
public void setNroCuenta(String nroCuenta) {
this.nroCuenta = nroCuenta;
}
public Integer getIdRubro() {
return idRubro;
}
public void setIdRubro(Integer idRubro) {
this.idRubro = idRubro;
}
public Integer getIdBanco() {
return idBanco;
}
public void setIdBanco(Integer idBanco) {
this.idBanco = idBanco;
}
public Integer getIdConfiguracionPedido() {
return idConfiguracionPedido;
}
public void setIdConfiguracionPedido(Integer idConfiguracionPedido) {
this.idConfiguracionPedido = idConfiguracionPedido;
}
public Integer getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public List<ImagenNegocio> getImagenNegocios() {
return imagenNegocios;
}
public void setImagenNegocios(List<ImagenNegocio> imagenNegocios) {
this.imagenNegocios = imagenNegocios;
}
}
And this is the what I get from the url:
{
"data": [
{
"id": 1,
"nombre": "Huellitas",
"ruc": "20123456789",
"razonSocial": "Huellitas SAC",
"descripcion": "Tienda de productos para mascotas",
"tiempoEntregaMinimo": 15,
"tiempoEntregaMaximo": 30,
"flgDeliveryPropio": false,
"flgAplicaCostoEnvio": true,
"flgPagoOnline": true,
"flgPagoEfectivo": true,
"flgRecomendado": false,
"flgDisponible": true,
"nroCuenta": "112548975",
"idRubro": 1,
"idBanco": 1,
"idConfiguracionPedido": 1,
"idUsuario": 2,
"imagenNegocios": [
{
"idImagenNegocio": 6,
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQyktAFVOzfKb29j7EUrRml2ZzMjpVbKQFJmgY3h7tK35wOWbQBUc6R1UVW2axs00puEg0&usqp=CAU",
"flgPortada": false,
"flgLogo": true,
"idNegocio": 1
},
{
"idImagenNegocio": 7,
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSC_3Dy_NlxlPDwC5LkFyLvvM1oxccl1Vvl9Q&usqp=CAU",
"flgPortada": true,
"flgLogo": false,
"idNegocio": 1
}
]
},
{
"id": 2,
"nombre": "Ikiitu",
"ruc": "20787945613",
"razonSocial": "Ikiitu EIRL",
"descripcion": "Restaurante amazonico e internacional",
"tiempoEntregaMinimo": 20,
"tiempoEntregaMaximo": 60,
"flgDeliveryPropio": true,
"flgAplicaCostoEnvio": true,
"flgPagoOnline": true,
"flgPagoEfectivo": false,
"flgRecomendado": false,
"flgDisponible": true,
"nroCuenta": "117894565",
"idRubro": 1,
"idBanco": 1,
"idConfiguracionPedido": 1,
"idUsuario": 3,
"imagenNegocios": [
{
"idImagenNegocio": 3,
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEMVyZ0EEg6v80LnnuZJwaL7a239EOpnfH6lKOF5TFQONEStJVk5-L9X2xME9OHjGeOts&usqp=CAU",
"flgPortada": false,
"flgLogo": true,
"idNegocio": 2
},
{
"idImagenNegocio": 4,
"url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQN5BnM6QwIqX3ruP1svQjyjoBsWPEFMxWlqA&usqp=CAU",
"flgPortada": true,
"flgLogo": false,
"idNegocio": 2
}
]
}
]
}
And this is my UserService.java
public interface UserService {
#GET("Negocio/")
Call<List<Datum>> Negocio();
}
What I'm trying to do is to populate this into an recyclerview. I've created the adapter
ListaNegocioAdapter.java
public class ListaNegocioAdapter extends RecyclerView.Adapter<ListaNegocioAdapter.ViewHolder> {
private Context mcontext;
private List<Datum> mNegocioList;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener (OnItemClickListener listener){
mListener = listener;
}
public ListaNegocioAdapter (Context mcontext, List<Datum> mNegocioList){
this.mcontext = mcontext;
this.mNegocioList = mNegocioList;
}
#NonNull
#Override
public ListaNegocioAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mcontext).inflate(R.layout.grd_item_list_negocio,viewGroup,false);
return new ListaNegocioAdapter.ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ListaNegocioAdapter.ViewHolder viewHolder, int position) {
Datum currentItem = mNegocioList.get(position);
viewHolder.nombreNegocio.setText(currentItem.getNombre());
//Picasso.get().load(currentItem.getImagenNegocios()).into(viewHolder.logoNegocio);
}
#Override
public int getItemCount() {
return mNegocioList.size();
}
public void adicinarLista (List<Datum> listaNegocios){
this.mNegocioList = listaNegocios;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView nombreNegocio;
public ImageView logoNegocio;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nombreNegocio = itemView.findViewById(R.id.txt_nombreNegocio);
logoNegocio = itemView.findViewById(R.id.img_negocioLogo);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener!=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
});
}
}
}
But I can't get into the ImagenNegocio to retrieve the images url. Can somebody help me, please?

How can use two method from two different models?

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.

Parcelable of Custom Classes

I am currently trying to pass an ArrayList of the class event into another activity as follows.events is an ArrayList of the Event class.
Intent i = new Intent(ViewEvents.this, UserFeed.class);
i.putParcelableArrayListExtra("events",events);
startActivity(i);
I am then retrieving the data as follows:
Intent i = getIntent();
ArrayList<Event> events = i.getParcelableArrayListExtra("events");
My Issue is that I get an Umarshing unknown type code 32 at offset 5788. I am not too sure how to fix this or why this is occurring. I have posted all the code for all three classes down below.Any help would be appreciated to solve this issue.
public class Event implements Parcelable {
public String tvEventName;
public String tvEventInfo;
public String tvDescription;
public String ivEventImage;
public String organizerName;
public String eventId;
public String veneuId;
public String organizerId;
public Venue venue;
public Organizer organizer;
public Event(String tvEventName, String tvEventInfo, String tvDescription, String ivEventImage, String eventId, String veneuId,Venue venue,Organizer organizer) {
this.tvEventName = tvEventName;
this.tvEventInfo = tvEventInfo;
this.tvDescription = tvDescription;
this.ivEventImage = ivEventImage;
this.eventId = eventId;
this.veneuId = veneuId;
}
public Event() {
}
protected Event(Parcel in) {
tvEventName = in.readString();
tvEventInfo = in.readString();
tvDescription = in.readString();
ivEventImage = in.readString();
organizerName = in.readString();
eventId = in.readString();
veneuId = in.readString();
organizerId = in.readString();
}
public static final Creator<Event> CREATOR = new Creator<Event>() {
#Override
public Event createFromParcel(Parcel in) {
return new Event(in);
}
#Override
public Event[] newArray(int size) {
return new Event[size];
}
};
public static Event fromJSON(JSONObject jsonObject)throws JSONException {
Event event = new Event();
//Getting the name of the event
JSONObject nameEvent = jsonObject.getJSONObject("name");
event.tvEventName = nameEvent.getString("text");
//Getting the description for the event Time and location only
JSONObject eventInfo = jsonObject.getJSONObject("start");
event.tvEventInfo = eventInfo.getString("utc");
SimpleDateFormat existingUTCFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat requiredFormat = new SimpleDateFormat("MM-dd hh:mm a");
event.eventId = jsonObject.getString("id");
try{
Date getDate = existingUTCFormat.parse(event.tvEventInfo);
String mydate = requiredFormat.format(getDate);
event.tvEventInfo = mydate;
}
catch(ParseException e){
e.printStackTrace();
}
//Getting the description of the event
JSONObject eventDescription = jsonObject.getJSONObject("description");
event.tvDescription = eventDescription.getString("text");
//Getting a thumbnail of the image for futer use.
try{
jsonObject.getJSONObject("logo");
JSONObject logo = jsonObject.getJSONObject("logo");
JSONObject original= logo.getJSONObject("original");
event.ivEventImage = original.getString("url");
Log.i("Ingo",event.ivEventImage);
}
catch (Exception exception){
event.ivEventImage ="#drawable/tree";
}
event.veneuId = jsonObject.getString("venue_id");
event.organizerId = jsonObject.getString("organizer_id");
return event;
}
public Organizer getOrganizer() {
return organizer;
}
public void setOrganizer(Organizer organizer) {
this.organizer = organizer;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getTvEventName() {
return tvEventName;
}
public void setTvEventName(String tvEventName) {
this.tvEventName = tvEventName;
}
public String getTvEventInfo() {
return tvEventInfo;
}
public void setTvEventInfo(String tvEventInfo) {
this.tvEventInfo = tvEventInfo;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public String getTvDescription() {
return tvDescription;
}
public void setTvDescription(String tvDescription) {
this.tvDescription = tvDescription;
}
public String getIvEventImage() {
return ivEventImage;
}
public void setIvEventImage(String ivEventImage) {
this.ivEventImage = ivEventImage;
}
public String getVeneuId() {
return veneuId;
}
public void setVeneuId(String veneuId) {
this.veneuId = veneuId;
}
public String getOrganizerName() {
return organizerName;
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public void setOrganizerName(String organizerName) {
this.organizerName = organizerName;
}
#Override
public int describeContents() {
return 0;
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tvEventName);
dest.writeString(tvEventInfo);
dest.writeString(tvDescription);
dest.writeString(ivEventImage);
dest.writeString(organizerName);
dest.writeString(eventId);
dest.writeString(veneuId);
dest.writeString(organizerId);
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
}
}
CLASS 2
public class Venue implements Parcelable {
public String address;
public String city;
public String region;
public String postalCode;
public String country;
public String latitude;
public String longitude;
public String simpleAddress;
public Venue() {
}
public Venue(String address, String city, String region, String postalCode, String country, String latitude, String longitude, String simpleAddress) {
this.address = address;
this.city = city;
this.region = region;
this.postalCode = postalCode;
this.country = country;
this.latitude = latitude;
this.longitude = longitude;
this.simpleAddress = simpleAddress;
}
protected Venue(Parcel in) {
address = in.readString();
city = in.readString();
region = in.readString();
postalCode = in.readString();
country = in.readString();
latitude = in.readString();
longitude = in.readString();
simpleAddress = in.readString();
}
public static final Creator<Venue> CREATOR = new Creator<Venue>() {
#Override
public Venue createFromParcel(Parcel in) {
return new Venue(in);
}
#Override
public Venue[] newArray(int size) {
return new Venue[size];
}
};
public static Venue fromJSON(JSONObject jsonObject)throws JSONException {
Venue venue = new Venue();
if(jsonObject.getString("address_1") == null){
if(jsonObject.getString("address_2") == null)
venue.address = "No Location Available";
else
venue.address = jsonObject.getString("address_2");
}
else
venue.address = jsonObject.getString("address_1");
venue.city = jsonObject.getString("city");
venue.region = jsonObject.getString("region");
venue.postalCode = jsonObject.getString("postal_code");
venue.country = jsonObject.getString("country");
venue.latitude = jsonObject.getString("latitude");
venue.longitude = jsonObject.getString("longitude");
venue.simpleAddress =venue.address +","+ venue.city +","+ venue.country;
Log.i("SIMPLE", venue.simpleAddress);
return venue;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
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 getSimpleAddress() {
return simpleAddress;
}
public void setSimpleAddress(String simpleAddress) {
this.simpleAddress = simpleAddress;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(address);
dest.writeString(city);
dest.writeString(region);
dest.writeString(postalCode);
dest.writeString(country);
dest.writeString(latitude);
dest.writeString(longitude);
dest.writeString(simpleAddress);
}
}
CLASS 3
public class Organizer implements Parcelable{
public String description;
public String organizerId;
public String numePastEvents;
public String numFutureEvents;
public String website;
public String facebookUsername;
public String twitter;
public String name;
public Organizer() {
}
protected Organizer(Parcel in) {
description = in.readString();
organizerId = in.readString();
numePastEvents = in.readString();
numFutureEvents = in.readString();
website = in.readString();
facebookUsername = in.readString();
twitter = in.readString();
name = in.readString();
}
public static final Creator<Organizer> CREATOR = new Creator<Organizer>() {
#Override
public Organizer createFromParcel(Parcel in) {
return new Organizer(in);
}
#Override
public Organizer[] newArray(int size) {
return new Organizer[size];
}
};
public static Organizer fromJson(JSONObject jsonObject){
Organizer organizer = new Organizer();
try {
organizer.description = jsonObject.getJSONObject("description").getString("text");
} catch (JSONException e) {
organizer.description ="NA";
e.printStackTrace();
}
try {
organizer.organizerId = jsonObject.getString("id");
} catch (JSONException e) {
organizer.organizerId = "NA";
e.printStackTrace();
}
try {
organizer.numePastEvents = jsonObject.getString("num_past_events");
} catch (JSONException e) {
organizer.numePastEvents = "Na";
e.printStackTrace();
}
try {
organizer.numFutureEvents = jsonObject.getString("num_future_events");
} catch (JSONException e) {
organizer.numFutureEvents = "NA";
e.printStackTrace();
}
try {
organizer.website = jsonObject.getString("website");
} catch (JSONException e) {
Log.i("Error",e.getMessage());
organizer.website = "NA";
e.printStackTrace();
}
try {
organizer.facebookUsername = jsonObject.getString("facebook");
} catch (JSONException e) {
organizer.facebookUsername = "NA";
e.printStackTrace();
}
try {
organizer.name = jsonObject.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
organizer.twitter = jsonObject.getString("twitter");
} catch (JSONException e) {
e.printStackTrace();
}
return organizer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrganizerId() {
return organizerId;
}
public void setOrganizerId(String organizerId) {
this.organizerId = organizerId;
}
public String getNumePastEvents() {
return numePastEvents;
}
public void setNumePastEvents(String numePastEvents) {
this.numePastEvents = numePastEvents;
}
public String getNumFutureEvents() {
return numFutureEvents;
}
public void setNumFutureEvents(String numFutureEvents) {
this.numFutureEvents = numFutureEvents;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getFacebookUsername() {
return facebookUsername;
}
public void setFacebookUsername(String facebookUsername) {
this.facebookUsername = facebookUsername;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(description);
dest.writeString(organizerId);
dest.writeString(numePastEvents);
dest.writeString(numFutureEvents);
dest.writeString(website);
dest.writeString(facebookUsername);
dest.writeString(twitter);
dest.writeString(name);
}
When implementing the Parcelable interface, it is an absolute requirement that your reads and writes exactly match each other. In your case, this is your Event(Parcel) constructor and void writeToParcel().
However, your writeToParcel() implementation includes two writes that your constructor does not read.
dest.writeParcelable( this.venue,flags);
dest.writeParcelable(this.organizer,flags);
You have to either remove these or add matching reads to your constructor.
venue = in.readParcelable(Venue.class.getClassLoader());
organizer = in.readParcelable(Organizer.class.getClassLoader());

Getting data from JSON in android mobile gives fatalexception main

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.

Put Parcelable via intent

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

Categories