Add data to Arraylist Object from fragment - android

I need a guide to add data from my add button of my fragment and show the list in another fragment..Everything in memory
This is my entity
public class Incidencia implements Parcelable {
private Integer id_incidencia;
private String FechaRegistroIncidencia;
private String NomRegistro;
private String FechaRegistro;;
private String HoraRegistro;
private int CodEstacion;
private String NomEstacion;
private int CodEquipo;
private String NomEquipo;
private String TipoFalla;
private int AtoramientoMoneda;
private int AtoramientoBillete;
private String HoraLlegadaEstacion;
private String Estado;
private String Observaciones;
private String FechaSolucion;
private String HoraSolucion;
public Integer getId_incidencia() {
return id_incidencia;
}
public void setId_incidencia(Integer id_incidencia) {
this.id_incidencia = id_incidencia;
}
public String getFechaRegistroIncidencia() {
return FechaRegistroIncidencia;
}
public void setFechaRegistroIncidencia(String fechaRegistroIncidencia) {
FechaRegistroIncidencia = fechaRegistroIncidencia;
}
public String getNomRegistro() {
return NomRegistro;
}
public void setNomRegistro(String nomRegistro) {
NomRegistro = nomRegistro;
}
public String getFechaRegistro() {
return FechaRegistro;
}
public void setFechaRegistro(String fechaRegistro) {
FechaRegistro = fechaRegistro;
}
public String getHoraRegistro() {
return HoraRegistro;
}
public void setHoraRegistro(String horaRegistro) {
HoraRegistro = horaRegistro;
}
public Integer getCodEstacion() {
return CodEstacion;
}
public void setCodEstacion(Integer codEstacion) {
CodEstacion = codEstacion;
}
public String getNomEstacion() {
return NomEstacion;
}
public void setNomEstacion(String nomEstacion) {
NomEstacion = nomEstacion;
}
public Integer getCodEquipo() {
return CodEquipo;
}
public void setCodEquipo(Integer codEquipo) {
CodEquipo = codEquipo;
}
public String getNomEquipo() {
return NomEquipo;
}
public void setNomEquipo(String nomEquipo) {
NomEquipo = nomEquipo;
}
public String getTipoFalla() {
return TipoFalla;
}
public void setTipoFalla(String tipoFalla) {
TipoFalla = tipoFalla;
}
public Integer getAtoramientoMoneda() {
return AtoramientoMoneda;
}
public void setAtoramientoMoneda(Integer atoramientoMoneda) {
AtoramientoMoneda = atoramientoMoneda;
}
public Integer getAtoramientoBillete() {
return AtoramientoBillete;
}
public void setAtoramientoBillete(Integer atoramientoBillete) {
AtoramientoBillete = atoramientoBillete;
}
public String getHoraLlegadaEstacion() {
return HoraLlegadaEstacion;
}
public void setHoraLlegadaEstacion(String horaLlegadaEstacion) {
HoraLlegadaEstacion = horaLlegadaEstacion;
}
public String getEstado() {
return Estado;
}
public void setEstado(String estado) {
Estado = estado;
}
public String getObservaciones() {
return Observaciones;
}
public void setObservaciones(String observaciones) {
Observaciones = observaciones;
}
public String getFechaSolucion() {
return FechaSolucion;
}
public void setFechaSolucion(String fechaSolucion) {
FechaSolucion = fechaSolucion;
}
public String getHoraSolucion() {
return HoraSolucion;
}
public void setHoraSolucion(String horaSolucion) {
HoraSolucion = horaSolucion;
}
public Incidencia(){}
protected Incidencia(Parcel in){
this.id_incidencia=in.readInt();;
this.FechaRegistroIncidencia=in.readString();
this.NomRegistro=in.readString();
this.FechaRegistro=in.readString();
this.HoraRegistro=in.readString();
this.CodEstacion=in.readInt();
this.NomEstacion=in.readString();
this.CodEquipo=in.readInt();
this.NomEquipo=in.readString();
this.TipoFalla=in.readString();
this.AtoramientoMoneda=in.readInt();
this.AtoramientoBillete=in.readInt();
this.HoraLlegadaEstacion=in.readString();
this.Estado=in.readString();
this.Observaciones=in.readString();
this.FechaSolucion=in.readString();
this.HoraSolucion=in.readString();
}
public static final Parcelable.Creator<Incidencia> CREATOR = new Parcelable.Creator<Incidencia>() {
#Override
public Incidencia createFromParcel(Parcel source) {
return new Incidencia(source);
}
#Override
public Incidencia[] newArray(int size) {
return new Incidencia[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.FechaRegistro);
dest.writeString(this.HoraRegistro);
dest.writeString(this.TipoFalla);
dest.writeString(this.FechaSolucion);
dest.writeString(this.HoraSolucion);
dest.writeString(this.NomEstacion);
}
}
This is my adapter
public class ListaIncidenciasTroncalAdapter extends RecyclerView.Adapter<ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder>
{
private List<Incidencia> mLstIncidencia = new ArrayList<>();
private OnItemClickListener listener;
public void add(Incidencia incidencia){
mLstIncidencia.add(incidencia);
notifyItemInserted(mLstIncidencia.size()-1);
}
#Override
public ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listaincidencias_item,parent,false);
ListaIncidenciasTroncalAdapterViewHolder mlistaIncidenciasTroncalAdapterViewHolder = new ListaIncidenciasTroncalAdapterViewHolder(view);
return mlistaIncidenciasTroncalAdapterViewHolder;
}
#Override
public void onBindViewHolder(ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder holder, final int position) {
final Incidencia incidencia= mLstIncidencia.get(position);
holder.tv_FechaRegistro.setText("Registro: "+incidencia.getFechaRegistro()+" - "+incidencia.getHoraRegistro());
holder.tv_Falla.setText(incidencia.getTipoFalla());
holder.tv_Estacion.setText(incidencia.getNomEstacion());
holder.tv_FechaSolucion.setText("Solucion: "+incidencia.getFechaSolucion()+" - "+incidencia.getHoraSolucion());
}
#Override
public int getItemCount() {
return mLstIncidencia.size();
}
static class ListaIncidenciasTroncalAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private OnItemClickListener listener;
TextView tv_FechaRegistro, tv_Falla, tv_Estacion,tv_FechaSolucion;
LinearLayout linearLayout;
public DetalleIncidencia detalleincidencia;
public ListaIncidenciasTroncalAdapterViewHolder(View itemView) {
super(itemView);
tv_FechaRegistro= (TextView) itemView.findViewById(R.id.tvRegistro);
tv_Falla= (TextView) itemView.findViewById(R.id.tvFalla);
tv_Estacion= (TextView) itemView.findViewById(R.id.tvEstacion);
tv_FechaSolucion= (TextView) itemView.findViewById(R.id.tvSolucion);
final Context context = itemView.getContext();
// detalleincidencia=(DetalleIncidencia) itemView.findViewById(R.id.)
linearLayout=(LinearLayout) itemView.findViewById(R.id.linearItem);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
public interface OnItemClickListener{
public void onItemClick(String textName, String textViewBrief);
}
}
I want to add an Incidencia Object from this fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate ingresoincidenciastroncal and setup Views.
*/
final View x = inflater.inflate(R.layout.ingresoincidenciastroncal,null);
context = x.getContext();
//BOTON DE AGREGAR INCIDENCIA
botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro(mDateDisplay.getText().toString());
incidencia.setHoraSolucion(mTimeDisplay.getText().toString());
Toast toast = Toast.makeText(getContext(), "Registrado", Toast.LENGTH_SHORT);
toast.show();
}
});
return x;
}
And I want to see the list in this fragment
public class ListaIncidenciasTroncalFragment extends Fragment {
Context context;
GestureDetector detector;
private RecyclerView rvListaIncidencias;
private ListaIncidenciasTroncalAdapter mlistaIncidenciasTroncalAdapter;
public ListaIncidenciasTroncalFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View x = inflater.inflate(R.layout.listaincidenciastroncalfragment,null);
context = x.getContext();
detector = new GestureDetector(getActivity(), new RecyclerViewOnGestureListener());
rvListaIncidencias=(RecyclerView)x.findViewById(R.id.rv_listaIncidenciasTroncal);
rvListaIncidencias.setLayoutManager(new LinearLayoutManager(getContext()));
mlistaIncidenciasTroncalAdapter = new ListaIncidenciasTroncalAdapter();
rvListaIncidencias.setAdapter(mlistaIncidenciasTroncalAdapter);
//I ADD THIS ONE FOR TEST AND ITS SUCCESFULL BUT I DONT KNOW HOW TO ADD IT BY THE BUTTON IN ANOTHER FRAGMENT
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro("06/06/2017");
incidencia.setHoraRegistro("10:30");
incidencia.setTipoFalla("Atasco Moneda");
incidencia.setNomEstacion("Javier Prado");
incidencia.setFechaSolucion("07/06/2017");
incidencia.setHoraSolucion("9:20");
mlistaIncidenciasTroncalAdapter.add(incidencia);
return x;
}

In your first fragment, define an interface which would pass your Incidencia object to the host activity. The interface method is called in your button's onClick():
public class YourFirstFragment extends Fragment {
private OnButtonClickedListener mListener;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
mListener.onButtonClicked(incidencia);
}
});
}
public interface OnButtonClickedListener {
void onButtonClicked(Incidencia incidencia);
}
}
Then, in your activity, implement this interface. The overridden method will also bundle the object and pass to your next fragment as the fragment argument:
public class YourActivity implements YourFirstFragment.OnButtonClicked {
.
.
.
#Override
public void onButtonClicked(Incidencia incidencia){
ListaIncidenciasTroncalFragment fragment = new ListaIncidenciasTroncalFragment();
Bundle args = new Bundle();
args.putParcelable("yourKey", incindencia);
fragement.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.yourFragmentContainer, fragment).commit();
}
}
Finally, in your second fragment, extract the bundle or arguments like so and use it however you want:
Bundle args = getArguments();
Incidencia incidencia = args.getParcelable("yourKey");

Related

How to pass an Object from one fragment to other fragment

I want to pass my total entity (Incidencia) who is created in One fragment and pass it to another fragment who will show a list of each entity added before. Both fragments are inside of one Activity. Im using recyclerview to list the entities and this entity implements parcelable.
This is the main activity who contain both fragments
public class MainActivity extends ActionBarActivity implements IngresoIncidenciaTroncalFragment.OnButtonClickedListener{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar mitoolbar = (Toolbar) findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
setSupportActionBar(mitoolbar);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_ingresoIncidencia) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new IngresoIncidenciaTroncalFragment()).commit();
mitoolbar.setTitle("Ingreso Incidencia Troncal");
}
else if (menuItem.getItemId() == R.id.nav_item_listarIncidencia) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new ListaIncidenciasTroncalFragment()).commit();
mitoolbar.setTitle("Lista Incidencias Troncal");
}
return false;
}
});
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
//THIS IS THE METHOD WHO DOESNT WORK
//WHAT CONTAINER DO I HAVE TO WRITE? THE ACTIVITY CONTAINER? OR FRAGMENT ONE OR TWO CONTAINERS?
#Override
public void onButtonClicked(Incidencia incidencia){
IngresoIncidenciaTroncalFragment fragment = new IngresoIncidenciaTroncalFragment();
Bundle args = new Bundle();
args.putParcelable("incident", incidencia);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.containerView, fragment).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
This is the fragment who will add the entity
public class IngresoIncidenciaTroncalFragment extends Fragment implements
FechaDialog.DatePickerDialogFragmentEvents,HoraDialog.TimePickerDialogFragmentEvents ,FechaLlegadaDialog.DateLlegadaPickerDialogFragmentEvents{
private TextView mDateDisplay;
private TextView mTimeDisplay;
private Button botonAgregaIncidencia;
Context context;
private OnButtonClickedListener mListener;
private Spinner spinnerFallas;
public interface OnButtonClickedListener {
void onButtonClicked(Incidencia incidencia);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate ingresoincidenciastroncal and setup Views.
*/
final View x = inflater.inflate(R.layout.ingresoincidenciastroncal,null);
context = x.getContext();
mHoraLLegadaEstacion=(TextView)x.findViewById(R.id.tvHoraLLegadaEstacion);
mObservaciones=(TextView)x.findViewById(R.id.tvObservaciones);
mFechaSolucion=(TextView)x.findViewById(R.id.tvFechaSolucion);
mHoraSolucion=(TextView)x.findViewById(R.id.tvHoraSolucion);
//ADD ENTITY BUTTON
botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//CREATING NEW ENTITY(Incidencia)
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro(mDateDisplay.toString());
incidencia.setHoraSolucion(mTimeDisplay.toString());
incidencia.setTipoFalla(spinnerFallas.getPrompt().toString());
//NEW ENTITY AS PAREMETER
mListener.onButtonClicked(incidencia);
}
});
return x;
}
}
This is the fragment who will show the list of entities
public class ListaIncidenciasTroncalFragment extends Fragment {
Context context;
GestureDetector detector;
private RecyclerView rvListaIncidencias;
private ListaIncidenciasTroncalAdapter mlistaIncidenciasTroncalAdapter;
public ListaIncidenciasTroncalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View x = inflater.inflate(R.layout.listaincidenciastroncalfragment,null);
context = x.getContext();
detector = new GestureDetector(getActivity(), new RecyclerViewOnGestureListener());
rvListaIncidencias=(RecyclerView)x.findViewById(R.id.rv_listaIncidenciasTroncal);
rvListaIncidencias.setLayoutManager(new LinearLayoutManager(getContext()));
mlistaIncidenciasTroncalAdapter = new ListaIncidenciasTroncalAdapter();
rvListaIncidencias.setAdapter(mlistaIncidenciasTroncalAdapter);
//HERE I SUPPOSE TO GET OBJECT CREATED FROM FRAGMENTONE
Bundle args = getArguments();
Incidencia incidencia = args.getParcelable("incident");
mlistaIncidenciasTroncalAdapter.add(incidencia);
return x;
}
}
This is the recyclerview adapter
public class ListaIncidenciasTroncalAdapter extends RecyclerView.Adapter<ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder>
{
private List<Incidencia> mLstIncidencia = new ArrayList<>();
//private OnItemClickListener listener;
public void add(Incidencia incidencia){
mLstIncidencia.add(incidencia);
notifyItemInserted(mLstIncidencia.size()-1);
}
#Override
public ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listaincidencias_item,parent,false);
ListaIncidenciasTroncalAdapterViewHolder mlistaIncidenciasTroncalAdapterViewHolder = new ListaIncidenciasTroncalAdapterViewHolder(view);
return mlistaIncidenciasTroncalAdapterViewHolder;
}
#Override
public void onBindViewHolder(ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder holder, final int position) {
final Incidencia incidencia= mLstIncidencia.get(position);
holder.tv_FechaRegistro.setText("Registro: "+incidencia.getFechaRegistro()+" - "+incidencia.getHoraRegistro());
holder.tv_Falla.setText(incidencia.getTipoFalla());
holder.tv_Estacion.setText(incidencia.getNomEstacion());
holder.tv_FechaSolucion.setText("Solucion: "+incidencia.getFechaSolucion()+" - "+incidencia.getHoraSolucion());
}
#Override
public int getItemCount() {
return mLstIncidencia.size();
}
static class ListaIncidenciasTroncalAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//private OnItemClickListener listener;
TextView tv_FechaRegistro, tv_Falla, tv_Estacion,tv_FechaSolucion;
LinearLayout linearLayout;
public DetalleIncidencia detalleincidencia;
public ListaIncidenciasTroncalAdapterViewHolder(View itemView) {
super(itemView);
tv_FechaRegistro= (TextView) itemView.findViewById(R.id.tvRegistro);
tv_Falla= (TextView) itemView.findViewById(R.id.tvFalla);
tv_Estacion= (TextView) itemView.findViewById(R.id.tvEstacion);
tv_FechaSolucion= (TextView) itemView.findViewById(R.id.tvSolucion);
final Context context = itemView.getContext();
//detalleincidencia=(DetalleIncidencia) itemView.findViewById(R.id.)
linearLayout=(LinearLayout) itemView.findViewById(R.id.linearItem);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
}}
And Finally this is the Entity (Incidencia)
public class Incidencia implements Parcelable {
private Integer id_incidencia;
private String FechaRegistroIncidencia;
private String NomRegistro;
private String FechaRegistro;;
private String HoraRegistro;
private int CodEstacion;
private String NomEstacion;
private int CodEquipo;
private String NomEquipo;
private String TipoFalla;
private int AtoramientoMoneda;
private int AtoramientoBillete;
private String HoraLlegadaEstacion;
private String Estado;
private String Observaciones;
private String FechaSolucion;
private String HoraSolucion;
public Integer getId_incidencia() {
return id_incidencia;
}
public void setId_incidencia(Integer id_incidencia) {
this.id_incidencia = id_incidencia;
}
public String getFechaRegistroIncidencia() {
return FechaRegistroIncidencia;
}
public void setFechaRegistroIncidencia(String fechaRegistroIncidencia) {
FechaRegistroIncidencia = fechaRegistroIncidencia;
}
public String getNomRegistro() {
return NomRegistro;
}
public void setNomRegistro(String nomRegistro) {
NomRegistro = nomRegistro;
}
public String getFechaRegistro() {
return FechaRegistro;
}
public void setFechaRegistro(String fechaRegistro) {
FechaRegistro = fechaRegistro;
}
public String getHoraRegistro() {
return HoraRegistro;
}
public void setHoraRegistro(String horaRegistro) {
HoraRegistro = horaRegistro;
}
public Integer getCodEstacion() {
return CodEstacion;
}
public void setCodEstacion(Integer codEstacion) {
CodEstacion = codEstacion;
}
public String getNomEstacion() {
return NomEstacion;
}
public void setNomEstacion(String nomEstacion) {
NomEstacion = nomEstacion;
}
public Integer getCodEquipo() {
return CodEquipo;
}
public void setCodEquipo(Integer codEquipo) {
CodEquipo = codEquipo;
}
public String getNomEquipo() {
return NomEquipo;
}
public void setNomEquipo(String nomEquipo) {
NomEquipo = nomEquipo;
}
public String getTipoFalla() {
return TipoFalla;
}
public void setTipoFalla(String tipoFalla) {
TipoFalla = tipoFalla;
}
public Integer getAtoramientoMoneda() {
return AtoramientoMoneda;
}
public void setAtoramientoMoneda(Integer atoramientoMoneda) {
AtoramientoMoneda = atoramientoMoneda;
}
public Integer getAtoramientoBillete() {
return AtoramientoBillete;
}
public void setAtoramientoBillete(Integer atoramientoBillete) {
AtoramientoBillete = atoramientoBillete;
}
public String getHoraLlegadaEstacion() {
return HoraLlegadaEstacion;
}
public void setHoraLlegadaEstacion(String horaLlegadaEstacion) {
HoraLlegadaEstacion = horaLlegadaEstacion;
}
public String getEstado() {
return Estado;
}
public void setEstado(String estado) {
Estado = estado;
}
public String getObservaciones() {
return Observaciones;
}
public void setObservaciones(String observaciones) {
Observaciones = observaciones;
}
public String getFechaSolucion() {
return FechaSolucion;
}
public void setFechaSolucion(String fechaSolucion) {
FechaSolucion = fechaSolucion;
}
public String getHoraSolucion() {
return HoraSolucion;
}
public void setHoraSolucion(String horaSolucion) {
HoraSolucion = horaSolucion;
}
public Incidencia(){}
protected Incidencia(Parcel in){
this.id_incidencia=in.readInt();;
this.FechaRegistroIncidencia=in.readString();
this.NomRegistro=in.readString();
this.FechaRegistro=in.readString();
this.HoraRegistro=in.readString();
this.CodEstacion=in.readInt();
this.NomEstacion=in.readString();
this.CodEquipo=in.readInt();
this.NomEquipo=in.readString();
this.TipoFalla=in.readString();
this.AtoramientoMoneda=in.readInt();
this.AtoramientoBillete=in.readInt();
this.HoraLlegadaEstacion=in.readString();
this.Estado=in.readString();
this.Observaciones=in.readString();
this.FechaSolucion=in.readString();
this.HoraSolucion=in.readString();
}
public static final Parcelable.Creator<Incidencia> CREATOR = new Parcelable.Creator<Incidencia>() {
#Override
public Incidencia createFromParcel(Parcel source) {
return new Incidencia(source);
}
#Override
public Incidencia[] newArray(int size) {
return new Incidencia[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.FechaRegistro);
dest.writeString(this.HoraRegistro);
dest.writeString(this.TipoFalla);
dest.writeString(this.FechaSolucion);
dest.writeString(this.HoraSolucion);
dest.writeString(this.NomEstacion);
}
}
You put the parcelable here
IngresoIncidenciaTroncalFragment fragment = new IngresoIncidenciaTroncalFragment();
Bundle args = new Bundle();
args.putParcelable("incident", incidencia);
But within IngresoIncidenciaTroncalFragment, you never got them.
Also, be sure to check the nullability of the arguments.
Bundle args = getArguments();
if (args != null) {
Incidencia incidencia = args.getParcelable("incident");
} else {
Log.w("GetIncidencia", "Arguments expected, but missing");
}
Also, you are missing many fields from writeToParcel that are being read into Incidencia(Parcel in), the first of which do not match, and the rest are out of order.
If you want to pass data between Fragments, see
How to implement OnFragmentInteractionListener
Communicating with Other Fragments
If both fragments in one Activity you just can use FragmentManager#findFragmentByTag(String) or FragmentManager#findFragmentById(int id) to get other fragment instance and just call some public method on that fragment to set entity.
Note that you should use either some tag or some container id when adding this fragments in order to be able to get them.
Try the update the Fragment like this
public class IngresoIncidenciaTroncalFragment extends Fragment implements
FechaDialog.DatePickerDialogFragmentEvents,HoraDialog.TimePickerDialogFragmentEvents ,FechaLlegadaDialog.DateLlegadaPickerDialogFragmentEvents{
private TextView mDateDisplay;
private TextView mTimeDisplay;
private Button botonAgregaIncidencia;
Context context;
private OnButtonClickedListener mListener;
private Spinner spinnerFallas;
public interface OnButtonClickedListener {
void onButtonClicked(Incidencia incidencia);
}
#Override
public void onAttach(Context context) {
if (context instanceOf OnButtonClickedListener) {
mListener = (OnButtonClickedListener) context;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate ingresoincidenciastroncal and setup Views.
*/
final View x = inflater.inflate(R.layout.ingresoincidenciastroncal,null);
context = x.getContext();
mHoraLLegadaEstacion=(TextView)x.findViewById(R.id.tvHoraLLegadaEstacion);
mObservaciones=(TextView)x.findViewById(R.id.tvObservaciones);
mFechaSolucion=(TextView)x.findViewById(R.id.tvFechaSolucion);
mHoraSolucion=(TextView)x.findViewById(R.id.tvHoraSolucion);
//ADD ENTITY BUTTON
botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//CREATING NEW ENTITY(Incidencia)
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro(mDateDisplay.toString());
incidencia.setHoraSolucion(mTimeDisplay.toString());
incidencia.setTipoFalla(spinnerFallas.getPrompt().toString());
//NEW ENTITY AS PAREMETER
if (mListener != null) {
mListener.onButtonClicked(incidencia);
}
}
});
return x;
}
}

RecyclerView (No adapter attached;skipping layout) using retrofit and fragment

Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView
Conexion Class
public class Conexion {
public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
EndPoint Interface
public interface EndPointsInterface {
#GET("chef/{idUser}")
Call<ChefResponse> GetChefsCercanos(#Path("idUser") Integer id_usuario);
}
Entity Usuario
public class Usuario {
#SerializedName("id_usuario")
private Integer id_usuario;
#SerializedName("NombreUsuario")
private String NombreUsuario;
#SerializedName("ApellidoUsuario")
private String ApellidoUsuario;
#SerializedName("TelefonoUsuario")
private String TelefonoUsuario;
#SerializedName("Email")
private String Email;
#SerializedName("Contraseña")
private String Contraseña;
#SerializedName("pos_x")
private Double pos_x;
#SerializedName("pos_y")
private Double pos_y;
public Usuario(){}
public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
this.id_usuario=id_usuario;
this.NombreUsuario=NombreUsuario;
this.ApellidoUsuario=ApellidoUsuario;
this.TelefonoUsuario=TelefonoUsuario;
this.Contraseña=Contraseña;
this.pos_x=pos_x;
this.pos_y=pos_y;
}
public Integer getId_usuario() {
return id_usuario;
}
public void setId_usuario(Integer id_usuario) {
this.id_usuario = id_usuario;
}
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
NombreUsuario = nombreUsuario;
}
public String getApellidoUsuario() {
return ApellidoUsuario;
}
public void setApellidoUsuario(String apellidoUsuario) {
ApellidoUsuario = apellidoUsuario;
}
public String getTelefonoUsuario() {
return TelefonoUsuario;
}
public void setTelefonoUsuario(String telefonoUsuario) {
TelefonoUsuario = telefonoUsuario;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getContraseña() {
return Contraseña;
}
public void setContraseña(String contraseña) {
Contraseña = contraseña;
}
public Double getPos_x() {
return pos_x;
}
public void setPos_x(Double pos_x) {
this.pos_x = pos_x;
}
public Double getPos_y() {
return pos_y;
}
public void setPos_y(Double pos_y) {
this.pos_y = pos_y;
}
}
Entity Chef
public class Chef extends Usuario{
#SerializedName("id_chef")
private Integer id_chef;
#SerializedName("TipoServicio")
private String TipoServicio;
#SerializedName("Rating")
private Double Rating;
#SerializedName("EstadoChef")
private Boolean EstadoChef;
public Chef(){}
public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
this.id_chef=id_chef;
this.TipoServicio=TipoServicio;
this.Rating=Rating;
this.EstadoChef=EstadoChef;
}
public Integer getId_chef() {
return id_chef;
}
public void setId_chef(Integer id_chef) {
this.id_chef = id_chef;
}
public String getTipoServicio() {
return TipoServicio;
}
public void setTipoServicio(String tipoServicio) {
TipoServicio = tipoServicio;
}
public Double getRating() {
return Rating;
}
public void setRating(Double rating) {
Rating = rating;
}
public Boolean getEstadoChef() {
return EstadoChef;
}
public void setEstadoChef(Boolean estadoChef) {
EstadoChef = estadoChef;
}
}
Chef Response
public class ChefResponse {
#SerializedName("results")
private Chef[] results;
public Chef[] getresults(){
return results;
}
}
RecyclerView Adapter
public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {
private List<Chef> chefs;
private List<Usuario> usuarios;
private int rowLayout;
private Context context;
#Override
public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ListaChefsCercanosViewHolder(view);
}
#Override
public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
holder.ratingchef.setText(chefs.get(position).getRating().toString());
}
#Override
public int getItemCount() {
return chefs.size();
}
public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
LinearLayout chefslayout;
TextView nombreschefscerca;
TextView ratingchef;
public ListaChefsCercanosViewHolder(View v){
super(v);
chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
}
}
public ListaChefsCercanos(ArrayList <Chef> chefs){
this.chefs=chefs;
//this.rowLayout = rowLayout;
//this.context = context;
}
}
and the fragment
public class RecomendadosFragment extends Fragment {
private RatingBar ratingBar;
//ListAdapter adapter;
ArrayList<Chef> listachef;
ListView lvLista;
String tag_json_array="jarray req";
RecyclerView recyclerviewChefsCarnos;
ListaChefsCercanos mListaChefsCercanos;
private ArrayList<Chef> data;
private ListaChefsCercanos adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.recomendados,null);
//ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);
Call<ChefResponse> call = apiService.GetChefsCercanos(5);
call.enqueue(new Callback<ChefResponse>() {
#Override
public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
ChefResponse jsonResponse = response.body();
if(jsonResponse != null) {
data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
adapter= new ListaChefsCercanos(data);
recyclerviewChefsCarnos.setAdapter(adapter);
}
} else {
// Do whatever you want if API is unsuccessful.
}
// List<Chef> chefs= response.body().getResults();
// recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
}
#Override
public void onFailure(Call<ChefResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
return x;
}
this is the error I found while Im debuging
E/RecyclerView: No adapter attached; skipping layout
Update: Use a empty adapter for the RecyclerView in the OncreateView()
recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));

mTracks size is 0 I Do not know why retrieve returns null

1- MainActivity:
public class MainActivity extends AppCompatActivity {
private List<String> mListItems = Arrays.asList("Hamaki","Amr Diab");
private ArtistsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.Artist_list_view);
mAdapter = new ArtistsAdapter(this, mListItems);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,SoundActivity.class);
intent.putExtra("Artist", mListItems.get(position));
startActivity(intent);
}
});
}
}
2-Sound Activity:
public class SoundActivity extends AppCompatActivity {
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new SoundFragment()).commit();
}
}
3-Sound Fragment:
public class SoundFragment extends Fragment {
static SCTrackAdapter mAdapter;
static DatabaseReference db;
static FirebaseHelper helper;
private TextView mSelectedTrackTitle;
static ArrayList<Music> mTracks = new ArrayList<>();
static MediaPlayer mMediaPlayer;
private ImageView mPlayerControl;
static String Artist;
static ListView listView;
int currentTrack;
private static String fileName;
public SoundFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
new Fetchtracks().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sound, container, false);
Intent intent = getActivity().getIntent();
if (intent != null) {
Artist = intent.getStringExtra("Artist");
}
listView = (ListView) rootView.findViewById(R.id.track_list_view);
mAdapter = new SCTrackAdapter(getActivity(), mTracks);
listView.setAdapter(mAdapter);
return rootView;
}
4- STrack Adapter:
public class SCTrackAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Music> mTracks;
public SCTrackAdapter(Context context, ArrayList<Music> tracks) {
mContext = context;
mTracks = tracks;
}
public void update_tracks(ArrayList<Music> list)
{
mTracks.clear();
mTracks.addAll(list);
}
#Override
public int getCount() {
return mTracks.size();
}
#Override
public Music getItem(int position) {
return mTracks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.track_list_row, parent, false);
holder = new ViewHolder();
holder.titleTextView = (TextView) convertView.findViewById(R.id.track_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleTextView.setText(mTracks.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView titleTextView;
}
}
5- Fetchtracks:
public class Fetchtracks extends AsyncTask<Void, Void, ArrayList<Music>> {
#Override
protected ArrayList<Music> doInBackground(Void... voids) {
db = FirebaseDatabase.getInstance().getReference().child(Artist);
helper = new FirebaseHelper(db);
mTracks.addAll(helper.retrieve());
Log.e("doInBackground: ",helper.retrieve()+"");
return mTracks;
}
#Override
protected void onPostExecute(ArrayList<Music> list) {
super.onPostExecute(list);
Log.e("doInBackground: ",list.size()+"");
mAdapter.update_tracks(list);
mAdapter.notifyDataSetChanged();
}
}
6- FirebaseHelper:
public class FirebaseHelper {
DatabaseReference db;
Boolean saved=null;
ArrayList<Music> A = new ArrayList<>();
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//WRITE
public Boolean save(Music m)
{
if(m==null)
{
saved=false;
}else
{
try
{
// db.child(Artist).push().setValue(m);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<Music> retrieve()
{
A.clear();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "1");
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("onChildAdded: ", "2");
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// Log.e("onChildAdded: ", "3");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
// Log.e("onChildAdded: ", "4");
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e("onChildAdded: ", "5");
}
});
return A;
}
private void fetchData(DataSnapshot dataSnapshot)
{
Music m=new Music();
m.setName(dataSnapshot.child("name").getValue().toString());
m.setUrl(dataSnapshot.child("url").getValue().toString());
A.add(m);
// SoundFragment.mTracks.add(m);
// Log.e("onFetch: ", SoundFragment.mTracks.size()+"");
}
}
7- Music:
public class Music {
String name;
String url;
public Music() {
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public String getURL() {
return url;
}
}
no need to call this in onPostExecute() as it is only set
listView.setAdapter(mAdapter);

Using itemClickListener to pass data from api call to another fragment

I have a list of data from my API call into my RecyclerView. I have an itemClickListener interface that opens a new fragment with item image and details.
When I click on the item, I need to pass data to the 2nd fragment and it's adapter. How will it work?
Do I need to send this data with a bundle and then make another API call inside my 2nd fragment? Or just the bundle with data which I can use without an additional API call?
This is my model:
public class Products {
private String productId;
private String productName;
private String shortDescription;
private String longDescription;
private String price;
#SerializedName("productImage")
private String image;
#SerializedName("reviewRating")
private double rating;
private int reviewCount;
private boolean inStock;
public String getProductId() {
return productId;
}
public String getProductName() {
return productName;
}
public String getShortDescription() {
return shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public String getPrice() {
return price;
}
public String getImage() {
return image;
}
public double getRating() {
return rating;
}
public int getReviewCount() {
return reviewCount;
}
public boolean isInStock() {
return inStock;
}
}
this is my MainFragment:
private void setBundle(int position) {
args = new Bundle();
String[] clickedItem = {apiProducts.get(position).getImage(),
apiProducts.get(position).getLongDescription(),
String.valueOf(apiProducts.get(position).isInStock())};
args.putStringArray("Item", clickedItem);
}
private void productsClickListener() {
if (apiObjectAdapter != null) {
apiObjectAdapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View itemView, int position) {
setBundle(position);
setDetailsFragment(args);
}
});
}
}
My adapter:
public class ApiObjectAdapter extends RecyclerView.Adapter<ApiObjectAdapter.MyViewHolder> {
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.product_name)
public TextView name;
#BindView(R.id.product_rating)
public TextView rating;
#BindView(R.id.product_price)
public TextView price;
public MyViewHolder(final View view) {
super(view);
this.parentView = view;
try {
ButterKnife.bind(this, view);
} catch (Exception e) {
e.printStackTrace();
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(view, getLayoutPosition());
}
});
}
}
Using bundle
form sender put data as
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
and in next receiver receive as
Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);
more detail about https://developer.android.com/reference/android/os/Bundle.html

Retrofit passing specific json nested objects to next activity

I have a JSON nested object and i have been trying to pass for example, stations "name" to next activity in the onClick method. 2 questions:
1) Have i set my model class right or is there a better way?
2) What steps am i missing to pass "name" from stations from the specific object clicked onto the next activity?
My error for code provided (
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.ogure.trolleyproject.Adapter.StationsAdapter$ViewHolder.onClick(StationsAdapter.java:52)
Here is my JSON nested object
{
id: 1,
name: "Bus 1",
code: "TROL1",
tag_uid: "2HF4780H240827H40F284",
last_spotted_at: "2015-09-25 01:20:30",
last_spotted_station: 1,
stations: [
{
id: 1,
name: "Hennings Hall Station", //WHAT i want to pass
lat: "40.000000",
long: "41.000000",
_pivot_bus_id: 1,
_pivot_station_id: 1
}
}
Here is my model class
public class Bus implements Serializable {
#SerializedName("id")
private int mStationId;
#SerializedName("name")
private String mStationName;
#SerializedName("code")
private String mStationCode;
#SerializedName("tag_uid")
private String mStationTag_uid;
#SerializedName("last_spotted_at")
private String mStationLast_spot_time;
#SerializedName("last_spotted_station")
private int mStationLast_spot_station;
#SerializedName("stations")
private List<stations> stationInfo;
public int getmStationId() {
return mStationId;
}
public void setmStationId(int mStationId) {
this.mStationId = mStationId;
}
public List<stations> getStationInfo() {
return stationInfo;
}
public void setStationInfo(List<stations> stationInfo) {
this.stationInfo = stationInfo;
}
public int getmStationLast_spot_station() {
return mStationLast_spot_station;
}
public void setmStationLast_spot_station(int mStationLast_spot_station) {
this.mStationLast_spot_station = mStationLast_spot_station;
}
public String getmStationLast_spot_time() {
return mStationLast_spot_time;
}
public void setmStationLast_spot_time(String mStationLast_spot_time) {
this.mStationLast_spot_time = mStationLast_spot_time;
}
public String getmStationTag_uid() {
return mStationTag_uid;
}
public void setmStationTag_uid(String mStationTag_uid) {
this.mStationTag_uid = mStationTag_uid;
}
public String getmStationCode() {
return mStationCode;
}
public void setmStationCode(String mStationCode) {
this.mStationCode = mStationCode;
}
public String getmStationName() {
return mStationName;
}
public void setmStationName(String mStationName) {
this.mStationName = mStationName;
}
public class stations {
#SerializedName("id")
private int stationID;
#SerializedName("name")
private String stationName;
#SerializedName("lat")
private double stationLat;
#SerializedName("long")
private double stationLong;
#SerializedName("_pivot_bus_id")
private int mStationPiviotBusId;
#SerializedName("_pivot_station_id")
private int mStationPiviotStationId;
public int getmStationPiviotStationId() {
return mStationPiviotStationId;
}
public void setmStationPiviotStationId(int mStationPiviotStationId) {
this.mStationPiviotStationId = mStationPiviotStationId;
}
public int getmStationPiviotBusId() {
return mStationPiviotBusId;
}
public void setmStationPiviotBusId(int mStationPiviotBusId) {
this.mStationPiviotBusId = mStationPiviotBusId;
}
public double getStationLong() {
return stationLong;
}
public void setStationLong(double stationLong) {
this.stationLong = stationLong;
}
public double getStationLat() {
return stationLat;
}
public void setStationLat(double stationLat) {
this.stationLat = stationLat;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
public int getStationID() {
return stationID;
}
public void setStationID(int stationID) {
this.stationID = stationID;
}
}
}
Here is my adapter class
public class StationsAdapter extends RecyclerView.Adapter<StationsAdapter.ViewHolder> {
private static List<Bus> mStations;
private static List<Bus.stations> mBusStations;
public StationsAdapter(List<Bus> stations) {
mStations = stations;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView TvStationName;
public ImageView IvImageView;
public CardView mCardView;
public ViewHolder(View itemView) {
super(itemView);
TvStationName = (TextView) itemView.findViewById(R.id.station_name);
IvImageView = (ImageView) itemView.findViewById(R.id.station_photo);
mCardView = (CardView) itemView.findViewById(R.id.cv);
mCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Bus s = mStations.get(position);
Bus.stations og = mBusStations.get(position); //HERE
Intent i = new Intent(v.getContext(), StationActivity.class);
i.putExtra("station_name", og.getStationName()); //and HERE is my problem
v.getContext().startActivity(i);
}
}
#Override
public StationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_card_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(StationsAdapter.ViewHolder holder, int position) {
Bus stationPos = mStations.get(position);
holder.TvStationName.setText(stationPos.getmStationName());
holder.mCardView.setTag(position);
}
#Override
public int getItemCount() {
return mStations.size();
}
Change your code to following:
public StationsAdapter(List<Bus> stations) {
List<Bus.stations> busStations = new ArrayList<>();
for (Bus bus : stations) {
busStations.addAll(bus.getStationInfo());
}
}
Issue is that you don't assign nothing to your mBusStations variable, that's why NPE throws.
Btw, don't use that confusing naming. Im talking about stationInfo in your Bus class.

Categories

Resources